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/Body.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.jimple.IdentityStmt; import soot.jimple.ParameterRef; import soot.jimple.ThisRef; import soot.options.Options; import soot.tagkit.AbstractHost; import soot.tagkit.CodeAttribute; import soot.tagkit.Tag; import soot.util.Chain; import soot.util.EscapedWriter; import soot.util.HashChain; import soot.validation.BodyValidator; import soot.validation.CheckEscapingValidator; import soot.validation.CheckInitValidator; import soot.validation.CheckTypesValidator; import soot.validation.CheckVoidLocalesValidator; import soot.validation.LocalsValidator; import soot.validation.TrapsValidator; import soot.validation.UnitBoxesValidator; import soot.validation.UsesValidator; import soot.validation.ValidationException; import soot.validation.ValueBoxesValidator; /** * Abstract base class that models the body (code attribute) of a Java method. Classes that implement an Intermediate * Representation for a method body should subclass it. In particular the classes GrimpBody, JimpleBody and BafBody all * extend this class. This class provides methods that are common to any IR, such as methods to get the body's units * (statements), traps, and locals. * * @see soot.grimp.GrimpBody * @see soot.jimple.JimpleBody * @see soot.baf.BafBody */ @SuppressWarnings("serial") public abstract class Body extends AbstractHost implements Serializable { private static final Logger logger = LoggerFactory.getLogger(Body.class); /** * The method associated with this Body. */ protected transient SootMethod method = null; /** * The chain of locals for this Body. */ protected Chain<Local> localChain = new HashChain<>(); /** * The chain of traps for this Body. */ protected Chain<Trap> trapChain = new HashChain<>(); /** * The chain of units for this Body. */ protected UnitPatchingChain unitChain = new UnitPatchingChain(new HashChain<>()); /** * Lazy initialized array containing some validators in order to validate the Body. */ private static class LazyValidatorsSingleton { static final BodyValidator[] V = new BodyValidator[] { LocalsValidator.v(), TrapsValidator.v(), UnitBoxesValidator.v(), UsesValidator.v(), ValueBoxesValidator.v(), /* CheckInitValidator.v(), */ CheckTypesValidator.v(), CheckVoidLocalesValidator.v(), CheckEscapingValidator.v() }; private LazyValidatorsSingleton() { } } /** * Creates a deep copy of this Body. * * @return */ @Override abstract public Object clone(); /** * Creates a Body associated to the given method. Used by subclasses during initialization. Creation of a Body is triggered * by e.g. Jimple.v().newBody(options). * * @param m */ protected Body(SootMethod m) { this.method = m; } /** * Creates an extremely empty Body. The Body is not associated to any method. */ protected Body() { } /** * Returns the method associated with this Body. * * @return the method that owns this body. */ public SootMethod getMethod() { if (method == null) { throw new RuntimeException("no method associated w/ body"); } return method; } /** * Returns the method associated with this Body. * * @return the method that owns this body. */ public SootMethod getMethodUnsafe() { return method; } /** * Sets the method associated with this Body. * * @param method * the method that owns this body. */ public void setMethod(SootMethod method) { this.method = method; } /** * Returns the number of locals declared in this body. * * @return */ public int getLocalCount() { return localChain.size(); } /** * Copies the contents of the given Body into this one. * * @param b * * @return */ public Map<Object, Object> importBodyContentsFrom(Body b) { HashMap<Object, Object> bindings = new HashMap<>(); // Clone units in body's statement list for (Unit original : b.getUnits()) { Unit copy = (Unit) original.clone(); copy.addAllTagsOf(original); // Add cloned unit to our unitChain. unitChain.addLast(copy); // Build old <-> new map to be able to patch up references to other units // within the cloned units. (these are still refering to the original // unit objects). bindings.put(original, copy); } // Clone trap units. for (Trap original : b.getTraps()) { Trap copy = (Trap) original.clone(); // Add cloned unit to our trap list. trapChain.addLast(copy); // Store old <-> new mapping. bindings.put(original, copy); } // Clone local units. for (Local original : b.getLocals()) { Local copy = (Local) original.clone(); // Add cloned unit to our trap list. localChain.addLast(copy); // Build old <-> new mapping. bindings.put(original, copy); } // Patch up references within units using our (old <-> new) map. for (UnitBox box : getAllUnitBoxes()) { Unit newObject = (Unit) bindings.get(box.getUnit()); // if we have a reference to an old object, replace it with its clone. if (newObject != null) { box.setUnit(newObject); } } { // backpatching all local variables. for (ValueBox vb : getUseBoxes()) { Value val = vb.getValue(); if (val instanceof Local) { vb.setValue((Value) bindings.get(val)); } } for (ValueBox vb : getDefBoxes()) { Value val = vb.getValue(); if (val instanceof Local) { vb.setValue((Value) bindings.get(val)); } } } return bindings; } protected void runValidation(BodyValidator validator) { final List<ValidationException> exceptionList = new ArrayList<>(); validator.validate(this, exceptionList); if (!exceptionList.isEmpty()) { throw exceptionList.get(0); } } /** * Verifies a few sanity conditions on the contents on this body. */ public void validate() { List<ValidationException> exceptionList = new ArrayList<>(); validate(exceptionList); if (!exceptionList.isEmpty()) { throw exceptionList.get(0); } } /** * Validates the jimple body and saves a list of all validation errors * * @param exceptionList * the list of validation errors */ public void validate(List<ValidationException> exceptionList) { final boolean runAllValidators = Options.v().debug() || Options.v().validate(); for (BodyValidator validator : LazyValidatorsSingleton.V) { if (!validator.isBasicValidator() && !runAllValidators) { continue; } validator.validate(this, exceptionList); } } /** * Verifies that a ValueBox is not used in more than one place. */ public void validateValueBoxes() { runValidation(ValueBoxesValidator.v()); } /** * Verifies that each Local of {@link #getUseAndDefBoxes()} is in this body's locals Chain. */ public void validateLocals() { runValidation(LocalsValidator.v()); } /** * Verifies that the begin, end and handler units of each trap are in this body. */ public void validateTraps() { runValidation(TrapsValidator.v()); } /** * Verifies that the UnitBoxes of this Body all point to a Unit contained within this body. */ public void validateUnitBoxes() { runValidation(UnitBoxesValidator.v()); } /** * Verifies that each use in this Body has a def. */ public void validateUses() { runValidation(UsesValidator.v()); } public void checkInit() { runValidation(CheckInitValidator.v()); } /** * Returns a backed chain of the locals declared in this Body. * * @return */ public Chain<Local> getLocals() { return localChain; } /** * Returns a backed view of the traps found in this Body. * * @return */ public Chain<Trap> getTraps() { return trapChain; } /** * Return unit containing the \@this-assignment * * @return */ public Unit getThisUnit() { for (Unit u : getUnits()) { if (u instanceof IdentityStmt && ((IdentityStmt) u).getRightOp() instanceof ThisRef) { return u; } } throw new RuntimeException("couldn't find this-assignment!" + " in " + getMethod()); } /** * Return LHS of the first identity stmt assigning from \@this. * * @return */ public Local getThisLocal() { return (Local) (((IdentityStmt) getThisUnit()).getLeftOp()); } /** * Return LHS of the first identity stmt assigning from \@parameter i. * * @param i * * @return */ public Local getParameterLocal(int i) { for (Unit s : getUnits()) { if (s instanceof IdentityStmt) { IdentityStmt is = (IdentityStmt) s; Value rightOp = is.getRightOp(); if (rightOp instanceof ParameterRef) { ParameterRef pr = (ParameterRef) rightOp; if (pr.getIndex() == i) { return (Local) is.getLeftOp(); } } } } throw new RuntimeException("couldn't find parameterref" + i + " in " + getMethod()); } /** * Get all the LHS of the identity statements assigning from parameter references. * * @return a list of size as per <code>getMethod().getParameterCount()</code> with all elements ordered as per the * parameter index. * * @throws RuntimeException * if a parameterref is missing */ public List<Local> getParameterLocals() { final int numParams = getMethod().getParameterCount(); Local[] res = new Local[numParams]; int numFound = 0; for (Unit u : getUnits()) { if (u instanceof IdentityStmt) { IdentityStmt is = (IdentityStmt) u; Value rightOp = is.getRightOp(); if (rightOp instanceof ParameterRef) { int idx = ((ParameterRef) rightOp).getIndex(); if (res[idx] != null) { throw new RuntimeException("duplicate parameterref" + idx + " in " + getMethod()); } res[idx] = (Local) is.getLeftOp(); numFound++; if (numFound >= numParams) { break; } } } } if (numFound != numParams) { for (int i = 0; i < numParams; i++) { if (res[i] == null) { throw new RuntimeException("couldn't find parameterref" + i + " in " + getMethod()); } } throw new RuntimeException("couldn't find parameterref? in " + getMethod()); } return Arrays.asList(res); } /** * Returns the list of parameter references used in this body. The list is as long as the number of parameters declared in * the associated method's signature. The list may have <code>null</code> entries for parameters not referenced in the * body. The returned list is of fixed size. * * @return */ public List<Value> getParameterRefs() { final int numParams = getMethod().getParameterCount(); Value[] res = new Value[numParams]; int numFound = 0; for (Unit u : getUnits()) { if (u instanceof IdentityStmt) { Value rightOp = ((IdentityStmt) u).getRightOp(); if (rightOp instanceof ParameterRef) { ParameterRef pr = (ParameterRef) rightOp; int idx = pr.getIndex(); if (res[idx] != null) { throw new RuntimeException("duplicate parameterref" + idx + " in " + getMethod()); } res[idx] = pr; numFound++; if (numFound >= numParams) { break; } } } } return Arrays.asList(res); } /** * Returns the Chain of Units that make up this body. The units are returned as a PatchingChain. The client can then * manipulate the chain, adding and removing units, and the changes will be reflected in the body. Since a PatchingChain is * returned the client need <i>not</i> worry about removing exception boundary units or otherwise corrupting the chain. * * @return the units in this Body * * @see PatchingChain * @see Unit */ public UnitPatchingChain getUnits() { return unitChain; } /** * Returns the result of iterating through all Units in this body and querying them for their UnitBoxes. All UnitBoxes thus * found are returned. Branching Units and statements which use PhiExpr will have UnitBoxes; a UnitBox contains a Unit that * is either a target of a branch or is being used as a pointer to the end of a CFG block. * * <p> * This method is typically used for pointer patching, eg when the unit chain is cloned. * * @return A list of all the UnitBoxes held by this body's units. * * @see UnitBox * @see #getUnitBoxes(boolean) * @see Unit#getUnitBoxes() * @see soot.shimple.PhiExpr#getUnitBoxes() */ public List<UnitBox> getAllUnitBoxes() { ArrayList<UnitBox> unitBoxList = new ArrayList<>(); for (Unit item : unitChain) { unitBoxList.addAll(item.getUnitBoxes()); } for (Trap item : trapChain) { unitBoxList.addAll(item.getUnitBoxes()); } for (Tag t : getTags()) { if (t instanceof CodeAttribute) { unitBoxList.addAll(((CodeAttribute) t).getUnitBoxes()); } } return unitBoxList; } /** * If branchTarget is true, returns the result of iterating through all branching Units in this body and querying them for * their UnitBoxes. These UnitBoxes contain Units that are the target of a branch. This is useful for, say, labeling blocks * or updating the targets of branching statements. * * <p> * If branchTarget is false, returns the result of iterating through the non-branching Units in this body and querying them * for their UnitBoxes. Any such UnitBoxes (typically from PhiExpr) contain a Unit that indicates the end of a CFG block. * * @param branchTarget * * @return a list of all the UnitBoxes held by this body's branching units. * * @see UnitBox * @see #getAllUnitBoxes() * @see Unit#getUnitBoxes() * @see soot.shimple.PhiExpr#getUnitBoxes() */ public List<UnitBox> getUnitBoxes(boolean branchTarget) { ArrayList<UnitBox> unitBoxList = new ArrayList<>(); for (Unit item : unitChain) { if (item.branches() == branchTarget) { unitBoxList.addAll(item.getUnitBoxes()); } } for (Trap item : trapChain) { unitBoxList.addAll(item.getUnitBoxes()); } for (Tag t : getTags()) { if (t instanceof CodeAttribute) { unitBoxList.addAll(((CodeAttribute) t).getUnitBoxes()); } } return unitBoxList; } /** * Returns the result of iterating through all Units in this body and querying them for ValueBoxes used. All of the * ValueBoxes found are then returned as a List. * * @return a list of all the ValueBoxes for the Values used this body's units. * * @see Value * @see Unit#getUseBoxes * @see ValueBox * @see Value */ public List<ValueBox> getUseBoxes() { ArrayList<ValueBox> useBoxList = new ArrayList<>(); for (Unit item : unitChain) { useBoxList.addAll(item.getUseBoxes()); } return useBoxList; } /** * Returns the result of iterating through all Units in this body and querying them for ValueBoxes defined. All of the * ValueBoxes found are then returned as a List. * * @return a list of all the ValueBoxes for Values defined by this body's units. * * @see Value * @see Unit#getDefBoxes * @see ValueBox * @see Value */ public List<ValueBox> getDefBoxes() { ArrayList<ValueBox> defBoxList = new ArrayList<>(); for (Unit item : unitChain) { defBoxList.addAll(item.getDefBoxes()); } return defBoxList; } /** * Returns a list of boxes corresponding to Values either used or defined in any unit of this Body. * * @return a list of ValueBoxes for held by the body's Units. * * @see Value * @see Unit#getUseAndDefBoxes * @see ValueBox * @see Value */ public List<ValueBox> getUseAndDefBoxes() { ArrayList<ValueBox> useAndDefBoxList = new ArrayList<>(); for (Unit item : unitChain) { useAndDefBoxList.addAll(item.getUseBoxes()); useAndDefBoxList.addAll(item.getDefBoxes()); } return useAndDefBoxList; } /** * {@inheritDoc} */ @Override public String toString() { ByteArrayOutputStream streamOut = new ByteArrayOutputStream(); try (PrintWriter writerOut = new PrintWriter(new EscapedWriter(new OutputStreamWriter(streamOut)))) { Printer.v().printTo(this, writerOut); writerOut.flush(); } catch (RuntimeException e) { logger.error(e.getMessage(), e); } return streamOut.toString(); } public long getModificationCount() { return localChain.getModificationCount() + unitChain.getModificationCount() + trapChain.getModificationCount(); } }
18,028
28.363192
125
java
soot
soot-master/src/main/java/soot/BodyPack.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai and 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.options.Options; import soot.toolkits.graph.interaction.InteractionHandler; /** * A wrapper object for a pack of optimizations. Provides chain-like operations, except that the key is the phase name. */ public class BodyPack extends Pack { private static final Logger logger = LoggerFactory.getLogger(BodyPack.class); public BodyPack(String name) { super(name); } @Override protected void internalApply(Body b) { final boolean interactive_mode = Options.v().interactive_mode(); for (Transform t : this) { if (interactive_mode) { // logger.debug("sending transform: "+t.getPhaseName()+" for body: "+b+" for body pack: "+this.getPhaseName()); InteractionHandler.v().handleNewAnalysis(t, b); } t.apply(b); if (interactive_mode) { InteractionHandler.v().handleTransformDone(t, b); } } } }
1,779
30.785714
119
java
soot
soot-master/src/main/java/soot/BodyTransformer.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 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.Collections; import java.util.Map; /** * An abstract class which acts on a Body. This class provides a harness and acts as an interface for classes that wish to * transform a Body. Subclasses provide the actual Body transformation implementation. */ public abstract class BodyTransformer extends Transformer { private static final Map<String, String> enabledOnlyMap = Collections.singletonMap("enabled", "true"); /** * Called by clients of the transformation. Acts as a generic interface for BodyTransformers. Calls internalTransform with * the optionsString properly set up. That is, the options in optionsString override those in the Scene. * * @param b * the body on which to apply the transformation * @param phaseName * phaseName for the transform. Used to retrieve options from the Scene. */ public final void transform(Body b, String phaseName, Map<String, String> options) { if (PhaseOptions.getBoolean(options, "enabled")) { internalTransform(b, phaseName, options); } } public final void transform(Body b, String phaseName) { internalTransform(b, phaseName, enabledOnlyMap); } public final void transform(Body b) { transform(b, ""); } /** * This method is called to perform the transformation itself. It is declared abstract; subclasses must implement this * method by making it the entry point to their actual Body transformation. * * @param b * the body on which to apply the transformation * @param phaseName * the phasename for this transform; not typically used by implementations. * @param options * the actual computed options; a combination of default options and Scene specified options. */ protected abstract void internalTransform(Body b, String phaseName, Map<String, String> options); }
2,696
35.945205
124
java
soot
soot-master/src/main/java/soot/BooleanType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java built-in type 'boolean'. Implemented as a singleton. */ @SuppressWarnings("serial") public class BooleanType extends PrimType implements IntegerType { public static final int HASHCODE = 0x1C4585DA; public BooleanType(Singletons.Global g) { } public static BooleanType v() { return G.v().soot_BooleanType(); } @Override public boolean equals(Object t) { return this == t; } @Override public int hashCode() { return HASHCODE; } @Override public String toString() { return "boolean"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseBooleanType(this); } @Override public RefType boxedType() { return RefType.v("java.lang.Boolean"); } @Override public Class<?> getJavaBoxedType() { return Boolean.class; } @Override public Class<?> getJavaPrimitiveType() { return boolean.class; } }
1,777
22.090909
87
java
soot
soot-master/src/main/java/soot/BriefUnitPrinter.java
package soot; /*- * #%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 soot.jimple.CaughtExceptionRef; import soot.jimple.IdentityRef; import soot.jimple.Jimple; import soot.jimple.ParameterRef; import soot.jimple.Stmt; import soot.jimple.ThisRef; /** * UnitPrinter implementation for normal (full) Jimple, Grimp, and Baf */ public class BriefUnitPrinter extends LabeledUnitPrinter { private boolean baf; public BriefUnitPrinter(Body body) { super(body); } @Override public void startUnit(Unit u) { super.startUnit(u); baf = !(u instanceof Stmt); } @Override public void methodRef(SootMethodRef m) { handleIndent(); if (!baf && m.resolve().isStatic()) { output.append(m.getDeclaringClass().getName()); literal("."); } output.append(m.name()); } @Override public void fieldRef(SootFieldRef f) { handleIndent(); if (baf || f.resolve().isStatic()) { output.append(f.declaringClass().getName()); literal("."); } output.append(f.name()); } @Override public void identityRef(IdentityRef r) { handleIndent(); if (r instanceof ThisRef) { literal("@this"); } else if (r instanceof ParameterRef) { ParameterRef pr = (ParameterRef) r; literal("@parameter" + pr.getIndex()); } else if (r instanceof CaughtExceptionRef) { literal("@caughtexception"); } else { throw new RuntimeException(); } } private boolean eatSpace = false; @Override public void literal(String s) { handleIndent(); if (eatSpace && " ".equals(s)) { eatSpace = false; return; } eatSpace = false; if (!baf) { switch (s) { case Jimple.STATICINVOKE: case Jimple.VIRTUALINVOKE: case Jimple.INTERFACEINVOKE: eatSpace = true; return; } } output.append(s); } @Override public void type(Type t) { handleIndent(); output.append(t.toString()); } }
2,732
23.401786
71
java
soot
soot-master/src/main/java/soot/ByteType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java built-in type 'byte'. Implemented as a singleton. */ @SuppressWarnings("serial") public class ByteType extends PrimType implements IntegerType { public static final int HASHCODE = 0x813D1329; public ByteType(Singletons.Global g) { } public static ByteType v() { return G.v().soot_ByteType(); } @Override public int hashCode() { return HASHCODE; } @Override public boolean equals(Object t) { return this == t; } @Override public String toString() { return "byte"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseByteType(this); } @Override public RefType boxedType() { return RefType.v("java.lang.Byte"); } @Override public Class<?> getJavaBoxedType() { return Byte.class; } @Override public Class<?> getJavaPrimitiveType() { return byte.class; } }
1,747
21.701299
84
java
soot
soot-master/src/main/java/soot/CharType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java built-in type 'char'. Implemented as a singleton. */ @SuppressWarnings("serial") public class CharType extends PrimType implements IntegerType { public static final int HASHCODE = 0x739EA474; public CharType(Singletons.Global g) { } public static CharType v() { return G.v().soot_CharType(); } @Override public boolean equals(Object t) { return this == t; } @Override public String toString() { return "char"; } @Override public int hashCode() { return HASHCODE; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseCharType(this); } @Override public RefType boxedType() { return RefType.v("java.lang.Character"); } @Override public Class<?> getJavaBoxedType() { return Character.class; } @Override public Class<?> getJavaPrimitiveType() { return char.class; } }
1,757
21.831169
84
java
soot
soot-master/src/main/java/soot/ClassMember.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Provides methods common to Soot objects belonging to classes, namely SootField and SootMethod. */ public interface ClassMember { /** Returns the SootClass declaring this one. */ public SootClass getDeclaringClass(); /** Returns true when some SootClass object declares this object. */ public boolean isDeclared(); /** Returns true when this object is from a phantom class. */ public boolean isPhantom(); /** Sets the phantom flag */ public void setPhantom(boolean value); /** Convenience method returning true if this class member is protected. */ public boolean isProtected(); /** Convenience method returning true if this class member is private. */ public boolean isPrivate(); /** Convenience method returning true if this class member is public. */ public boolean isPublic(); /** Convenience method returning true if this class member is static. */ public boolean isStatic(); /** Sets modifiers of this class member. */ public void setModifiers(int modifiers); /** Returns modifiers of this class member. */ public int getModifiers(); }
1,921
31.033333
97
java
soot
soot-master/src/main/java/soot/ClassProvider.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A class provider looks for a file of a specific format for a specified class, and returns a ClassSource for it if it finds * it. */ public interface ClassProvider { /** * Look for the specified class. Return a ClassSource for it if found, or null if it was not found. */ public abstract ClassSource find(String className); }
1,157
32.085714
125
java
soot
soot-master/src/main/java/soot/ClassSource.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.javaToJimple.IInitialResolver.Dependencies; /** * A class source is responsible for resolving a single class from a particular source format (.class, .jimple, .java, etc.) */ public abstract class ClassSource { protected final String className; public ClassSource(String className) { if (className == null) { throw new IllegalStateException("Error: The class name must not be null."); } this.className = className; } /** * Resolve the class into the SootClass sc. Returns a list of Strings or Types referenced by the class. */ public abstract Dependencies resolve(SootClass sc); public void close() { } }
1,475
29.122449
124
java
soot
soot-master/src/main/java/soot/CoffiClassProvider.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A class provider looks for a file of a specific format for a specified class, and returns a ClassSource for it if it finds * it. */ public class CoffiClassProvider implements ClassProvider { /** * Look for the specified class. Return a ClassSource for it if found, or null if it was not found. */ @Override public ClassSource find(String className) { String fileName = className.replace('.', '/') + ".class"; FoundFile file = SourceLocator.v().lookupInClassPath(fileName); return (file == null) ? null : new CoffiClassSource(className, file); } }
1,395
33.9
125
java
soot
soot-master/src/main/java/soot/CoffiClassSource.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.javaToJimple.IInitialResolver; import soot.javaToJimple.IInitialResolver.Dependencies; import soot.options.Options; import soot.tagkit.SourceFileTag; /** * A class source for resolving from .class files through coffi. */ public class CoffiClassSource extends ClassSource { private static final Logger logger = LoggerFactory.getLogger(CoffiClassSource.class); private FoundFile foundFile; private InputStream classFile; private final String fileName; private final String zipFileName; public CoffiClassSource(String className, FoundFile foundFile) { super(className); if (foundFile == null) { throw new IllegalStateException("Error: The FoundFile must not be null."); } this.foundFile = foundFile; this.classFile = foundFile.inputStream(); this.fileName = foundFile.getFile().getAbsolutePath(); this.zipFileName = !foundFile.isZipFile() ? null : foundFile.getFilePath(); } public CoffiClassSource(String className, InputStream classFile, String fileName) { super(className); if (classFile == null || fileName == null) { throw new IllegalStateException("Error: The class file input strean and file name must not be null."); } this.classFile = classFile; this.fileName = fileName; this.zipFileName = null; this.foundFile = null; } @Override public Dependencies resolve(SootClass sc) { if (Options.v().verbose()) { logger.debug("resolving [from .class]: " + className); } List<Type> references = new ArrayList<Type>(); try { soot.coffi.Util.v().resolveFromClassFile(sc, classFile, fileName, references); } finally { close(); } addSourceFileTag(sc); IInitialResolver.Dependencies deps = new IInitialResolver.Dependencies(); deps.typesToSignature.addAll(references); return deps; } private void addSourceFileTag(soot.SootClass sc) { if (fileName == null && zipFileName == null) { return; } SourceFileTag tag = (SourceFileTag) sc.getTag(SourceFileTag.NAME); if (tag == null) { tag = new SourceFileTag(); sc.addTag(tag); } // Sets sourceFile only when it hasn't been set before if (tag.getSourceFile() == null) { String name = zipFileName == null ? new File(fileName).getName() : new File(zipFileName).getName(); tag.setSourceFile(name); } } @Override public void close() { try { if (classFile != null) { classFile.close(); classFile = null; } } catch (IOException e) { throw new RuntimeException("Error: Failed to close source input stream.", e); } finally { if (foundFile != null) { foundFile.close(); foundFile = null; } } } }
3,748
28.519685
108
java
soot
soot-master/src/main/java/soot/CompilationDeathException.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville * %% * 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% */ @SuppressWarnings("serial") public class CompilationDeathException extends RuntimeException { public static final int COMPILATION_ABORTED = 0; public static final int COMPILATION_SUCCEEDED = 1; private final int mStatus; public CompilationDeathException(String msg, Throwable t) { super(msg, t); mStatus = COMPILATION_ABORTED; } public CompilationDeathException(String msg) { super(msg); mStatus = COMPILATION_ABORTED; } public CompilationDeathException(int status, String msg) { super(msg); mStatus = status; } public CompilationDeathException(int status) { mStatus = status; } public int getStatus() { return mStatus; } }
1,507
25.928571
71
java
soot
soot-master/src/main/java/soot/ConflictingFieldRefException.java
package soot; /*- * #%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% */ /** * Exception that is thrown when code tries to resolve a reference for some field "fld: type1", but the target class already * declares a field "fld: type2". In other words, this exception denotes a mismatch in expected and declared type. * * @author Steven Arzt */ public class ConflictingFieldRefException extends RuntimeException { private static final long serialVersionUID = -2351763146637880592L; private final SootField existingField; private final Type requestedType; public ConflictingFieldRefException(SootField existingField, Type requestedType) { this.existingField = existingField; this.requestedType = requestedType; } @Override public String toString() { return String.format("Existing field %s does not match expected field type %s", existingField.toString(), requestedType.toString()); } }
1,688
33.469388
124
java
soot
soot-master/src/main/java/soot/Context.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A context in a context-sensitive all graph. May be a unit (in a 1CFA call graph) or a Spark AllocNode (in an * object-sensitive call graph). */ public interface Context { }
995
31.129032
111
java
soot
soot-master/src/main/java/soot/DexClassProvider.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2012 Michael Markert, Frank Hartmann * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.jf.dexlib2.iface.ClassDef; import org.jf.dexlib2.iface.DexFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.dexpler.DexFileProvider; import soot.dexpler.Util; import soot.options.Options; /** * Looks for a dex file which includes the definition of a class. */ public class DexClassProvider implements ClassProvider { private static final Logger logger = LoggerFactory.getLogger(DexClassProvider.class); public static Set<String> classesOfDex(DexFile dexFile) { Set<String> classes = new HashSet<String>(); for (ClassDef c : dexFile.getClasses()) { classes.add(Util.dottedClassName(c.getType())); } return classes; } /** * Provides the DexClassSource for the class. * * @param className * class to provide. * @return a DexClassSource that defines the className named class. */ @Override public ClassSource find(String className) { ensureDexIndex(); File file = SourceLocator.v().dexClassIndex().get(className); return (file == null) ? null : new DexClassSource(className, file); } /** * Checks whether the dex class index needs to be (re)built and triggers the build if necessary */ protected void ensureDexIndex() { final SourceLocator loc = SourceLocator.v(); Map<String, File> index = loc.dexClassIndex(); if (index == null) { index = new HashMap<String, File>(); buildDexIndex(index, loc.classPath()); loc.setDexClassIndex(index); } // Process the classpath extensions Set<String> extensions = loc.getDexClassPathExtensions(); if (extensions != null) { buildDexIndex(index, new ArrayList<>(extensions)); loc.clearDexClassPathExtensions(); } } /** * Build index of ClassName-to-File mappings. * * @param index * map to insert mappings into * @param classPath * paths to index */ private void buildDexIndex(Map<String, File> index, List<String> classPath) { for (String path : classPath) { try { File dexFile = new File(path); if (dexFile.exists()) { for (DexFileProvider.DexContainer<? extends DexFile> container : DexFileProvider.v().getDexFromSource(dexFile)) { for (String className : classesOfDex(container.getBase().getDexFile())) { if (!index.containsKey(className)) { index.put(className, container.getFilePath()); } else if (Options.v().verbose()) { logger.debug(String.format( "Warning: Duplicate of class '%s' found in dex file '%s' from source '%s'. Omitting class.", className, container.getDexName(), container.getFilePath().getCanonicalPath())); } } } } } catch (IOException e) { logger.warn("IO error while processing dex file '" + path + "'"); logger.debug("Exception: " + e); } catch (Exception e) { logger.warn("exception while processing dex file '" + path + "'"); logger.debug("Exception: " + e); } } } }
4,141
31.614173
123
java
soot
soot-master/src/main/java/soot/DexClassSource.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2011 - 2012 Michael Markert * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.dexpler.DexResolver; import soot.javaToJimple.IInitialResolver.Dependencies; import soot.options.Options; /** * Responsible for resolving a single class from a dex source format. */ public class DexClassSource extends ClassSource { private static final Logger logger = LoggerFactory.getLogger(DexClassSource.class); protected final File path; /** * @param className * the class which dependencies are to be resolved. * @param path * to the file that defines the class. */ public DexClassSource(String className, File path) { super(className); this.path = path; } /** * Resolve dependencies of class. * * @param sc * The SootClass to resolve into. * @return Dependencies of class (Strings or Types referenced). */ @Override public Dependencies resolve(SootClass sc) { if (Options.v().verbose()) { logger.debug("resolving " + className + " from file " + path.getPath()); } return DexResolver.v().resolveFromFile(path, className, sc); } }
1,960
27.838235
85
java
soot
soot-master/src/main/java/soot/DoubleType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java built-in type 'double'. Implemented as a singleton. */ @SuppressWarnings("serial") public class DoubleType extends PrimType { public static final int HASHCODE = 0x4B9D7242; public DoubleType(Singletons.Global g) { } public static DoubleType v() { return G.v().soot_DoubleType(); } @Override public boolean equals(Object t) { return this == t; } @Override public int hashCode() { return HASHCODE; } @Override public String toString() { return "double"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseDoubleType(this); } @Override public RefType boxedType() { return RefType.v("java.lang.Double"); } @Override public Class<?> getJavaBoxedType() { return Double.class; } @Override public Class<?> getJavaPrimitiveType() { return double.class; } }
1,744
21.662338
86
java
soot
soot-master/src/main/java/soot/EntryPoints.java
package soot; /*- * #%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.Iterator; import java.util.List; import java.util.NoSuchElementException; import soot.util.NumberedString; import soot.util.StringNumberer; /** * Returns the various potential entry points of a Java program. * * @author Ondrej Lhotak */ public class EntryPoints { final NumberedString sigMain; final NumberedString sigFinalize; final NumberedString sigExit; final NumberedString sigClinit; final NumberedString sigInit; final NumberedString sigStart; final NumberedString sigRun; final NumberedString sigObjRun; final NumberedString sigForName; public EntryPoints(Singletons.Global g) { final StringNumberer subSigNumberer = Scene.v().getSubSigNumberer(); sigMain = subSigNumberer.findOrAdd("void main(java.lang.String[])"); sigFinalize = subSigNumberer.findOrAdd("void finalize()"); sigExit = subSigNumberer.findOrAdd("void exit()"); sigClinit = subSigNumberer.findOrAdd("void <clinit>()"); sigInit = subSigNumberer.findOrAdd("void <init>()"); sigStart = subSigNumberer.findOrAdd("void start()"); sigRun = subSigNumberer.findOrAdd("void run()"); sigObjRun = subSigNumberer.findOrAdd("java.lang.Object run()"); sigForName = subSigNumberer.findOrAdd("java.lang.Class forName(java.lang.String)"); } public static EntryPoints v() { return G.v().soot_EntryPoints(); } protected void addMethod(List<SootMethod> set, SootClass cls, NumberedString methodSubSig) { SootMethod sm = cls.getMethodUnsafe(methodSubSig); if (sm != null) { set.add(sm); } } protected void addMethod(List<SootMethod> set, String methodSig) { final Scene sc = Scene.v(); if (sc.containsMethod(methodSig)) { set.add(sc.getMethod(methodSig)); } } /** * Returns only the application entry points, not including entry points invoked implicitly by the VM. */ public List<SootMethod> application() { List<SootMethod> ret = new ArrayList<SootMethod>(); final Scene sc = Scene.v(); if (sc.hasMainClass()) { SootClass mainClass = sc.getMainClass(); addMethod(ret, mainClass, sigMain); for (SootMethod clinit : clinitsOf(mainClass)) { ret.add(clinit); } } return ret; } /** Returns only the entry points invoked implicitly by the VM. */ public List<SootMethod> implicit() { List<SootMethod> ret = new ArrayList<SootMethod>(); addMethod(ret, "<java.lang.System: void initializeSystemClass()>"); addMethod(ret, "<java.lang.ThreadGroup: void <init>()>"); // addMethod( ret, "<java.lang.ThreadGroup: void // remove(java.lang.Thread)>"); addMethod(ret, "<java.lang.Thread: void exit()>"); addMethod(ret, "<java.lang.ThreadGroup: void uncaughtException(java.lang.Thread,java.lang.Throwable)>"); // addMethod( ret, "<java.lang.System: void // loadLibrary(java.lang.String)>"); addMethod(ret, "<java.lang.ClassLoader: void <init>()>"); addMethod(ret, "<java.lang.ClassLoader: java.lang.Class loadClassInternal(java.lang.String)>"); addMethod(ret, "<java.lang.ClassLoader: void checkPackageAccess(java.lang.Class,java.security.ProtectionDomain)>"); addMethod(ret, "<java.lang.ClassLoader: void addClass(java.lang.Class)>"); addMethod(ret, "<java.lang.ClassLoader: long findNative(java.lang.ClassLoader,java.lang.String)>"); addMethod(ret, "<java.security.PrivilegedActionException: void <init>(java.lang.Exception)>"); // addMethod( ret, "<java.lang.ref.Finalizer: void // register(java.lang.Object)>"); addMethod(ret, "<java.lang.ref.Finalizer: void runFinalizer()>"); addMethod(ret, "<java.lang.Thread: void <init>(java.lang.ThreadGroup,java.lang.Runnable)>"); addMethod(ret, "<java.lang.Thread: void <init>(java.lang.ThreadGroup,java.lang.String)>"); return ret; } /** Returns all the entry points. */ public List<SootMethod> all() { List<SootMethod> ret = new ArrayList<SootMethod>(); ret.addAll(application()); ret.addAll(implicit()); return ret; } /** Returns a list of all static initializers. */ public List<SootMethod> clinits() { List<SootMethod> ret = new ArrayList<SootMethod>(); for (SootClass cl : Scene.v().getClasses()) { addMethod(ret, cl, sigClinit); } return ret; } /** Returns a list of all constructors taking no arguments. */ public List<SootMethod> inits() { List<SootMethod> ret = new ArrayList<SootMethod>(); for (SootClass cl : Scene.v().getClasses()) { addMethod(ret, cl, sigInit); } return ret; } /** Returns a list of all constructors. */ public List<SootMethod> allInits() { List<SootMethod> ret = new ArrayList<SootMethod>(); for (SootClass cl : Scene.v().getClasses()) { for (SootMethod m : cl.getMethods()) { if ("<init>".equals(m.getName())) { ret.add(m); } } } return ret; } /** Returns a list of all concrete methods of all application classes. */ public List<SootMethod> methodsOfApplicationClasses() { List<SootMethod> ret = new ArrayList<SootMethod>(); for (SootClass cl : Scene.v().getApplicationClasses()) { for (SootMethod m : cl.getMethods()) { if (m.isConcrete()) { ret.add(m); } } } return ret; } /** * Returns a list of all concrete main(String[]) methods of all application classes. */ public List<SootMethod> mainsOfApplicationClasses() { List<SootMethod> ret = new ArrayList<SootMethod>(); for (SootClass cl : Scene.v().getApplicationClasses()) { SootMethod m = cl.getMethodUnsafe("void main(java.lang.String[])"); if (m != null && m.isConcrete()) { ret.add(m); } } return ret; } /** Returns a list of all clinits of class cl and its superclasses. */ public Iterable<SootMethod> clinitsOf(SootClass cl) { // Do not create an actual list, since this method gets called quite often // Instead, callers usually just want to iterate over the result. SootMethod init = cl.getMethodUnsafe(sigClinit); SootClass superClass = cl.getSuperclassUnsafe(); // check super classes until finds a constructor or no super class there anymore. while (init == null && superClass != null) { init = superClass.getMethodUnsafe(sigClinit); superClass = superClass.getSuperclassUnsafe(); } if (init == null) { return Collections.emptyList(); } SootMethod initStart = init; return new Iterable<SootMethod>() { @Override public Iterator<SootMethod> iterator() { return new Iterator<SootMethod>() { SootMethod current = initStart; @Override public SootMethod next() { if (!hasNext()) { throw new NoSuchElementException(); } SootMethod n = current; // Pre-fetch the next element current = null; SootClass currentClass = n.getDeclaringClass(); while (true) { SootClass superClass = currentClass.getSuperclassUnsafe(); if (superClass == null) { break; } SootMethod m = superClass.getMethodUnsafe(sigClinit); if (m != null) { current = m; break; } currentClass = superClass; } return n; } @Override public boolean hasNext() { return current != null; } }; } }; } }
8,427
32.983871
119
java
soot
soot-master/src/main/java/soot/EquivTo.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * An alternate equivalence relation between objects. The standard interpretation will be structural equality. We also demand * that if x.equivTo(y), then x.equivHashCode() == y.equivHashCode. */ public interface EquivTo { /** * Returns true if this object is equivalent to o. */ public boolean equivTo(Object o); /** * Returns a (not necessarily fixed) hash code for this object. This hash code coincides with equivTo; it is undefined in * the presence of mutable objects. */ public int equivHashCode(); }
1,360
31.404762
125
java
soot
soot-master/src/main/java/soot/EquivalentValue.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrick Lam * extended 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.util.Switch; /** * Encapsulates the Value class, but uses EquivTo for equality comparisons. Also uses equivHashCode as its hash code. */ @SuppressWarnings("serial") public class EquivalentValue implements Value { private final Value e; public EquivalentValue(Value v) { this.e = (v instanceof EquivalentValue) ? ((EquivalentValue) v).e : v; } @Override public boolean equals(Object o) { return e.equivTo((o instanceof EquivalentValue) ? ((EquivalentValue) o).e : o); } /** * compares the encapsulated value with <code>v</code>, using <code>equivTo</code> */ public boolean equivToValue(Value v) { return e.equivTo(v); } /** * compares the encapsulated value with <code>v</code>, using <code>equals</code> */ public boolean equalsToValue(Value v) { return e.equals(v); } /** * @deprecated * @see #getValue() */ @Deprecated public Value getDeepestValue() { return getValue(); } @Override public int hashCode() { return e.equivHashCode(); } @Override public String toString() { return e.toString(); } public Value getValue() { return e; } /*********************************/ /* implement the Value-interface */ /*********************************/ @Override public List<ValueBox> getUseBoxes() { return e.getUseBoxes(); } @Override public Type getType() { return e.getType(); } @Override public Object clone() { return new EquivalentValue((Value) e.clone()); } @Override public boolean equivTo(Object o) { return e.equivTo(o); } @Override public int equivHashCode() { return e.equivHashCode(); } @Override public void apply(Switch sw) { e.apply(sw); } @Override public void toString(UnitPrinter up) { e.toString(up); } }
2,695
21.098361
117
java
soot
soot-master/src/main/java/soot/ErroneousType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation used for untypable objects. Implemented as a singleton. */ @SuppressWarnings("serial") public class ErroneousType extends Type { public ErroneousType(Singletons.Global g) { } public static ErroneousType v() { return G.v().soot_ErroneousType(); } @Override public int hashCode() { return 0x92473FFF; } @Override public boolean equals(Object t) { return this == t; } @Override public String toString() { return "<error>"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseErroneousType(this); } }
1,443
23.474576
78
java
soot
soot-master/src/main/java/soot/EscapeAnalysis.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.jimple.AnyNewExpr; /** * A generic interface to an escape analysis. * * @author Ondrej Lhotak */ public interface EscapeAnalysis { /** * Returns true if objects allocated at n may continue to be live after the method in which they are allocated returns. */ public boolean mayEscapeMethod(AnyNewExpr n); /** * Returns true if objects allocated at n in context c may continue to be live after the method in which they are allocated * returns. */ public boolean mayEscapeMethod(Context c, AnyNewExpr n); /** * Returns true if objects allocated at n may be accessed in a thread other than the thread in which they were allocated. */ public boolean mayEscapeThread(AnyNewExpr n); /** * Returns true if objects allocated at n in context c may be accessed in a thread other than the thread in which they were * allocated. */ public boolean mayEscapeThread(Context c, AnyNewExpr n); }
1,757
30.392857
125
java
soot
soot-master/src/main/java/soot/FastHierarchy.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import java.util.ArrayDeque; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import soot.jimple.spark.internal.TypeManager; import soot.options.Options; import soot.util.ConcurrentHashMultiMap; import soot.util.MultiMap; import soot.util.NumberedString; /** * Represents the class hierarchy. It is closely linked to a Scene, and must be recreated if the Scene changes. * * <p> * This version supercedes the old soot.Hierarchy class. * * @author Ondrej Lhotak * @author Manuel Benz 22.10.19 - Fixed concrete/abstract dispatch methods to car for default interface methods and account * for overwritten return types */ public class FastHierarchy { protected static final int USE_INTERVALS_BOUNDARY = 100; protected Table<SootClass, NumberedString, SootMethod> typeToVtbl = HashBasedTable.create(); /** * This map holds all key,value pairs such that value.getSuperclass() == key. This is one of the three maps that hold the * inverse of the relationships given by the getSuperclass and getInterfaces methods of SootClass. */ protected MultiMap<SootClass, SootClass> classToSubclasses = new ConcurrentHashMultiMap<SootClass, SootClass>(); /** * This map holds all key,value pairs such that value is an interface and key is in value.getInterfaces(). This is one of * the three maps that hold the inverse of the relationships given by the getSuperclass and getInterfaces methods of * SootClass. */ protected MultiMap<SootClass, SootClass> interfaceToSubinterfaces = new ConcurrentHashMultiMap<SootClass, SootClass>(); /** * This map holds all key,value pairs such that value is a class (NOT an interface) and key is in value.getInterfaces(). * This is one of the three maps that hold the inverse of the relationships given by the getSuperclass and getInterfaces * methods of SootClass. */ protected MultiMap<SootClass, SootClass> interfaceToImplementers = new ConcurrentHashMultiMap<SootClass, SootClass>(); /** * This map is a transitive closure of interfaceToSubinterfaces, and each set contains its superinterface itself. */ protected MultiMap<SootClass, SootClass> interfaceToAllSubinterfaces = new ConcurrentHashMultiMap<SootClass, SootClass>(); /** * This map gives, for an interface, all concrete classes that implement that interface and all its subinterfaces, but NOT * their subclasses. */ protected MultiMap<SootClass, SootClass> interfaceToAllImplementers = new ConcurrentHashMultiMap<SootClass, SootClass>(); /** * For each class (NOT interface), this map contains a Interval, which is a pair of numbers giving a preorder and postorder * ordering of classes in the inheritance tree. */ protected Map<SootClass, Interval> classToInterval = new HashMap<SootClass, Interval>(); protected final Scene sc; protected final RefType rtObject; protected final RefType rtSerializable; protected final RefType rtCloneable; protected class Interval { int lower; int upper; public Interval() { } public Interval(int lower, int upper) { this.lower = lower; this.upper = upper; } public boolean isSubrange(Interval potentialSubrange) { return (potentialSubrange == this) || (potentialSubrange != null && this.lower <= potentialSubrange.lower && this.upper >= potentialSubrange.upper); } } protected int dfsVisit(int start, SootClass c) { Interval r = new Interval(); r.lower = start++; Collection<SootClass> col = classToSubclasses.get(c); if (col != null) { for (SootClass sc : col) { // For some awful reason, Soot thinks interface are subclasses // of java.lang.Object if (sc.isInterface()) { continue; } start = dfsVisit(start, sc); } } r.upper = start++; if (c.isInterface()) { throw new RuntimeException("Attempt to dfs visit interface " + c); } classToInterval.putIfAbsent(c, r); return start; } /** * Constructs a hierarchy from the current scene. */ public FastHierarchy() { this.sc = Scene.v(); this.rtObject = sc.getObjectType(); this.rtSerializable = RefType.v("java.io.Serializable"); this.rtCloneable = RefType.v("java.lang.Cloneable"); /* First build the inverse maps. */ buildInverseMaps(); /* Now do a dfs traversal to get the Interval numbers. */ int r = dfsVisit(0, sc.getSootClass("java.lang.Object")); /* * also have to traverse for all phantom classes because they also can be roots of the type hierarchy */ for (Iterator<SootClass> phantomClassIt = sc.getPhantomClasses().snapshotIterator(); phantomClassIt.hasNext();) { SootClass phantomClass = phantomClassIt.next(); if (!phantomClass.isInterface()) { r = dfsVisit(r, phantomClass); } } } protected void buildInverseMaps() { for (SootClass cl : sc.getClasses().getElementsUnsorted()) { if (cl.resolvingLevel() < SootClass.HIERARCHY) { continue; } if (!cl.isInterface()) { SootClass superClass = cl.getSuperclassUnsafe(); if (superClass != null) { classToSubclasses.put(superClass, cl); } } for (SootClass supercl : cl.getInterfaces()) { if (cl.isInterface()) { interfaceToSubinterfaces.put(supercl, cl); } else { interfaceToImplementers.put(supercl, cl); } } } } /** * Return true if class child is a subclass of class parent, neither of them being allowed to be interfaces. If we don't * know any of the classes, we always return false */ public boolean isSubclass(SootClass child, SootClass parent) { child.checkLevel(SootClass.HIERARCHY); parent.checkLevel(SootClass.HIERARCHY); Interval parentInterval = classToInterval.get(parent); Interval childInterval = classToInterval.get(child); return parentInterval != null && childInterval != null && parentInterval.isSubrange(childInterval); } /** * For an interface parent (MUST be an interface), returns set of all implementers of it but NOT their subclasses. * * <p> * This method can be used concurrently (is thread safe). * * @param parent * the parent interface. * @return an set, possibly empty */ public Set<SootClass> getAllImplementersOfInterface(SootClass parent) { parent.checkLevel(SootClass.HIERARCHY); Set<SootClass> result = interfaceToAllImplementers.get(parent); if (!result.isEmpty()) { return result; } result = new HashSet<>(); for (SootClass subinterface : getAllSubinterfaces(parent)) { if (subinterface == parent) { continue; } result.addAll(getAllImplementersOfInterface(subinterface)); } result.addAll(interfaceToImplementers.get(parent)); interfaceToAllImplementers.putAll(parent, result); return result; } /** * For an interface parent (MUST be an interface), returns set of all subinterfaces including <code>parent</code>. * * <p> * This method can be used concurrently (is thread safe). * * @param parent * the parent interface. * @return an set, possibly empty */ public Set<SootClass> getAllSubinterfaces(SootClass parent) { parent.checkLevel(SootClass.HIERARCHY); if (!parent.isInterface()) { return Collections.emptySet(); } Set<SootClass> result = interfaceToAllSubinterfaces.get(parent); if (!result.isEmpty()) { return result; } result = new HashSet<>(); result.add(parent); for (SootClass si : interfaceToSubinterfaces.get(parent)) { result.addAll(getAllSubinterfaces(si)); } interfaceToAllSubinterfaces.putAll(parent, result); return result; } /** * Given an object of declared type child, returns true if the object can be stored in a variable of type parent. If child * is an interface that is not a subinterface of parent, this method will return false even though some objects * implementing the child interface may also implement the parent interface. */ public boolean canStoreType(final Type child, final Type parent) { if (child == parent || child.equals(parent)) { return true; } else if (parent instanceof NullType) { return false; } else if (child instanceof NullType) { return parent instanceof RefLikeType; } else if (child instanceof RefType) { if (parent == rtObject) { return true; } else if (parent instanceof RefType) { return canStoreClass(((RefType) child).getSootClass(), ((RefType) parent).getSootClass()); } else { return false; } } else if (child instanceof AnySubType) { if (!(parent instanceof RefLikeType)) { throw new RuntimeException("Unhandled type " + parent); } else if (parent instanceof ArrayType) { // SA, 2021-09-15. Someone previously misinterpreted the Java Language Spec here. All array types implement // Serializable and Cloneable, and that allows you to assign an array Foo[] to a variable of type Serializable. // However, it doesn't work the other way round. You can't assign a Serializable to a variable of type Foo[]. return false; } else { Deque<SootClass> worklist = new ArrayDeque<SootClass>(); SootClass base = ((AnySubType) child).getBase().getSootClass(); if (base.isInterface()) { worklist.addAll(getAllImplementersOfInterface(base)); } else { worklist.add(base); } final SootClass parentClass = ((RefType) parent).getSootClass(); { Set<SootClass> workset = new HashSet<>(); SootClass cl; while ((cl = worklist.poll()) != null) { if (!workset.add(cl)) { continue; } else if (cl.isConcrete() && canStoreClass(cl, parentClass)) { return true; } worklist.addAll(getSubclassesOf(cl)); } } return false; } } else if (child instanceof ArrayType) { if (parent instanceof RefType) { // From Java Language Spec 2nd ed., Chapter 10, Arrays return parent == rtObject || parent == rtSerializable || parent == rtCloneable; } else if (parent instanceof ArrayType) { // You can store a int[][] in a Object[]. Yuck! // Also, you can store a Interface[] in a Object[] final ArrayType aparent = (ArrayType) parent; final ArrayType achild = (ArrayType) child; if (achild.numDimensions == aparent.numDimensions) { final Type pBaseType = aparent.baseType; final Type cBaseType = achild.baseType; if (cBaseType.equals(pBaseType)) { return true; } else if ((cBaseType instanceof RefType) && (pBaseType instanceof RefType)) { return canStoreType(cBaseType, pBaseType); } else { return false; } } else if (achild.numDimensions > aparent.numDimensions) { final Type pBaseType = aparent.baseType; return pBaseType == rtObject || pBaseType == rtSerializable || pBaseType == rtCloneable; } else { return false; } } else { return false; } } else { return false; } } /** * Given an object of declared type child, returns true if the object can be stored in a variable of type parent. If child * is an interface that is not a subinterface of parent, this method will return false even though some objects * implementing the child interface may also implement the parent interface. */ public boolean canStoreClass(SootClass child, SootClass parent) { parent.checkLevel(SootClass.HIERARCHY); child.checkLevel(SootClass.HIERARCHY); Interval parentInterval = classToInterval.get(parent); Interval childInterval = classToInterval.get(child); if (parentInterval != null && childInterval != null) { return parentInterval.isSubrange(childInterval); } else if (childInterval == null) { // child is interface if (parentInterval != null) { // parent is not interface return parent == rtObject.getSootClass(); } else { return getAllSubinterfaces(parent).contains(child); } } else { final Set<SootClass> impl = getAllImplementersOfInterface(parent); if (impl.size() > USE_INTERVALS_BOUNDARY) { // If we have more than 100 entries it is quite time consuming to check each and every // implementing class // if it is the "child" class. Therefore we use an alternative implementation which just // checks the client // class it's super classes and all the interfaces it implements. return canStoreClassClassic(child, parent); } else { // If we only have a few entries, you can't beat the performance of a plain old loop // in combination with the interval approach. for (SootClass c : impl) { Interval interval = classToInterval.get(c); if (interval != null && interval.isSubrange(childInterval)) { return true; } } return false; } } } /** * "Classic" implementation using the intuitive approach (without using {@link Interval}) to check whether * <code>child</code> can be stored in a type of <code>parent</code>: * * <p> * If <code>parent</code> is not an interface we simply traverse and check the super-classes of <code>child</code>. * * <p> * If <code>parent</code> is an interface we traverse the super-classes of <code>child</code> and check each interface * implemented by this class. Also each interface is checked recursively for super interfaces it implements. * * <p> * This implementation can be much faster (compared to the interval based implementation of * {@link #canStoreClass(SootClass, SootClass)} in cases where one interface is implemented in thousands of classes. * * @param child * @param parent * @return */ protected boolean canStoreClassClassic(final SootClass child, final SootClass parent) { final boolean parentIsInterface = parent.isInterface(); ArrayDeque<SootClass> children = new ArrayDeque<>(); children.add(child); for (SootClass p; (p = children.poll()) != null;) { for (SootClass sc = p; sc != null;) { if (sc == parent) { return true; } if (parentIsInterface) { for (SootClass interf : sc.getInterfaces()) { if (interf == parent) { return true; } children.push(interf); } } sc = sc.getSuperclassUnsafe(); } } return false; } public Collection<SootMethod> resolveConcreteDispatchWithoutFailing(Collection<Type> concreteTypes, SootMethod m, RefType declaredTypeOfBase) { final SootClass declaringClass = declaredTypeOfBase.getSootClass(); declaringClass.checkLevel(SootClass.HIERARCHY); Set<SootMethod> ret = new HashSet<SootMethod>(); for (final Type t : concreteTypes) { if (t instanceof AnySubType) { HashSet<SootClass> s = new HashSet<SootClass>(); s.add(declaringClass); while (!s.isEmpty()) { final SootClass c = s.iterator().next(); s.remove(c); if (!c.isInterface() && !c.isAbstract() && canStoreClass(c, declaringClass)) { SootMethod concreteM = resolveConcreteDispatch(c, m); if (concreteM != null) { ret.add(concreteM); } } { Set<SootClass> subclasses = classToSubclasses.get(c); if (subclasses != null) { s.addAll(subclasses); } } { Set<SootClass> subinterfaces = interfaceToSubinterfaces.get(c); if (subinterfaces != null) { s.addAll(subinterfaces); } } { Set<SootClass> implementers = interfaceToImplementers.get(c); if (implementers != null) { s.addAll(implementers); } } } return ret; } else if (t instanceof RefType) { SootClass concreteClass = ((RefType) t).getSootClass(); if (!canStoreClass(concreteClass, declaringClass)) { continue; } SootMethod concreteM; try { concreteM = resolveConcreteDispatch(concreteClass, m); } catch (Exception e) { concreteM = null; } if (concreteM != null) { ret.add(concreteM); } } else if (t instanceof ArrayType) { SootMethod concreteM; try { concreteM = resolveConcreteDispatch(RefType.v("java.lang.Object").getSootClass(), m); } catch (Exception e) { concreteM = null; } if (concreteM != null) { ret.add(concreteM); } } else { throw new RuntimeException("Unrecognized reaching type " + t); } } return ret; } public Collection<SootMethod> resolveConcreteDispatch(Collection<Type> concreteTypes, SootMethod m, RefType declaredTypeOfBase) { final SootClass declaringClass = declaredTypeOfBase.getSootClass(); declaringClass.checkLevel(SootClass.HIERARCHY); Set<SootMethod> ret = new HashSet<SootMethod>(); for (final Type t : concreteTypes) { if (t instanceof AnySubType) { HashSet<SootClass> s = new HashSet<SootClass>(); s.add(declaringClass); while (!s.isEmpty()) { final SootClass c = s.iterator().next(); s.remove(c); if (!c.isInterface() && !c.isAbstract() && canStoreClass(c, declaringClass)) { SootMethod concreteM = resolveConcreteDispatch(c, m); if (concreteM != null) { ret.add(concreteM); } } { Set<SootClass> subclasses = classToSubclasses.get(c); if (subclasses != null) { s.addAll(subclasses); } } { Set<SootClass> subinterfaces = interfaceToSubinterfaces.get(c); if (subinterfaces != null) { s.addAll(subinterfaces); } } { Set<SootClass> implementers = interfaceToImplementers.get(c); if (implementers != null) { s.addAll(implementers); } } } return ret; } else if (t instanceof RefType) { SootClass concreteClass = ((RefType) t).getSootClass(); if (!canStoreClass(concreteClass, declaringClass)) { continue; } SootMethod concreteM = resolveConcreteDispatch(concreteClass, m); if (concreteM != null) { ret.add(concreteM); } } else if (t instanceof ArrayType) { SootMethod concreteM = resolveConcreteDispatch(rtObject.getSootClass(), m); if (concreteM != null) { ret.add(concreteM); } } else { throw new RuntimeException("Unrecognized reaching type " + t); } } return ret; } /** * Returns true if a method defined in declaringClass with the given modifiers is visible from the class from. */ private boolean isVisible(SootClass from, SootClass declaringClass, int modifier) { from.checkLevel(SootClass.HIERARCHY); if (Modifier.isPublic(modifier)) { return true; } // If two inner classes are (transitively) inside the same outer class, such as A$B$C and A$D$E they can override methods // from one another, even if all methods are private. In the example, it's perfectly fine for private class A$D$E to // extend private class A$B$C and override a method in it. for (SootClass curDecl = declaringClass; curDecl.hasOuterClass();) { curDecl = curDecl.getOuterClass(); if (from.equals(curDecl)) { return true; } for (SootClass curFrom = from; curFrom.hasOuterClass();) { curFrom = curFrom.getOuterClass(); if (curDecl.equals(curFrom)) { return true; } } } if (Modifier.isPrivate(modifier)) { return from.equals(declaringClass); } if (Modifier.isProtected(modifier)) { return canStoreClass(from, declaringClass); } // m is package return from.getJavaPackageName().equals(declaringClass.getJavaPackageName()); } /** * Given an object of declared type C, returns the methods which could be called on an o.f() invocation. * * @param baseType * The declared type C */ public Set<SootMethod> resolveAbstractDispatch(SootClass baseType, SootMethod m) { return resolveAbstractDispatch(baseType, m.makeRef()); } /** * Given an object of declared type C, returns the methods which could be called on an o.f() invocation. * * @param baseType * The declared type C */ public Set<SootMethod> resolveAbstractDispatch(SootClass baseType, SootMethodRef m) { HashSet<SootClass> resolved = new HashSet<>(); HashSet<SootMethod> ret = new HashSet<>(); ArrayDeque<SootClass> worklist = new ArrayDeque<>(); worklist.add(baseType); while (true) { SootClass concreteType = worklist.poll(); if (concreteType == null) { break; } else if (resolved.contains(concreteType) && classToSubclasses.get(concreteType).isEmpty()) { continue; } if (concreteType.isInterface()) { worklist.addAll(getAllImplementersOfInterface(concreteType)); continue; } else { Collection<SootClass> c = classToSubclasses.get(concreteType); if (c != null) { worklist.addAll(c); } } if (!resolved.contains(concreteType)) { SootMethod resolvedMethod = resolveMethod(concreteType, m, false, resolved); if (resolvedMethod != null) { ret.add(resolvedMethod); } } } return ret; } /** * Given an object of actual type C (o = new C()), returns the method which will be called on an o.f() invocation. * * @param baseType * The actual type C */ public SootMethod resolveConcreteDispatch(SootClass baseType, SootMethod m) { return resolveConcreteDispatch(baseType, m.makeRef()); } /** * Given an object of actual type C (o = new C()), returns the method which will be called on an o.f() invocation. * * @param baseType * The actual type C */ public SootMethod resolveConcreteDispatch(SootClass baseType, SootMethodRef m) { baseType.checkLevel(SootClass.HIERARCHY); if (baseType.isInterface()) { throw new RuntimeException("A concrete type cannot be an interface: " + baseType); } return resolveMethod(baseType, m, false); } /** * Conducts the actual dispatch by searching up the baseType's superclass hierarchy and interface hierarchy if the * sourcecode level is beyond Java 7 (due to default interface methods.) Given an object of actual type C (o = new C()), * returns the method which will be called on an o.f() invocation. * * <p> * If abstract methods are allowed, it will just resolve to the first method found according to javas method resolution * process: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3 * * @param baseType * The type C * @param m * The method f to resolve * @return The concrete method o.f() to call */ public SootMethod resolveMethod(SootClass baseType, SootMethod m, boolean allowAbstract) { return resolveMethod(baseType, m.makeRef(), allowAbstract); } /** * Conducts the actual dispatch by searching up the baseType's superclass hierarchy and interface hierarchy if the * sourcecode level is beyond Java 7 (due to default interface methods.) Given an object of actual type C (o = new C()), * returns the method which will be called on an o.f() invocation. * * <p> * If abstract methods are allowed, it will just resolve to the first method found according to javas method resolution * process: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3 * * @param baseType * The type C * @param m * The method f to resolve * @return The concrete method o.f() to call */ public SootMethod resolveMethod(SootClass baseType, SootMethodRef m, boolean allowAbstract) { return resolveMethod(baseType, m, allowAbstract, new HashSet<>()); } /** * Conducts the actual dispatch by searching up the baseType's superclass hierarchy and interface hierarchy if the * sourcecode level is beyond Java 7 (due to default interface methods.) Given an object of actual type C (o = new C()), * returns the method which will be called on an o.f() invocation. * * <p> * * * * <p> * If abstract methods are allowed, it will just resolve to the first method found according to * javas method resolution * process: * https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3 * * @param baseType * The type C * @param m * The method f to resolve * @param ignoreList * A set of classes that should be ignored during dispatch. This set will also be modified since every traversed * class/interface will be added. This is required for the abstract dispatch to not do additional resolving effort * by resolving the same classes multiple times. * @return The concrete method o.f() to call */ private SootMethod resolveMethod(SootClass baseType, SootMethodRef m, boolean allowAbstract, Set<SootClass> ignoreList) { return resolveMethod(baseType, m.getDeclaringClass(), m.getName(), m.getParameterTypes(), m.getReturnType(), allowAbstract, ignoreList, m.getSubSignature()); } /** * Conducts the actual dispatch by searching up the baseType's superclass hierarchy and interface hierarchy if the * sourcecode level is beyond Java 7 (due to default interface methods.) Given an object of actual type C (o = new C()), * returns the method which will be called on an o.f() invocation. * * <p> * If abstract methods are allowed, it will just resolve to the first method found according to javas method resolution * process: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3 * * @param baseType * The type C * @param declaringClass * declaring class of the method to resolve * @param name * Name of the method to resolve * @return The concrete method o.f() to call */ public SootMethod resolveMethod(SootClass baseType, SootClass declaringClass, String name, List<Type> parameterTypes, Type returnType, boolean allowAbstract) { return resolveMethod(baseType, declaringClass, name, parameterTypes, returnType, allowAbstract, new HashSet<>(), null); } /** * Conducts the actual dispatch by searching up the baseType's superclass hierarchy and interface hierarchy if the * sourcecode level is beyond Java 7 (due to default interface methods.) Given an object of actual type C (o = new C()), * returns the method which will be called on an o.f() invocation. * * <p> * If abstract methods are allowed, it will just resolve to the first method found according to javas method resolution * process: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3 * * @param baseType * The type C * @param declaringClass * declaring class of the method to resolve * @param name * Name of the method to resolve * @param subsignature * The subsignature (can be null) to speed up the resolving process. * @return The concrete method o.f() to call */ public SootMethod resolveMethod(SootClass baseType, SootClass declaringClass, String name, List<Type> parameterTypes, Type returnType, boolean allowAbstract, NumberedString subsignature) { return resolveMethod(baseType, declaringClass, name, parameterTypes, returnType, allowAbstract, new HashSet<>(), subsignature); } /** * Conducts the actual dispatch by searching up the baseType's superclass hierarchy and interface hierarchy if the * sourcecode level is beyond Java 7 (due to default interface methods.) Given an object of actual type C (o = new C()), * returns the method which will be called on an o.f() invocation. * * <p> * If abstract methods are allowed, it will just resolve to the first method found according to javas method resolution * process: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3 * * @param baseType * The type C * @param declaringClass * declaring class of the method to resolve * @param name * Name of the method to resolve * @param ignoreList * A set of classes that should be ignored during dispatch. This set will also be modified since every traversed * class/interface will be added. This is required for the abstract dispatch to not do additional resolving effort * by resolving the same classes multiple times. * @param subsignature * The subsignature (can be null) to speed up the resolving process. * @return The concrete method o.f() to call */ private SootMethod resolveMethod(final SootClass baseType, final SootClass declaringClass, final String name, final List<Type> parameterTypes, final Type returnType, final boolean allowAbstract, final Set<SootClass> ignoreList, NumberedString subsignature) { final NumberedString methodSignature; if (subsignature == null) { methodSignature = Scene.v().getSubSigNumberer().findOrAdd(SootMethod.getSubSignature(name, parameterTypes, returnType)); } else { methodSignature = subsignature; } { SootMethod resolvedMethod = typeToVtbl.get(baseType, methodSignature); if (resolvedMethod != null) { return resolvedMethod; } } // When there is no proper dispatch found, we simply return null to let the caller decide what to do SootMethod candidate = null; for (SootClass concreteType = baseType; concreteType != null && ignoreList.add(concreteType);) { candidate = getSignaturePolymorphicMethod(concreteType, name, parameterTypes, returnType); if (candidate != null) { if (isVisible(declaringClass, concreteType, candidate.getModifiers())) { if (!allowAbstract && candidate.isAbstract()) { candidate = null; break; } if (!candidate.isAbstract()) { typeToVtbl.put(baseType, methodSignature, candidate); } return candidate; } } concreteType = concreteType.getSuperclassUnsafe(); } // for java > 7 we have to go through the interface hierarchy after the superclass hierarchy to // look for default methods: // https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3 if (isHandleDefaultMethods()) { // keep our own ignorelist here so we are not restricted to already hit suinterfaces when // determining the most specific super interface HashSet<SootClass> interfaceIgnoreList = new HashSet<>(); for (SootClass concreteType = baseType; concreteType != null;) { Queue<SootClass> worklist = new LinkedList<>(concreteType.getInterfaces()); // we have to determine the "most specific super interface" while (!worklist.isEmpty()) { SootClass iFace = worklist.poll(); if (interfaceIgnoreList.contains(iFace)) { continue; } interfaceIgnoreList.add(iFace); SootMethod method = getSignaturePolymorphicMethod(iFace, name, parameterTypes, returnType); if (method != null && isVisible(declaringClass, iFace, method.getModifiers())) { if (!allowAbstract && method.isAbstract()) { // abstract method cannot be dispatched } else if (candidate == null || canStoreClass(method.getDeclaringClass(), candidate.getDeclaringClass())) { // the found method is more specific than our current candidate candidate = method; } } else { // go up the interface hierarchy worklist.addAll(iFace.getInterfaces()); } } // we also have to search upwards the class hierarchy again to find the most specific // super interface concreteType = concreteType.getSuperclassUnsafe(); } ignoreList.addAll(interfaceIgnoreList); } if (candidate != null) { typeToVtbl.put(baseType, methodSignature, candidate); } return candidate; } private boolean isHandleDefaultMethods() { int version = Options.v().java_version(); return version == 0 || version > 7; } /** Returns the target for the given SpecialInvokeExpr. */ public SootMethod resolveSpecialDispatch(SootMethod callee, SootMethod container) { /* * This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the * definition of invokespecial. */ final SootClass containerClass = container.getDeclaringClass(); final SootClass calleeClass = callee.getDeclaringClass(); if (containerClass.getType() != calleeClass.getType() && canStoreType(containerClass.getType(), calleeClass.getType()) && !SootMethod.constructorName.equals(callee.getName()) && !SootMethod.staticInitializerName.equals(callee.getName()) // default interface methods are explicitly dispatched to the default // method with a specialinvoke instruction (i.e. do not dispatch to an // overwritten version of that method) && !calleeClass.isInterface()) { return resolveConcreteDispatch(containerClass, callee); } else { return callee; } } /** * Searches the given class for a method that is signature polymorphic according to the given facts, i.e., matches name and * parameter types and ensures that the return type is a an equal or subtype of the given method's subtype. * * @param concreteType * @return */ private SootMethod getSignaturePolymorphicMethod(SootClass concreteType, String name, List<Type> parameterTypes, Type returnType) { SootMethod candidate = null; for (SootMethod method : concreteType.getMethods()) { if (method.getName().equals(name) && method.getParameterTypes().equals(parameterTypes) && canStoreType(method.getReturnType(), returnType)) { candidate = method; returnType = method.getReturnType(); } } return candidate; } /** * Gets the direct subclasses of a given class. The class needs to be resolved at least at the HIERARCHY level. * * @param c * the class * @return a collection (possibly empty) of the direct subclasses */ public Collection<SootClass> getSubclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); Set<SootClass> ret = classToSubclasses.get(c); return (ret == null) ? Collections.emptySet() : ret; } /** * Returns a list of types which can be used to store the given type * * @param nt * the given type * @return the list of types which can be used to store the given type */ public Iterable<Type> canStoreTypeList(final Type nt) { return new Iterable<Type>() { @Override public Iterator<Type> iterator() { Iterator<Type> it = Scene.v().getTypeNumberer().iterator(); return new Iterator<Type>() { Type crt = null; @Override public boolean hasNext() { if (crt != null) { return true; } Type c = null; while (it.hasNext()) { c = it.next(); if (TypeManager.isUnresolved(c)) { continue; } if (canStoreType(nt, c)) { crt = c; return true; } } return false; } @Override public Type next() { Type old = crt; crt = null; hasNext(); return old; } }; } }; } }
37,755
36.568159
125
java
soot
soot-master/src/main/java/soot/FloatType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java built-in type 'float'. Implemented as a singleton. */ @SuppressWarnings("serial") public class FloatType extends PrimType { public static final int HASHCODE = 0xA84373FA; public FloatType(Singletons.Global g) { } public static FloatType v() { return G.v().soot_FloatType(); } @Override public boolean equals(Object t) { return this == t; } @Override public int hashCode() { return HASHCODE; } @Override public String toString() { return "float"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseFloatType(this); } @Override public RefType boxedType() { return RefType.v("java.lang.Float"); } @Override public Class<?> getJavaBoxedType() { return Float.class; } @Override public Class<?> getJavaPrimitiveType() { return float.class; } }
1,734
21.532468
85
java
soot
soot-master/src/main/java/soot/FoundFile.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FoundFile { private static final Logger logger = LoggerFactory.getLogger(FoundFile.class); protected File file; private Path path; protected String entryName; protected ZipFile zipFile; protected ZipEntry zipEntry; protected List<InputStream> openedInputStreams; public FoundFile(ZipFile file, ZipEntry entry) { this(); if (file == null || entry == null) { throw new IllegalArgumentException("Error: The archive and entry cannot be null."); } this.zipFile = file; this.zipEntry = entry; } public FoundFile(String archivePath, String entryName) { this(); if (archivePath == null || entryName == null) { throw new IllegalArgumentException("Error: The archive path and entry name cannot be null."); } this.file = new File(archivePath); this.entryName = entryName; } public FoundFile(File file) { this(); if (file == null) { throw new IllegalArgumentException("Error: The file cannot be null."); } this.file = file; this.entryName = null; } public FoundFile(Path path) { this(); this.path = path; } private FoundFile() { this.openedInputStreams = new ArrayList<InputStream>(); } public String getFilePath() { return file.getPath(); } public boolean isZipFile() { return entryName != null; } public ZipFile getZipFile() { return zipFile; } public File getFile() { return file; } public InputStream inputStream() { InputStream ret = null; if (path != null) { try { ret = Files.newInputStream(path); } catch (IOException e) { throw new RuntimeException( "Error: Failed to open a InputStream for the file at path '" + path.toAbsolutePath().toString() + "'.", e); } } else if (!isZipFile()) { try { ret = new FileInputStream(file); } catch (Exception e) { throw new RuntimeException("Error: Failed to open a InputStream for the file at path '" + file.getPath() + "'.", e); } } else { if (zipFile == null) { try { zipFile = new ZipFile(file); zipEntry = zipFile.getEntry(entryName); if (zipEntry == null) { silentClose(); throw new RuntimeException( "Error: Failed to find entry '" + entryName + "' in the archive file at path '" + file.getPath() + "'."); } } catch (Exception e) { silentClose(); throw new RuntimeException( "Error: Failed to open the archive file at path '" + file.getPath() + "' for entry '" + entryName + "'.", e); } } InputStream stream = null; try { stream = zipFile.getInputStream(zipEntry); ret = doJDKBugWorkaround(stream, zipEntry.getSize()); } catch (Exception e) { throw new RuntimeException("Error: Failed to open a InputStream for the entry '" + zipEntry.getName() + "' of the archive at path '" + zipFile.getName() + "'.", e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // There's not much we can do here logger.debug(e.getMessage(), e); } } } } openedInputStreams.add(ret); return ret; } public void silentClose() { try { close(); } catch (Exception e) { logger.debug(e.getMessage(), e); } } public void close() { // Try to close all opened input streams List<Exception> errs = new ArrayList<Exception>(0); for (InputStream is : openedInputStreams) { try { is.close(); } catch (Exception e) { errs.add(e);// record errors for later } } openedInputStreams.clear(); closeZipFile(errs); // Throw single exception combining all errors if (!errs.isEmpty()) { String msg = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = null; try { ps = new PrintStream(baos, true, "utf-8"); ps.println("Error: Failed to close all opened resources. The following exceptions were thrown in the process: "); int i = 0; for (Throwable t : errs) { ps.print("Exception "); ps.print(i++); ps.print(": "); logger.error(t.getMessage(), t); } msg = new String(baos.toByteArray(), StandardCharsets.UTF_8); } catch (Exception e) { // Do nothing as this will never occur } finally { ps.close(); } throw new RuntimeException(msg); } } protected void closeZipFile(List<Exception> errs) { // Try to close the opened zip file if it exists if (zipFile != null) { try { zipFile.close(); errs.clear();// Successfully closed the archive so all input // streams were closed successfully also } catch (Exception e) { errs.add(e); } zipFile = null;// set to null no matter what zipEntry = null;// set to null no matter what } } private InputStream doJDKBugWorkaround(InputStream is, long size) throws IOException { int sz = (int) size; byte[] buf = new byte[sz]; final int N = 1024; int ln = 0; int count = 0; while (sz > 0 && (ln = is.read(buf, count, Math.min(N, sz))) != -1) { count += ln; sz -= ln; } return new ByteArrayInputStream(buf); } }
6,785
28.124464
124
java
soot
soot-master/src/main/java/soot/G.java
package soot; /*- * #%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.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.coffi.Utf8_Enumeration; import soot.dava.internal.SET.SETBasicBlock; import soot.dava.internal.SET.SETNode; import soot.dexpler.DalvikThrowAnalysis; import soot.jimple.spark.pag.MethodPAG; import soot.jimple.spark.pag.Parm; import soot.jimple.spark.sets.P2SetFactory; import soot.jimple.toolkits.annotation.arraycheck.Array2ndDimensionSymbol; import soot.jimple.toolkits.pointer.UnionFactory; import soot.jimple.toolkits.pointer.util.NativeHelper; import soot.jimple.toolkits.typing.ClassHierarchy; import soot.toolkits.astmetrics.ClassData; import soot.toolkits.scalar.Pair; /** A class to group together all the global variables in Soot. */ public class G extends Singletons { public static interface GlobalObjectGetter { public G getG(); public void reset(); } public static G v() { return objectGetter.getG(); } public static void reset() { objectGetter.reset(); } private static GlobalObjectGetter objectGetter = new GlobalObjectGetter() { private G instance = new G(); @Override public G getG() { return instance; } @Override public void reset() { instance = new G(); } }; public static void setGlobalObjectGetter(GlobalObjectGetter newGetter) { objectGetter = newGetter; } /** * Deprecated use logging via slf4j instead */ @Deprecated public PrintStream out = System.out; public class Global { } public long coffi_BasicBlock_ids = 0; public Utf8_Enumeration coffi_CONSTANT_Utf8_info_e1 = new Utf8_Enumeration(); public Utf8_Enumeration coffi_CONSTANT_Utf8_info_e2 = new Utf8_Enumeration(); public int SETNodeLabel_uniqueId = 0; public HashMap<SETNode, SETBasicBlock> SETBasicBlock_binding = new HashMap<SETNode, SETBasicBlock>(); public boolean ASTAnalysis_modified; public NativeHelper NativeHelper_helper = null; public P2SetFactory newSetFactory; public P2SetFactory oldSetFactory; public Map<Pair<SootMethod, Integer>, Parm> Parm_pairToElement = new HashMap<Pair<SootMethod, Integer>, Parm>(); public int SparkNativeHelper_tempVar = 0; public int PaddleNativeHelper_tempVar = 0; public boolean PointsToSetInternal_warnedAlready = false; public HashMap<SootMethod, MethodPAG> MethodPAG_methodToPag = new HashMap<SootMethod, MethodPAG>(); public Set MethodRWSet_allGlobals = new HashSet(); public Set MethodRWSet_allFields = new HashSet(); public int GeneralConstObject_counter = 0; public UnionFactory Union_factory = null; public HashMap<Object, Array2ndDimensionSymbol> Array2ndDimensionSymbol_pool = new HashMap<Object, Array2ndDimensionSymbol>(); public List<Timer> Timer_outstandingTimers = new ArrayList<Timer>(); public boolean Timer_isGarbageCollecting; public Timer Timer_forcedGarbageCollectionTimer = new Timer("gc"); public int Timer_count; public final Map<Scene, ClassHierarchy> ClassHierarchy_classHierarchyMap = new HashMap<Scene, ClassHierarchy>(); public final Map<MethodContext, MethodContext> MethodContext_map = new HashMap<MethodContext, MethodContext>(); public DalvikThrowAnalysis interproceduralDalvikThrowAnalysis = null; public DalvikThrowAnalysis interproceduralDalvikThrowAnalysis() { if (this.interproceduralDalvikThrowAnalysis == null) { this.interproceduralDalvikThrowAnalysis = new DalvikThrowAnalysis(g, true); } return this.interproceduralDalvikThrowAnalysis; } public boolean ASTTransformations_modified; /* * 16th Feb 2006 Nomair The AST transformations are unfortunately non-monotonic. Infact one transformation on each * iteration simply reverses the bodies of an if-else To make the remaining transformations monotonic this transformation * is handled with a separate flag...clumsy but works */ public boolean ASTIfElseFlipped; /* * Nomair A. Naeem January 15th 2006 Added For Dava.toolkits.AST.transformations.SuperFirstStmtHandler * * The SootMethodAddedByDava is checked by the PackManager after decompiling methods for a class. If any additional methods * were added by the decompiler (refer to filer SuperFirstStmtHandler) SootMethodsAdded ArrayList contains these method. * These methods are then added to the SootClass * * Some of these newly added methods make use of an object of a static inner class DavaSuperHandler which is to be output * in the decompilers output. The class is marked to need a DavaSuperHandlerClass by adding it into the * SootClassNeedsDavaSuperHandlerClass list. The DavaPrinter when printing out the class checks this list and if this * class's name exists in the list prints out an implementation of DavSuperHandler */ public boolean SootMethodAddedByDava; public ArrayList<SootClass> SootClassNeedsDavaSuperHandlerClass = new ArrayList<SootClass>(); public ArrayList<SootMethod> SootMethodsAdded = new ArrayList<SootMethod>(); // ASTMetrics Data public ArrayList<ClassData> ASTMetricsData = new ArrayList<ClassData>(); public void resetSpark() { // We reset SPARK the hard way. for (Method m : getClass().getSuperclass().getDeclaredMethods()) { if (m.getName().startsWith("release_soot_jimple_spark_")) { try { m.invoke(this); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } // Reset some other stuff directly in this class MethodPAG_methodToPag.clear(); MethodRWSet_allFields.clear(); MethodRWSet_allGlobals.clear(); newSetFactory = null; oldSetFactory = null; Parm_pairToElement.clear(); // We need to reset the virtual call resolution table release_soot_jimple_toolkits_callgraph_VirtualCalls(); } }
6,948
36.160428
125
java
soot
soot-master/src/main/java/soot/HasPhaseOptions.java
package soot; /*- * #%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% */ /** Interface for things like Packs and phases that have phase options. */ public interface HasPhaseOptions { public String getDeclaredOptions(); public String getDefaultOptions(); public String getPhaseName(); }
1,034
30.363636
74
java
soot
soot-master/src/main/java/soot/Hierarchy.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.jimple.SpecialInvokeExpr; import soot.util.ArraySet; import soot.util.Chain; /** * Represents the class hierarchy. It is closely linked to a Scene, and must be recreated if the Scene changes. * * The general convention is that if a method name contains "Including", then it returns the non-strict result; otherwise, it * does a strict query (e.g. strict superclass). */ public class Hierarchy { // These two maps are not filled in the constructor. protected Map<SootClass, List<SootClass>> classToSubclasses; protected Map<SootClass, List<SootClass>> interfaceToSubinterfaces; protected Map<SootClass, List<SootClass>> interfaceToSuperinterfaces; protected Map<SootClass, List<SootClass>> classToDirSubclasses; protected Map<SootClass, List<SootClass>> interfaceToDirSubinterfaces; protected Map<SootClass, List<SootClass>> interfaceToDirSuperinterfaces; // This holds the direct implementers. protected Map<SootClass, List<SootClass>> interfaceToDirImplementers; final Scene sc; final int state; /** Constructs a hierarchy from the current scene. */ public Hierarchy() { this.sc = Scene.v(); this.state = sc.getState(); // Well, this used to be describable by 'Duh'. // Construct the subclasses hierarchy and the subinterfaces hierarchy. { Chain<SootClass> allClasses = sc.getClasses(); final int mapSize = allClasses.size() * 2 + 1; this.classToSubclasses = new HashMap<SootClass, List<SootClass>>(mapSize, 0.7f); this.interfaceToSubinterfaces = new HashMap<SootClass, List<SootClass>>(mapSize, 0.7f); this.interfaceToSuperinterfaces = new HashMap<SootClass, List<SootClass>>(mapSize, 0.7f); this.classToDirSubclasses = new HashMap<SootClass, List<SootClass>>(mapSize, 0.7f); this.interfaceToDirSubinterfaces = new HashMap<SootClass, List<SootClass>>(mapSize, 0.7f); this.interfaceToDirSuperinterfaces = new HashMap<SootClass, List<SootClass>>(mapSize, 0.7f); this.interfaceToDirImplementers = new HashMap<SootClass, List<SootClass>>(mapSize, 0.7f); initializeHierarchy(allClasses); } } /** * Initializes the hierarchy given a chain of all classes that shall be included in the hierarchy * * @param allClasses * The chain of all classes to be included in the hierarchy */ protected void initializeHierarchy(Chain<SootClass> allClasses) { for (SootClass c : allClasses) { if (c.resolvingLevel() < SootClass.HIERARCHY) { continue; } if (c.isInterface()) { interfaceToDirSubinterfaces.put(c, new ArrayList<SootClass>()); interfaceToDirSuperinterfaces.put(c, new ArrayList<SootClass>()); interfaceToDirImplementers.put(c, new ArrayList<SootClass>()); } else { classToDirSubclasses.put(c, new ArrayList<SootClass>()); } } for (SootClass c : allClasses) { if (c.resolvingLevel() < SootClass.HIERARCHY) { continue; } if (c.hasSuperclass()) { if (c.isInterface()) { List<SootClass> l2 = interfaceToDirSuperinterfaces.get(c); for (SootClass i : c.getInterfaces()) { if (c.resolvingLevel() < SootClass.HIERARCHY) { continue; } List<SootClass> l = interfaceToDirSubinterfaces.get(i); if (l != null) { l.add(c); } if (l2 != null) { l2.add(i); } } } else { List<SootClass> l = classToDirSubclasses.get(c.getSuperclass()); if (l != null) { l.add(c); } for (SootClass i : c.getInterfaces()) { if (c.resolvingLevel() < SootClass.HIERARCHY) { continue; } List<SootClass> l2 = interfaceToDirImplementers.get(i); if (l2 != null) { l2.add(c); } } } } } // Fill the directImplementers lists with subclasses. for (SootClass c : allClasses) { if (c.resolvingLevel() < SootClass.HIERARCHY) { continue; } if (c.isInterface()) { Set<SootClass> s = new ArraySet<SootClass>(); for (SootClass c0 : interfaceToDirImplementers.get(c)) { if (c.resolvingLevel() < SootClass.HIERARCHY) { continue; } s.addAll(getSubclassesOfIncluding(c0)); } interfaceToDirImplementers.put(c, new ArrayList<SootClass>(s)); } else if (c.hasSuperclass()) { List<SootClass> l = classToDirSubclasses.get(c); if (l != null) { classToDirSubclasses.put(c, new ArrayList<>(l)); } } } } protected void checkState() { if (state != sc.getState()) { throw new ConcurrentModificationException("Scene changed for Hierarchy!"); } } // This includes c in the list of subclasses. /** Returns a list of subclasses of c, including itself. */ public List<SootClass> getSubclassesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) { throw new RuntimeException("class needed!"); } List<SootClass> subclasses = getSubclassesOf(c); List<SootClass> result = new ArrayList<SootClass>(subclasses.size() + 1); result.addAll(subclasses); result.add(c); return Collections.unmodifiableList(result); } /** Returns a list of subclasses of c, excluding itself. */ public List<SootClass> getSubclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) { throw new RuntimeException("class needed!"); } checkState(); // If already cached, return the value. List<SootClass> retVal = classToSubclasses.get(c); if (retVal != null) { return retVal; } // Otherwise, build up the hashmap. { ArrayList<SootClass> l = new ArrayList<SootClass>(); for (SootClass cls : classToDirSubclasses.get(c)) { if (cls.resolvingLevel() < SootClass.HIERARCHY) { continue; } l.addAll(getSubclassesOfIncluding(cls)); } l.trimToSize(); retVal = Collections.unmodifiableList(l); } classToSubclasses.put(c, retVal); return retVal; } /** * Returns a list of superclasses of {@code sootClass}, including itself. * * @param sootClass * the <strong>class</strong> of which superclasses will be taken. Must not be {@code null} or interface * @return list of superclasses, including itself * @throws IllegalArgumentException * when passed class is an interface * @throws NullPointerException * when passed argument is {@code null} */ public List<SootClass> getSuperclassesOfIncluding(SootClass sootClass) { List<SootClass> superclasses = getSuperclassesOf(sootClass); List<SootClass> result = new ArrayList<>(superclasses.size() + 1); result.add(sootClass); result.addAll(superclasses); return Collections.unmodifiableList(result); } /** * Returns a list of <strong>direct</strong> superclasses of passed class in reverse order, starting with its parent. * * @param sootClass * the <strong>class</strong> of which superclasses will be taken. Must not be {@code null} or interface * @return list of superclasses * @throws IllegalArgumentException * when passed class is an interface * @throws NullPointerException * when passed argument is {@code null} */ public List<SootClass> getSuperclassesOf(SootClass sootClass) { sootClass.checkLevel(SootClass.HIERARCHY); if (sootClass.isInterface()) { throw new IllegalArgumentException(sootClass.getName() + " is an interface, but class is expected"); } checkState(); final List<SootClass> superclasses = new ArrayList<>(); for (SootClass current = sootClass; current.hasSuperclass();) { SootClass superclass = current.getSuperclass(); superclasses.add(superclass); current = superclass; } return Collections.unmodifiableList(superclasses); } /** * Returns a list of subinterfaces of sootClass, including itself. * * @param sootClass * the <strong>interface</strong> of which subinterfaces will be taken. Must not be {@code null} or class * @return list of subinterfaces, including passed one * @throws IllegalArgumentException * when passed class is a class * @throws NullPointerException * when passed argument is {@code null} */ public List<SootClass> getSubinterfacesOfIncluding(SootClass sootClass) { List<SootClass> subinterfaces = getSubinterfacesOf(sootClass); List<SootClass> result = new ArrayList<>(subinterfaces.size() + 1); result.addAll(subinterfaces); result.add(sootClass); return Collections.unmodifiableList(result); } /** * Returns a list of subinterfaces of sootClass, excluding itself. * * @param sootClass * the <strong>interface</strong> of which subinterfaces will be taken. Must not be {@code null} or class * @return list of subinterfaces, including passed one * @throws IllegalArgumentException * when passed sootClass is a class * @throws NullPointerException * when passed argument is {@code null} */ public List<SootClass> getSubinterfacesOf(SootClass sootClass) { sootClass.checkLevel(SootClass.HIERARCHY); if (!sootClass.isInterface()) { throw new IllegalArgumentException(sootClass.getName() + " is a class, but interface is expected"); } checkState(); // If already cached, return the value. List<SootClass> retVal = interfaceToSubinterfaces.get(sootClass); if (retVal != null) { return retVal; } // Otherwise, build up the hashmap. { List<SootClass> directSubInterfaces = interfaceToDirSubinterfaces.get(sootClass); if (directSubInterfaces == null || directSubInterfaces.isEmpty()) { return Collections.emptyList(); } final ArrayList<SootClass> l = new ArrayList<>(); for (SootClass si : directSubInterfaces) { l.addAll(getSubinterfacesOfIncluding(si)); } l.trimToSize(); retVal = Collections.unmodifiableList(l); } interfaceToSubinterfaces.put(sootClass, retVal); return retVal; } /** Returns a list of superinterfaces of c, including itself. */ public List<SootClass> getSuperinterfacesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) { throw new RuntimeException("interface needed!"); } List<SootClass> superinterfaces = getSuperinterfacesOf(c); List<SootClass> result = new ArrayList<SootClass>(superinterfaces.size() + 1); result.addAll(superinterfaces); result.add(c); return Collections.unmodifiableList(result); } /** Returns a list of superinterfaces of c, excluding itself. */ public List<SootClass> getSuperinterfacesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) { throw new RuntimeException("interface needed!"); } checkState(); // If already cached, return the value. List<SootClass> retVal = interfaceToSuperinterfaces.get(c); if (retVal != null) { return retVal; } // Otherwise, build up the hashmap. { ArrayList<SootClass> l = new ArrayList<SootClass>(); for (SootClass si : interfaceToDirSuperinterfaces.get(c)) { l.addAll(getSuperinterfacesOfIncluding(si)); } l.trimToSize(); retVal = Collections.unmodifiableList(l); } interfaceToSuperinterfaces.put(c, retVal); return retVal; } /** Returns a list of direct superclasses of c, excluding c. */ public List<SootClass> getDirectSuperclassesOf(SootClass c) { throw new RuntimeException("Not implemented yet!"); } /** Returns a list of direct subclasses of c, excluding c. */ public List<SootClass> getDirectSubclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) { throw new RuntimeException("class needed!"); } checkState(); return Collections.unmodifiableList(classToDirSubclasses.get(c)); } // This includes c in the list of subclasses. /** Returns a list of direct subclasses of c, including c. */ public List<SootClass> getDirectSubclassesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) { throw new RuntimeException("class needed!"); } checkState(); List<SootClass> subclasses = classToDirSubclasses.get(c); List<SootClass> l = new ArrayList<SootClass>(subclasses.size() + 1); l.addAll(subclasses); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of direct superinterfaces of c. */ public List<SootClass> getDirectSuperinterfacesOf(SootClass c) { throw new RuntimeException("Not implemented yet!"); } /** Returns a list of direct subinterfaces of c. */ public List<SootClass> getDirectSubinterfacesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) { throw new RuntimeException("interface needed!"); } checkState(); return Collections.unmodifiableList(interfaceToDirSubinterfaces.get(c)); } /** Returns a list of direct subinterfaces of c, including itself. */ public List<SootClass> getDirectSubinterfacesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) { throw new RuntimeException("interface needed!"); } checkState(); List<SootClass> subinterfaces = interfaceToDirSubinterfaces.get(c); List<SootClass> l = new ArrayList<SootClass>(subinterfaces.size() + 1); l.addAll(subinterfaces); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of direct implementers of c, excluding itself. */ public List<SootClass> getDirectImplementersOf(SootClass i) { i.checkLevel(SootClass.HIERARCHY); if (!i.isInterface()) { throw new RuntimeException("interface needed; got " + i); } checkState(); return Collections.unmodifiableList(interfaceToDirImplementers.get(i)); } /** Returns a list of implementers of c, excluding itself. */ public List<SootClass> getImplementersOf(SootClass i) { i.checkLevel(SootClass.HIERARCHY); if (!i.isInterface()) { throw new RuntimeException("interface needed; got " + i); } checkState(); ArraySet<SootClass> set = new ArraySet<SootClass>(); for (SootClass c : getSubinterfacesOfIncluding(i)) { set.addAll(getDirectImplementersOf(c)); } return Collections.unmodifiableList(new ArrayList<SootClass>(set)); } /** * Returns true if child is a subclass of possibleParent. If one of the known parent classes is phantom, we conservatively * assume that the current class might be a child. */ public boolean isClassSubclassOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); List<SootClass> parentClasses = getSuperclassesOf(child); if (parentClasses.contains(possibleParent)) { return true; } for (SootClass sc : parentClasses) { if (sc.isPhantom()) { return true; } } return false; } /** * Returns true if child is, or is a subclass of, possibleParent. If one of the known parent classes is phantom, we * conservatively assume that the current class might be a child. */ public boolean isClassSubclassOfIncluding(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); List<SootClass> parentClasses = getSuperclassesOfIncluding(child); if (parentClasses.contains(possibleParent)) { return true; } for (SootClass sc : parentClasses) { if (sc.isPhantom()) { return true; } } return false; } /** Returns true if child is a direct subclass of possibleParent. */ public boolean isClassDirectSubclassOf(SootClass c, SootClass c2) { throw new RuntimeException("Not implemented yet!"); } /** Returns true if child is a superclass of possibleParent. */ public boolean isClassSuperclassOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSubclassesOf(parent).contains(possibleChild); } /** Returns true if parent is, or is a superclass of, possibleChild. */ public boolean isClassSuperclassOfIncluding(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSubclassesOfIncluding(parent).contains(possibleChild); } /** Returns true if child is a subinterface of possibleParent. */ public boolean isInterfaceSubinterfaceOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); return getSubinterfacesOf(possibleParent).contains(child); } /** Returns true if child is a direct subinterface of possibleParent. */ public boolean isInterfaceDirectSubinterfaceOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); return getDirectSubinterfacesOf(possibleParent).contains(child); } /** Returns true if parent is a superinterface of possibleChild. */ public boolean isInterfaceSuperinterfaceOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSuperinterfacesOf(possibleChild).contains(parent); } /** Returns true if parent is a direct superinterface of possibleChild. */ public boolean isInterfaceDirectSuperinterfaceOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getDirectSuperinterfacesOf(possibleChild).contains(parent); } /** * Returns the most specific type which is an ancestor of both c1 and c2. */ public SootClass getLeastCommonSuperclassOf(SootClass c1, SootClass c2) { c1.checkLevel(SootClass.HIERARCHY); c2.checkLevel(SootClass.HIERARCHY); throw new RuntimeException("Not implemented yet!"); } // Questions about method invocation. /** * Checks whether check is a visible class in view of the from class. It assumes that protected and private classes do not * exit. If they exist and check is either protected or private, the check will return false. */ public boolean isVisible(SootClass from, SootClass check) { if (check.isPublic()) { return true; } if (check.isProtected() || check.isPrivate()) { return false; } // package visibility return from.getJavaPackageName().equals(check.getJavaPackageName()); } /** * Returns true if the classmember m is visible from code in the class from. */ public boolean isVisible(SootClass from, ClassMember m) { from.checkLevel(SootClass.HIERARCHY); final SootClass declaringClass = m.getDeclaringClass(); declaringClass.checkLevel(SootClass.HIERARCHY); if (!isVisible(from, declaringClass)) { return false; } if (m.isPublic()) { return true; } if (m.isPrivate()) { return from.equals(declaringClass); } if (m.isProtected()) { return isClassSubclassOfIncluding(from, declaringClass) || from.getJavaPackageName().equals(declaringClass.getJavaPackageName()); } // m is package return from.getJavaPackageName().equals(declaringClass.getJavaPackageName()); } /** * Given an object of actual type C (o = new C()), returns the method which will be called on an o.f() invocation. */ public SootMethod resolveConcreteDispatch(SootClass concreteType, SootMethod m) { concreteType.checkLevel(SootClass.HIERARCHY); m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); if (concreteType.isInterface()) { throw new RuntimeException("class needed!"); } final String methodSig = m.getSubSignature(); for (SootClass c : getSuperclassesOfIncluding(concreteType)) { SootMethod sm = c.getMethodUnsafe(methodSig); if (sm != null && isVisible(c, m)) { return sm; } } throw new RuntimeException("could not resolve concrete dispatch!\nType: " + concreteType + "\nMethod: " + m); } /** * Given a set of definite receiver types, returns a list of possible targets. */ public List<SootMethod> resolveConcreteDispatch(List<Type> classes, SootMethod m) { m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); Set<SootMethod> s = new ArraySet<SootMethod>(); for (Type cls : classes) { if (cls instanceof RefType) { s.add(resolveConcreteDispatch(((RefType) cls).getSootClass(), m)); } else if (cls instanceof ArrayType) { s.add(resolveConcreteDispatch(RefType.v("java.lang.Object").getSootClass(), m)); } else { throw new RuntimeException("Unable to resolve concrete dispatch of type " + cls); } } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } // what can get called for c & all its subclasses /** * Given an abstract dispatch to an object of type c and a method m, gives a list of possible receiver methods. */ public List<SootMethod> resolveAbstractDispatch(SootClass c, SootMethod m) { c.checkLevel(SootClass.HIERARCHY); m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); Collection<SootClass> classes; if (c.isInterface()) { classes = new HashSet<SootClass>(); for (SootClass sootClass : getImplementersOf(c)) { classes.addAll(getSubclassesOfIncluding(sootClass)); } } else { classes = getSubclassesOfIncluding(c); } Set<SootMethod> s = new ArraySet<SootMethod>(); for (SootClass cl : classes) { if (!Modifier.isAbstract(cl.getModifiers())) { s.add(resolveConcreteDispatch(cl, m)); } } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } // what can get called if you have a set of possible receiver types /** * Returns a list of possible targets for the given method and set of receiver types. */ public List<SootMethod> resolveAbstractDispatch(List<SootClass> classes, SootMethod m) { m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); Set<SootMethod> s = new ArraySet<SootMethod>(); for (SootClass sootClass : classes) { s.addAll(resolveAbstractDispatch(sootClass, m)); } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } /** Returns the target for the given SpecialInvokeExpr. */ public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) { final SootClass containerClass = container.getDeclaringClass(); containerClass.checkLevel(SootClass.HIERARCHY); final SootMethod target = ie.getMethod(); final SootClass targetClass = target.getDeclaringClass(); targetClass.checkLevel(SootClass.HIERARCHY); /* * This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the * definition of invokespecial. */ if ("<init>".equals(target.getName()) || target.isPrivate()) { return target; } else if (isClassSubclassOf(targetClass, containerClass)) { return resolveConcreteDispatch(containerClass, target); } else { return target; } } }
24,915
33.225275
125
java
soot
soot-master/src/main/java/soot/ITypeSwitch.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** Describes a switch on internal types. */ interface ITypeSwitch extends soot.util.Switch { void caseArrayType(ArrayType t); void caseBooleanType(BooleanType t); void caseByteType(ByteType t); void caseCharType(CharType t); void caseDoubleType(DoubleType t); void caseFloatType(FloatType t); void caseIntType(IntType t); void caseLongType(LongType t); void caseRefType(RefType t); void caseShortType(ShortType t); void caseStmtAddressType(StmtAddressType t); void caseUnknownType(UnknownType t); void caseVoidType(VoidType t); void caseAnySubType(AnySubType t); void caseNullType(NullType t); void caseErroneousType(ErroneousType t); void defaultCase(Type t); /** * @deprecated Replaced by defaultCase(Type) * @see #defaultCase(Type) */ @Deprecated void caseDefault(Type t); }
1,667
23.529412
71
java
soot
soot-master/src/main/java/soot/IdentityUnit.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** A unit that assigns to a variable from one of {parameters, this, caughtexception}. */ public interface IdentityUnit extends Unit { public Value getLeftOp(); public Value getRightOp(); public ValueBox getLeftOpBox(); public ValueBox getRightOpBox(); }
1,088
30.114286
89
java
soot
soot-master/src/main/java/soot/Immediate.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A local or constant. */ public interface Immediate extends Value { }
890
28.7
71
java
soot
soot-master/src/main/java/soot/IntType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java built-in type 'int'. Implemented as a singleton. */ @SuppressWarnings("serial") public class IntType extends PrimType implements IntegerType { public static final int HASHCODE = 0xB747239F; public IntType(Singletons.Global g) { } public static IntType v() { return G.v().soot_IntType(); } @Override public boolean equals(Object t) { return this == t; } @Override public int hashCode() { return HASHCODE; } @Override public String toString() { return "int"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseIntType(this); } @Override public RefType boxedType() { return RefType.v("java.lang.Integer"); } @Override public Class<?> getJavaBoxedType() { return Integer.class; } @Override public Class<?> getJavaPrimitiveType() { return int.class; } }
1,746
21.397436
83
java
soot
soot-master/src/main/java/soot/IntegerType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Etienne M. Gagnon <egagnon@j-meg.com>. All rights reserved. * %% * 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% */ /** * Soot interface implemented by all classes representing integer types [boolean, byte, short, char, and int]. */ public interface IntegerType { }
1,012
32.766667
110
java
soot
soot-master/src/main/java/soot/JastAddInitialResolver.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2008 Eric Bodden * Copyright (C) 2008 Torbjorn Ekman * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.JastAddJ.BodyDecl; import soot.JastAddJ.CompilationUnit; import soot.JastAddJ.ConstructorDecl; import soot.JastAddJ.MethodDecl; import soot.JastAddJ.Program; import soot.JastAddJ.TypeDecl; import soot.javaToJimple.IInitialResolver; /** * An {@link IInitialResolver} for the JastAdd frontend. * * @author Torbjorn Ekman * @author Eric Bodden */ public class JastAddInitialResolver implements IInitialResolver { private static final Logger logger = LoggerFactory.getLogger(JastAddInitialResolver.class); public JastAddInitialResolver(soot.Singletons.Global g) { } public static JastAddInitialResolver v() { return soot.G.v().soot_JastAddInitialResolver(); } protected Map<String, CompilationUnit> classNameToCU = new HashMap<String, CompilationUnit>(); public void formAst(String fullPath, List<String> locations, String className) { Program program = SootResolver.v().getProgram(); CompilationUnit u = program.getCachedOrLoadCompilationUnit(fullPath); if (u != null && !u.isResolved) { u.isResolved = true; java.util.ArrayList<soot.JastAddJ.Problem> errors = new java.util.ArrayList<soot.JastAddJ.Problem>(); u.errorCheck(errors); if (!errors.isEmpty()) { for (soot.JastAddJ.Problem p : errors) { logger.debug("" + p); } // die throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED, "there were errors during parsing and/or type checking (JastAdd frontend)"); } u.transformation(); u.jimplify1phase1(); u.jimplify1phase2(); HashSet<SootClass> types = new HashSet<SootClass>(); for (TypeDecl typeDecl : u.getTypeDecls()) { collectTypeDecl(typeDecl, types); } if (types.isEmpty()) { classNameToCU.put(className, u); } else { for (SootClass sc : types) { classNameToCU.put(sc.getName(), u); } } } } @SuppressWarnings("unchecked") private void collectTypeDecl(TypeDecl typeDecl, HashSet<SootClass> types) { types.add(typeDecl.getSootClassDecl()); for (TypeDecl nestedType : (Collection<TypeDecl>) typeDecl.nestedTypes()) { collectTypeDecl(nestedType, types); } } @SuppressWarnings("unchecked") private TypeDecl findNestedTypeDecl(TypeDecl typeDecl, SootClass sc) { if (typeDecl.sootClass() == sc) { return typeDecl; } for (TypeDecl nestedType : (Collection<TypeDecl>) typeDecl.nestedTypes()) { TypeDecl t = findNestedTypeDecl(nestedType, sc); if (t != null) { return t; } } return null; } public Dependencies resolveFromJavaFile(SootClass sootclass) { CompilationUnit u = classNameToCU.get(sootclass.getName()); if (u == null) { throw new RuntimeException("Error: couldn't find class: " + sootclass.getName() + " are the packages set properly?"); } HashSet<SootClass> types = new HashSet<SootClass>(); for (TypeDecl typeDecl : u.getTypeDecls()) { collectTypeDecl(typeDecl, types); } Dependencies deps = new Dependencies(); u.collectTypesToHierarchy(deps.typesToHierarchy); u.collectTypesToSignatures(deps.typesToSignature); for (SootClass sc : types) { for (SootMethod m : sc.getMethods()) { m.setSource(new MethodSource() { public Body getBody(SootMethod m, String phaseName) { SootClass sc = m.getDeclaringClass(); CompilationUnit u = classNameToCU.get(sc.getName()); for (TypeDecl typeDecl : u.getTypeDecls()) { typeDecl = findNestedTypeDecl(typeDecl, sc); if (typeDecl != null) { if (typeDecl.clinit == m) { typeDecl.jimplify2clinit(); return m.getActiveBody(); } for (BodyDecl bodyDecl : typeDecl.getBodyDecls()) { if (bodyDecl instanceof MethodDecl) { MethodDecl methodDecl = (MethodDecl) bodyDecl; if (m.equals(methodDecl.sootMethod)) { methodDecl.jimplify2(); return m.getActiveBody(); } } else if (bodyDecl instanceof ConstructorDecl) { ConstructorDecl constrDecl = (ConstructorDecl) bodyDecl; if (m.equals(constrDecl.sootMethod)) { constrDecl.jimplify2(); return m.getActiveBody(); } } } } } throw new RuntimeException( "Could not find body for " + m.getSignature() + " in " + m.getDeclaringClass().getName()); } }); } } return deps; } }
5,824
33.064327
123
java
soot
soot-master/src/main/java/soot/JavaClassProvider.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.options.Options; /** * A class provider looks for a file of a specific format for a specified class, and returns a ClassSource for it if it finds * it. */ public class JavaClassProvider implements ClassProvider { public static class JarException extends RuntimeException { private static final long serialVersionUID = 1L; public JarException(String className) { super("Class " + className + " was found in an archive, but Soot doesn't support reading source files out of an archive"); } } /** * Look for the specified class. Return a ClassSource for it if found, or null if it was not found. */ @Override public ClassSource find(String className) { if (Options.v().polyglot() && soot.javaToJimple.InitialResolver.v().hasASTForSootName(className)) { soot.javaToJimple.InitialResolver.v().setASTForSootName(className); return new JavaClassSource(className); } else { // jastAdd; or polyglot AST not yet produced /* * 04.04.2006 mbatch if there is a $ in the name, we need to check if it's a real file, not just inner class */ boolean checkAgain = className.indexOf('$') >= 0; FoundFile file = null; try { final SourceLocator loc = SourceLocator.v(); String javaClassName = loc.getSourceForClass(className); file = loc.lookupInClassPath(javaClassName.replace('.', '/') + ".java"); /* * 04.04.2006 mbatch if inner class not found, check if it's a real file */ if (file == null && checkAgain) { file = loc.lookupInClassPath(className.replace('.', '/') + ".java"); } /* 04.04.2006 mbatch end */ if (file == null) { return null; } if (file.isZipFile()) { throw new JarException(className); } return new JavaClassSource(className, file.getFile()); } finally { if (file != null) { file.close(); } } } } }
2,822
31.825581
125
java
soot
soot-master/src/main/java/soot/JavaClassSource.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import polyglot.ast.Node; import soot.javaToJimple.IInitialResolver; import soot.javaToJimple.IInitialResolver.Dependencies; import soot.javaToJimple.InitialResolver; import soot.options.Options; import soot.toolkits.astmetrics.ComputeASTMetrics; /** * A class source for resolving from .java files using javaToJimple. */ public class JavaClassSource extends ClassSource { private static final Logger logger = LoggerFactory.getLogger(JavaClassSource.class); private final File fullPath; public JavaClassSource(String className, File fullPath) { super(className); this.fullPath = fullPath; } public JavaClassSource(String className) { this(className, null); } @Override public Dependencies resolve(SootClass sc) { if (Options.v().verbose()) { logger.debug("resolving [from .java]: " + className); } IInitialResolver resolver = Options.v().polyglot() ? InitialResolver.v() : JastAddInitialResolver.v(); if (fullPath != null) { resolver.formAst(fullPath.getPath(), SourceLocator.v().sourcePath(), className); } // System.out.println("about to call initial resolver in j2j: "+sc.getName()); Dependencies references = resolver.resolveFromJavaFile(sc); /* * 1st March 2006 Nomair This seems to be a good place to calculate all the AST Metrics needed from Java's AST */ if (Options.v().ast_metrics()) { // System.out.println("CALLING COMPUTEASTMETRICS!!!!!!!"); Node ast = InitialResolver.v().getAst(); if (ast == null) { logger.debug("No compatible AST available for AST metrics. Skipping. Try -polyglot option."); } else { ComputeASTMetrics metrics = new ComputeASTMetrics(ast); metrics.apply(); } } return references; } }
2,673
30.093023
114
java
soot
soot-master/src/main/java/soot/JavaToJimpleBodyPack.java
package soot; /*- * #%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.jimple.JimpleBody; import soot.options.JJOptions; import soot.options.Options; /** * A wrapper object for a pack of optimizations. Provides chain-like operations, except that the key is the phase name. This * is a specific one for the very messy jb phase. */ public class JavaToJimpleBodyPack extends BodyPack { public JavaToJimpleBodyPack() { super("jj"); } /** * Applies the transformations corresponding to the given options. */ private void applyPhaseOptions(JimpleBody b, Map<String, String> opts) { JJOptions options = new JJOptions(opts); if (options.use_original_names()) { PhaseOptions.v().setPhaseOptionIfUnset("jj.lns", "only-stack-locals"); } final PackManager pacman = PackManager.v(); final boolean time = Options.v().time(); if (time) { Timers.v().splitTimer.start(); } pacman.getTransform("jj.ls").apply(b); if (time) { Timers.v().splitTimer.end(); } pacman.getTransform("jj.a").apply(b); pacman.getTransform("jj.ule").apply(b); pacman.getTransform("jj.ne").apply(b); if (time) { Timers.v().assignTimer.start(); } pacman.getTransform("jj.tr").apply(b); if (time) { Timers.v().assignTimer.end(); } if (options.use_original_names()) { pacman.getTransform("jj.ulp").apply(b); } pacman.getTransform("jj.lns").apply(b); pacman.getTransform("jj.cp").apply(b); pacman.getTransform("jj.dae").apply(b); pacman.getTransform("jj.cp-ule").apply(b); pacman.getTransform("jj.lp").apply(b); // pacman.getTransform( "jj.ct" ).apply( b ); pacman.getTransform("jj.uce").apply(b); if (time) { Timers.v().stmtCount += b.getUnits().size(); } } @Override protected void internalApply(Body b) { applyPhaseOptions((JimpleBody) b, PhaseOptions.v().getPhaseOptions(getPhaseName())); } }
2,731
26.59596
124
java
soot
soot-master/src/main/java/soot/JimpleBodyPack.java
package soot; /*- * #%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.jimple.JimpleBody; import soot.options.JBOptions; import soot.options.Options; /** * A wrapper object for a pack of optimizations. Provides chain-like operations, except that the key is the phase name. This * is a specific one for the very messy jb phase. */ public class JimpleBodyPack extends BodyPack { public JimpleBodyPack() { super("jb"); } /** * Applies the transformations corresponding to the given options. */ private void applyPhaseOptions(JimpleBody b, Map<String, String> opts) { JBOptions options = new JBOptions(opts); if (options.use_original_names()) { PhaseOptions.v().setPhaseOptionIfUnset("jb.lns", "only-stack-locals"); } final PackManager pacman = PackManager.v(); final boolean time = Options.v().time(); if (time) { Timers.v().splitTimer.start(); } pacman.getTransform("jb.tt").apply(b); // TrapTigthener pacman.getTransform("jb.dtr").apply(b); // DuplicateCatchAllTrapRemover // UnreachableCodeEliminator: We need to do this before splitting // locals for not creating disconnected islands of useless assignments // that afterwards mess up type assignment. pacman.getTransform("jb.uce").apply(b); pacman.getTransform("jb.ls").apply(b); pacman.getTransform("jb.sils").apply(b); if (time) { Timers.v().splitTimer.end(); } pacman.getTransform("jb.a").apply(b); pacman.getTransform("jb.ule").apply(b); if (time) { Timers.v().assignTimer.start(); } pacman.getTransform("jb.tr").apply(b); if (time) { Timers.v().assignTimer.end(); } if (options.use_original_names()) { pacman.getTransform("jb.ulp").apply(b); } pacman.getTransform("jb.lns").apply(b); // LocalNameStandardizer pacman.getTransform("jb.cp").apply(b); // CopyPropagator pacman.getTransform("jb.dae").apply(b); // DeadAssignmentElimintaor pacman.getTransform("jb.cp-ule").apply(b); // UnusedLocalEliminator pacman.getTransform("jb.lp").apply(b); // LocalPacker pacman.getTransform("jb.ne").apply(b); // NopEliminator pacman.getTransform("jb.uce").apply(b); // UnreachableCodeEliminator: Again, we might have new dead code // LocalNameStandardizer: After all these changes, some locals // may end up being eliminated. If we want a stable local iteration // order between soot instances, running LocalNameStandardizer // again after all other changes is required. if (options.stabilize_local_names()) { PhaseOptions.v().setPhaseOption("jb.lns", "sort-locals:true"); pacman.getTransform("jb.lns").apply(b); } if (time) { Timers.v().stmtCount += b.getUnits().size(); } } @Override protected void internalApply(Body b) { applyPhaseOptions((JimpleBody) b, PhaseOptions.v().getPhaseOptions(getPhaseName())); } }
3,702
31.2
124
java
soot
soot-master/src/main/java/soot/JimpleClassProvider.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.options.Options; /** * A class provider looks for a file of a specific format for a specified class, and returns a ClassSource for it if it finds * it. */ public class JimpleClassProvider implements ClassProvider { /** * Look for the specified class. Return a ClassSource for it if found, or null if it was not found. */ @Override public ClassSource find(String className) { FoundFile file = SourceLocator.v().lookupInClassPath(className + ".jimple"); if (file == null) { if (Options.v().permissive_resolving()) { file = SourceLocator.v().lookupInClassPath(className.replace('.', '/') + ".jimple"); } if (file == null) { return null; } } return new JimpleClassSource(className, file); } }
1,589
30.8
125
java
soot
soot-master/src/main/java/soot/JimpleClassSource.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.javaToJimple.IInitialResolver.Dependencies; import soot.jimple.JimpleMethodSource; import soot.jimple.parser.lexer.LexerException; import soot.jimple.parser.parser.ParserException; import soot.options.Options; /** * A class source for resolving from .jimple files using the Jimple parser. */ public class JimpleClassSource extends ClassSource { private static final Logger logger = LoggerFactory.getLogger(JimpleClassSource.class); private FoundFile foundFile; public JimpleClassSource(String className, FoundFile foundFile) { super(className); if (foundFile == null) { throw new IllegalStateException("Error: The FoundFile must not be null."); } this.foundFile = foundFile; } @Override public Dependencies resolve(SootClass sc) { if (Options.v().verbose()) { logger.debug("resolving [from .jimple]: " + className); } InputStream classFile = null; try { // Parse jimple file classFile = foundFile.inputStream(); soot.jimple.parser.JimpleAST jimpAST = new soot.jimple.parser.JimpleAST(classFile); jimpAST.getSkeleton(sc); // Set method source for all methods JimpleMethodSource mtdSrc = new JimpleMethodSource(jimpAST); for (Iterator<SootMethod> mtdIt = sc.methodIterator(); mtdIt.hasNext();) { SootMethod sm = mtdIt.next(); sm.setSource(mtdSrc); } // set outer class if not set (which it should not be) and class name contains outer class indicator String outerClassName = null; if (!sc.hasOuterClass()) { String className = sc.getName(); if (className.contains("$")) { if (className.contains("$-")) { /* * This is a special case for generated lambda classes of jack and jill compiler. Generated lambda classes may * contain '$' which do not indicate an inner/outer class separator if the '$' occurs after a inner class with a * name starting with '-'. Thus we search for '$-' and anything after it including '-' is the inner classes name * and anything before it is the outer classes name. */ outerClassName = className.substring(0, className.indexOf("$-")); } else { outerClassName = className.substring(0, className.lastIndexOf('$')); } sc.setOuterClass(SootResolver.v().makeClassRef(outerClassName)); } } // Construct the type dependencies of the class Dependencies deps = new Dependencies(); // The method documentation states it returns RefTypes only, so this is a transformation safe for (String t : jimpAST.getCstPool()) { deps.typesToSignature.add(RefType.v(t)); } if (outerClassName != null) { deps.typesToSignature.add(RefType.v(outerClassName)); } return deps; } catch (IOException e) { throw new RuntimeException("Error: Failed to create JimpleAST from source input stream for class " + className + ".", e); } catch (ParserException e) { throw new RuntimeException("Error: Failed when parsing class " + className + ".", e); } catch (LexerException e) { throw new RuntimeException("Error: Failed when lexing class " + className + ".", e); } finally { try { if (classFile != null) { classFile.close(); classFile = null; } } catch (IOException e) { throw new RuntimeException("Error: Failed to close source input stream.", e); } finally { close(); } } } @Override public void close() { if (foundFile != null) { foundFile.close(); foundFile = null; } } }
4,668
33.843284
124
java
soot
soot-master/src/main/java/soot/Kind.java
package soot; /*- * #%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.util.Numberable; /** * Enumeration type representing the kind of a call graph edge. * * @author Ondrej Lhotak */ public final class Kind implements Numberable { public static final Kind INVALID = new Kind("INVALID"); /** * Due to explicit invokestatic instruction. */ public static final Kind STATIC = new Kind("STATIC"); /** * Due to explicit invokevirtual instruction. */ public static final Kind VIRTUAL = new Kind("VIRTUAL"); /** * Due to explicit invokeinterface instruction. */ public static final Kind INTERFACE = new Kind("INTERFACE"); /** * Due to explicit invokespecial instruction. */ public static final Kind SPECIAL = new Kind("SPECIAL"); /** * Implicit call to static initializer. */ public static final Kind CLINIT = new Kind("CLINIT"); /** * Fake edges from our generic callback model. */ public static final Kind GENERIC_FAKE = new Kind("GENERIC_FAKE"); /** * Implicit call to Thread.run() due to Thread.start() call. */ public static final Kind THREAD = new Kind("THREAD"); /** * Implicit call to java.lang.Runnable.run() due to Executor.execute() call. */ public static final Kind EXECUTOR = new Kind("EXECUTOR"); /** * Implicit call to AsyncTask.doInBackground() due to AsyncTask.execute() call. */ public static final Kind ASYNCTASK = new Kind("ASYNCTASK"); /** * Implicit call to java.lang.ref.Finalizer.register from new bytecode. */ public static final Kind FINALIZE = new Kind("FINALIZE"); /** * Implicit call to Handler.handleMessage(android.os.Message) due to Handler.sendxxxxMessagexxxx() call. */ public static final Kind HANDLER = new Kind("HANDLER"); /** * Implicit call to finalize() from java.lang.ref.Finalizer.invokeFinalizeMethod(). */ public static final Kind INVOKE_FINALIZE = new Kind("INVOKE_FINALIZE"); /** * Implicit call to run() through AccessController.doPrivileged(). */ public static final Kind PRIVILEGED = new Kind("PRIVILEGED"); /** * Implicit call to constructor from java.lang.Class.newInstance(). */ public static final Kind NEWINSTANCE = new Kind("NEWINSTANCE"); /** * Due to call to Method.invoke(..). */ public static final Kind REFL_INVOKE = new Kind("REFL_METHOD_INVOKE"); /** * Due to call to Constructor.newInstance(..). */ public static final Kind REFL_CONSTR_NEWINSTANCE = new Kind("REFL_CONSTRUCTOR_NEWINSTANCE"); /** * Due to call to Class.newInstance(..) when reflection log is enabled. */ public static final Kind REFL_CLASS_NEWINSTANCE = new Kind("REFL_CLASS_NEWINSTANCE"); private final String name; private int num; private Kind(String name) { this.name = name; } public String name() { return name; } @Override public int getNumber() { return num; } @Override public void setNumber(int num) { this.num = num; } @Override public String toString() { return name(); } public boolean passesParameters() { return passesParameters(this); } public boolean isFake() { return isFake(this); } /** * Returns true if the call is due to an explicit invoke statement. */ public boolean isExplicit() { return isExplicit(this); } /** * Returns true if the call is due to an explicit instance invoke statement. */ public boolean isInstance() { return isInstance(this); } /** * Returns true if the call is due to an explicit virtual invoke statement. */ public boolean isVirtual() { return isVirtual(this); } public boolean isSpecial() { return isSpecial(this); } /** * Returns true if the call is to static initializer. */ public boolean isClinit() { return isClinit(this); } /** * Returns true if the call is due to an explicit static invoke statement. */ public boolean isStatic() { return isStatic(this); } public boolean isThread() { return isThread(this); } public boolean isExecutor() { return isExecutor(this); } public boolean isAsyncTask() { return isAsyncTask(this); } public boolean isPrivileged() { return isPrivileged(this); } public boolean isReflection() { return isReflection(this); } public boolean isReflInvoke() { return isReflInvoke(this); } public static boolean passesParameters(Kind k) { return isExplicit(k) || k == THREAD || k == EXECUTOR || k == ASYNCTASK || k == FINALIZE || k == PRIVILEGED || k == NEWINSTANCE || k == INVOKE_FINALIZE || k == REFL_INVOKE || k == REFL_CONSTR_NEWINSTANCE || k == REFL_CLASS_NEWINSTANCE; } public static boolean isFake(Kind k) { return k == THREAD || k == EXECUTOR || k == ASYNCTASK || k == PRIVILEGED || k == HANDLER || k == GENERIC_FAKE; } /** * Returns true if the call is due to an explicit invoke statement. */ public static boolean isExplicit(Kind k) { return isInstance(k) || isStatic(k); } /** * Returns true if the call is due to an explicit instance invoke statement. */ public static boolean isInstance(Kind k) { return k == VIRTUAL || k == INTERFACE || k == SPECIAL; } /** * Returns true if the call is due to an explicit virtual invoke statement. */ public static boolean isVirtual(Kind k) { return k == VIRTUAL; } public static boolean isSpecial(Kind k) { return k == SPECIAL; } /** * Returns true if the call is to static initializer. */ public static boolean isClinit(Kind k) { return k == CLINIT; } /** * Returns true if the call is due to an explicit static invoke statement. */ public static boolean isStatic(Kind k) { return k == STATIC; } public static boolean isThread(Kind k) { return k == THREAD; } public static boolean isExecutor(Kind k) { return k == EXECUTOR; } public static boolean isAsyncTask(Kind k) { return k == ASYNCTASK; } public static boolean isPrivileged(Kind k) { return k == PRIVILEGED; } public static boolean isReflection(Kind k) { return k == REFL_CLASS_NEWINSTANCE || k == REFL_CONSTR_NEWINSTANCE || k == REFL_INVOKE; } public static boolean isReflInvoke(Kind k) { return k == REFL_INVOKE; } }
7,057
24.759124
114
java
soot
soot-master/src/main/java/soot/LabeledUnitPrinter.java
package soot; /*- * #%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.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import soot.util.Chain; /** * UnitPrinter implementation for representations that have labelled stmts, such as Jimple, Grimp, and Baf */ public abstract class LabeledUnitPrinter extends AbstractUnitPrinter { /** * branch targets */ protected Map<Unit, String> labels; /** * for unit references in Phi nodes */ protected Map<Unit, String> references; protected String labelIndent = "\u0020\u0020\u0020\u0020\u0020"; public LabeledUnitPrinter(Body b) { createLabelMaps(b); } public Map<Unit, String> labels() { return labels; } public Map<Unit, String> references() { return references; } @Override public void unitRef(Unit u, boolean branchTarget) { String oldIndent = getIndent(); // normal case, ie labels if (branchTarget) { setIndent(labelIndent); handleIndent(); setIndent(oldIndent); String label = labels.get(u); if (label == null || "<unnamed>".equals(label)) { label = "[?= " + u + "]"; } output.append(label); } else { // refs to control flow predecessors (for Shimple) String ref = references.get(u); if (startOfLine) { String newIndent = "(" + ref + ")" + indent.substring(ref.length() + 2); setIndent(newIndent); handleIndent(); setIndent(oldIndent); } else { output.append(ref); } } } private void createLabelMaps(Body body) { Chain<Unit> units = body.getUnits(); labels = new HashMap<Unit, String>(units.size() * 2 + 1, 0.7f); references = new HashMap<Unit, String>(units.size() * 2 + 1, 0.7f); // Create statement name table Set<Unit> labelStmts = new HashSet<Unit>(); Set<Unit> refStmts = new HashSet<Unit>(); // Build labelStmts and refStmts for (UnitBox box : body.getAllUnitBoxes()) { Unit stmt = box.getUnit(); if (box.isBranchTarget()) { labelStmts.add(stmt); } else { refStmts.add(stmt); } } // left side zero padding for all labels // this simplifies debugging the jimple code in simple editors, as it // avoids the situation where a label is the prefix of another label final int maxDigits = 1 + (int) Math.log10(labelStmts.size()); final String formatString = "label%0" + maxDigits + "d"; int labelCount = 0; int refCount = 0; // Traverse the stmts and assign a label if necessary for (Unit s : units) { if (labelStmts.contains(s)) { labels.put(s, String.format(formatString, ++labelCount)); } if (refStmts.contains(s)) { references.put(s, Integer.toString(refCount++)); } } } }
3,591
26.844961
106
java
soot
soot-master/src/main/java/soot/LambdaMetaFactory.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2017 Brian Alliet Initial implementation * Copyright (C) 2018 Manuel Benz Bug fixes and improvements * %% * 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.base.Optional; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.asm.AsmUtil; import soot.jimple.ClassConstant; import soot.jimple.IntConstant; import soot.jimple.InvokeExpr; import soot.jimple.Jimple; import soot.jimple.JimpleBody; import soot.jimple.MethodHandle; import soot.jimple.MethodType; import soot.jimple.toolkits.scalar.LocalNameStandardizer; import soot.tagkit.ArtificialEntityTag; import soot.util.Chain; import soot.util.HashChain; public class LambdaMetaFactory { private static final Logger LOGGER = LoggerFactory.getLogger(LambdaMetaFactory.class); private final Wrapper wrapper; private int uniq; public LambdaMetaFactory(Singletons.Global g) { uniq = 0; wrapper = new Wrapper(); } public static LambdaMetaFactory v() { return G.v().soot_LambdaMetaFactory(); } /** * @param bootstrapArgs * @param tag * @param name * @param invokedType * types of captured arguments, the last element is always the type of the FunctionalInterface * @param enclosingClass * @return */ public SootMethodRef makeLambdaHelper(List<? extends Value> bootstrapArgs, int tag, String name, Type[] invokedType, SootClass enclosingClass) { final int argsSize = bootstrapArgs.size(); if (argsSize < 3 || !(bootstrapArgs.get(0) instanceof MethodType) || !(bootstrapArgs.get(1) instanceof MethodHandle) || !(bootstrapArgs.get(2) instanceof MethodType) || (argsSize > 3 && !(bootstrapArgs.get(3) instanceof IntConstant))) { LOGGER.warn("LambdaMetaFactory: unexpected arguments for LambdaMetaFactory.metaFactory: {}", bootstrapArgs); return null; } /** implemented method type */ MethodType samMethodType = ((MethodType) bootstrapArgs.get(0)); /** the MethodHandle providing the implementation */ MethodHandle implMethod = ((MethodHandle) bootstrapArgs.get(1)); // we might not have seen types used in the handle elsewhere yet, so let's try to resolve them // now resolveHandle(implMethod); /** allows restrictions on invocation */ MethodType instantiatedMethodType = ((MethodType) bootstrapArgs.get(2)); int flags = 0; if (argsSize > 3) { flags = ((IntConstant) bootstrapArgs.get(3)).value; } boolean serializable = (flags & 1 /* FLAGS_SERIALIZABLE */) != 0; List<ClassConstant> markerInterfaces = new ArrayList<ClassConstant>(); List<MethodType> bridges = new ArrayList<MethodType>(); int va = 4; if ((flags & 2 /* FLAG_MARKERS */) != 0) { if (va == argsSize || !(bootstrapArgs.get(va) instanceof IntConstant)) { LOGGER.warn("LambdaMetaFactory: unexpected arguments for LambdaMetaFactory.altMetaFactory"); return null; } int count = ((IntConstant) bootstrapArgs.get(va++)).value; for (int i = 0; i < count; i++) { if (va >= argsSize) { LOGGER.warn("LambdaMetaFactory: unexpected arguments for LambdaMetaFactory.altMetaFactory"); return null; } Value v = bootstrapArgs.get(va++); if (!(v instanceof ClassConstant)) { LOGGER.warn("LambdaMetaFactory: unexpected arguments for LambdaMetaFactory.altMetaFactory"); return null; } markerInterfaces.add((ClassConstant) v); } } if ((flags & 4 /* FLAG_BRIDGES */) != 0) { if (va == argsSize || !(bootstrapArgs.get(va) instanceof IntConstant)) { LOGGER.warn("LambdaMetaFactory: unexpected arguments for LambdaMetaFactory.altMetaFactory"); return null; } int count = ((IntConstant) bootstrapArgs.get(va++)).value; for (int i = 0; i < count; i++) { if (va >= argsSize) { LOGGER.warn("LambdaMetaFactory: unexpected arguments for LambdaMetaFactory.altMetaFactory"); return null; } Value v = bootstrapArgs.get(va++); if (!(v instanceof MethodType)) { LOGGER.warn("LambdaMetaFactory: unexpected arguments for LambdaMetaFactory.altMetaFactory"); return null; } bridges.add((MethodType) v); } } List<Type> capTypes = Arrays.asList(invokedType).subList(0, invokedType.length - 1); if (!(invokedType[invokedType.length - 1] instanceof RefType)) { LOGGER.warn("unexpected interface type: " + invokedType[invokedType.length - 1]); return null; } // Our thunk class implements the functional interface SootClass functionalInterfaceToImplement = ((RefType) invokedType[invokedType.length - 1]).getSootClass(); final String enclosingClassname = enclosingClass.getName(); String className; final boolean readableClassnames = true; if (readableClassnames) { // class names cannot contain <> String implMethodName = implMethod.getMethodRef().getName(); String dummyName = "<init>".equals(implMethodName) ? "init" : implMethodName; // XXX: $ causes confusion in inner class inference; remove for now dummyName = dummyName.replace('$', '_'); String prefix = (enclosingClassname == null || enclosingClassname.isEmpty()) ? "soot.dummy." : enclosingClassname + "$"; className = prefix + dummyName + "__" + uniqSupply(); } else { className = "soot.dummy.lambda" + uniqSupply(); } SootClass tclass = Scene.v().makeSootClass(className); tclass.setModifiers(Modifier.PUBLIC | Modifier.FINAL); tclass.setSuperclass(Scene.v().getObjectType().getSootClass()); tclass.addInterface(functionalInterfaceToImplement); tclass.addTag(new ArtificialEntityTag()); // additions from altMetafactory if (serializable) { tclass.addInterface(RefType.v("java.io.Serializable").getSootClass()); } for (int i = 0; i < markerInterfaces.size(); i++) { tclass.addInterface( ((RefType) AsmUtil.toBaseType(markerInterfaces.get(i).getValue(), Optional.fromNullable(tclass.moduleName))) .getSootClass()); } // It contains fields for all the captures in the lambda List<SootField> capFields = new ArrayList<SootField>(capTypes.size()); for (int i = 0, e = capTypes.size(); i < e; i++) { SootField f = Scene.v().makeSootField("cap" + i, capTypes.get(i), 0); capFields.add(f); tclass.addField(f); } // if the implMethod is a new private static in the enclosing class, make it public access so // it can be invoked from the thunk class if (MethodHandle.Kind.REF_INVOKE_STATIC.getValue() == implMethod.getKind()) { SootClass declClass = implMethod.getMethodRef().getDeclaringClass(); if (declClass.getName().equals(enclosingClassname)) { SootMethod method = implMethod.getMethodRef().resolve(); method.setModifiers((method.getModifiers() & ~Modifier.PRIVATE) | Modifier.PUBLIC); } } MethodSource ms = new ThunkMethodSource(capFields, samMethodType, implMethod, instantiatedMethodType); // Bootstrap method creates a new instance of this class SootMethod tboot = Scene.v().makeSootMethod("bootstrap$", capTypes, functionalInterfaceToImplement.getType(), Modifier.PUBLIC | Modifier.STATIC); tclass.addMethod(tboot); tboot.setSource(ms); // Constructor just copies the captures SootMethod tctor = Scene.v().makeSootMethod("<init>", capTypes, VoidType.v(), Modifier.PUBLIC); tclass.addMethod(tctor); tctor.setSource(ms); // Dispatch runs the 'real' method implementing the body of the lambda addDispatch(name, tclass, samMethodType, instantiatedMethodType, capFields, implMethod); // For each bridge MethodType, add another dispatch method which calls the 'real' method for (MethodType bridgeType : bridges) { addDispatch(name, tclass, bridgeType, instantiatedMethodType, capFields, implMethod); } for (SootMethod m : tclass.getMethods()) { // There is no reason not to load the bodies directly. After all, // we are introducing new classes while loading bodies. m.retrieveActiveBody(); } addClassAndInvalidateHierarchy(tclass); if (enclosingClass.isApplicationClass()) { tclass.setApplicationClass(); } return tboot.makeRef(); } /** * Invalidates the class hierarchy due to some newly added class. * * @param tclass */ protected void addClassAndInvalidateHierarchy(SootClass tclass) { Scene.v().addClass(tclass); // The hierarchy has to be rebuilt after adding the MetaFactory implementation. // soot.FastHierarchy.canStoreClass will otherwise fail due to not having an interval set for // the class. This eventually // leads to the MetaFactory not being accepted as implementation of the functional interface it // actually implements. // This, in turn, leads to missing edges in the call graph. Scene.v().releaseFastHierarchy(); } /** * Makes sure all types used in the implMethod signature are properly resolved. The method has to be synchronized since * body creation happens in parallel and the SootResolver is not thread-safe * * @param implMethod */ private synchronized void resolveHandle(MethodHandle implMethod) { Scene scene = Scene.v(); SootMethodRef methodRef = implMethod.getMethodRef(); scene.forceResolve(methodRef.getDeclaringClass().getName(), SootClass.HIERARCHY); Stream.concat(Stream.of(methodRef.getReturnType()), methodRef.getParameterTypes().stream()) .filter(t -> t instanceof RefType) .forEach(t -> scene.forceResolve(((RefType) t).getSootClass().getName(), SootClass.HIERARCHY)); } private void addDispatch(String name, SootClass tclass, MethodType implMethodType, MethodType instantiatedMethodType, List<SootField> capFields, MethodHandle implMethod) { ThunkMethodSource ms = new ThunkMethodSource(capFields, implMethodType, implMethod, instantiatedMethodType); SootMethod m = Scene.v().makeSootMethod(name, implMethodType.getParameterTypes(), implMethodType.getReturnType(), Modifier.PUBLIC); tclass.addMethod(m); m.setSource(ms); } private synchronized long uniqSupply() { return ++uniq; } private static class Wrapper { final Map<RefType, PrimType> wrapperTypes; final Map<PrimType, RefType> primitiveTypes; /** valueOf(primitive) method signature */ final Map<PrimType, SootMethod> valueOf; /** primitiveValue() method signature */ final Map<RefType, SootMethod> primitiveValue; public Wrapper() { final Scene sc = Scene.v(); Map<RefType, PrimType> wrapperTypesTmp = new HashMap<>(); Map<PrimType, RefType> primitiveTypesTmp = new HashMap<>(); Map<PrimType, SootMethod> valueOfTmp = new HashMap<>(); Map<RefType, SootMethod> primitiveValueTmp = new HashMap<>(); PrimType[] primTypes = { BooleanType.v(), ByteType.v(), CharType.v(), DoubleType.v(), FloatType.v(), IntType.v(), LongType.v(), ShortType.v() }; for (PrimType primTy : primTypes) { RefType wrapTy = primTy.boxedType(); wrapperTypesTmp.put(wrapTy, primTy); primitiveTypesTmp.put(primTy, wrapTy); SootClass wrapCls = wrapTy.getSootClass(); valueOfTmp.put(primTy, sc.makeMethodRef(wrapCls, "valueOf", Collections.singletonList(primTy), wrapTy, true).resolve()); primitiveValueTmp.put(wrapTy, sc.makeMethodRef(wrapCls, primTy.toString() + "Value", Collections.emptyList(), primTy, false).resolve()); } this.wrapperTypes = Collections.unmodifiableMap(wrapperTypesTmp); this.primitiveTypes = Collections.unmodifiableMap(primitiveTypesTmp); this.valueOf = Collections.unmodifiableMap(valueOfTmp); this.primitiveValue = Collections.unmodifiableMap(primitiveValueTmp); } } private class ThunkMethodSource implements MethodSource { /** * fields storing capture variables, in the order they appear in invokedType; to be prepended at target invocation site */ private final List<SootField> capFields; /** * MethodType of method to implemented by function object; either samMethodType or bridgeMethodType * */ private final MethodType implMethodType; /** implMethod - the MethodHandle providing the implementation */ private final MethodHandle implMethod; /** allows restrictions on invocation */ private final MethodType instantiatedMethodType; public ThunkMethodSource(List<SootField> capFields, MethodType implMethodType, MethodHandle implMethod, MethodType instantiatedMethodType) { this.capFields = capFields; this.implMethodType = implMethodType; this.implMethod = implMethod; this.instantiatedMethodType = instantiatedMethodType; } @Override public Body getBody(SootMethod m, String phaseName) { if (!"jb".equals(phaseName)) { throw new Error("unsupported body type: " + phaseName); } SootClass tclass = m.getDeclaringClass(); JimpleBody jb = Jimple.v().newBody(m); if (null != m.getName()) { switch (m.getName()) { case "<init>": getInitBody(tclass, jb); break; case "bootstrap$": getBootstrapBody(tclass, jb); break; default: getInvokeBody(tclass, jb); break; } } // rename locals consistent with JimpleBodyPack, at least when it is activated LocalNameStandardizer.v().transform(jb, "jb.lns", PhaseOptions.v().getPhaseOptions("jb.lns")); return jb; } /** * Thunk class init (constructor) * * @param tclass * thunk class * @param jb */ private void getInitBody(SootClass tclass, JimpleBody jb) { final Jimple jimp = Jimple.v(); PatchingChain<Unit> us = jb.getUnits(); LocalGenerator lc = Scene.v().createLocalGenerator(jb); // @this Local l = lc.generateLocal(tclass.getType()); us.add(jimp.newIdentityStmt(l, jimp.newThisRef(tclass.getType()))); // @parameters Chain<Local> capLocals = new HashChain<>(); int i = 0; for (SootField f : capFields) { Local l2 = lc.generateLocal(f.getType()); us.add(jimp.newIdentityStmt(l2, jimp.newParameterRef(f.getType(), i))); capLocals.add(l2); i++; } // super java.lang.Object.<init> us.add(jimp.newInvokeStmt(jimp.newSpecialInvokeExpr(l, Scene.v().makeConstructorRef(Scene.v().getObjectType().getSootClass(), Collections.emptyList()), Collections.emptyList()))); // assign parameters to fields Iterator<Local> localItr = capLocals.iterator(); for (SootField f : capFields) { Local l2 = localItr.next(); us.add(jimp.newAssignStmt(jimp.newInstanceFieldRef(l, f.makeRef()), l2)); } us.add(jimp.newReturnVoidStmt()); } private void getBootstrapBody(SootClass tclass, JimpleBody jb) { final Jimple jimp = Jimple.v(); PatchingChain<Unit> us = jb.getUnits(); LocalGenerator lc = Scene.v().createLocalGenerator(jb); List<Value> capValues = new ArrayList<Value>(); List<Type> capTypes = new ArrayList<Type>(); int i = 0; for (SootField capField : capFields) { Type type = capField.getType(); capTypes.add(type); Local p = lc.generateLocal(type); us.add(jimp.newIdentityStmt(p, jimp.newParameterRef(type, i))); capValues.add(p); i++; } Local l = lc.generateLocal(tclass.getType()); us.add(jimp.newAssignStmt(l, jimp.newNewExpr(tclass.getType()))); us.add(jimp.newInvokeStmt(jimp.newSpecialInvokeExpr(l, Scene.v().makeConstructorRef(tclass, capTypes), capValues))); us.add(jimp.newReturnStmt(l)); } /** * Adds method which implements functional interface and invokes target implementation. * * @param tclass * @param jb */ private void getInvokeBody(SootClass tclass, JimpleBody jb) { final Jimple jimp = Jimple.v(); PatchingChain<Unit> us = jb.getUnits(); LocalGenerator lc = Scene.v().createLocalGenerator(jb); // @this Local this_ = lc.generateLocal(tclass.getType()); us.add(jimp.newIdentityStmt(this_, jimp.newThisRef(tclass.getType()))); // @parameter for direct arguments Chain<Local> samParamLocals = new HashChain<>(); int i = 0; for (Type ty : implMethodType.getParameterTypes()) { Local l = lc.generateLocal(ty); us.add(jimp.newIdentityStmt(l, jimp.newParameterRef(ty, i))); samParamLocals.add(l); i++; } // narrowing casts to match instantiatedMethodType Iterator<Type> iptItr = instantiatedMethodType.getParameterTypes().iterator(); Chain<Local> instParamLocals = new HashChain<>(); for (Local l : samParamLocals) { Type ipt = iptItr.next(); instParamLocals.add(narrowingReferenceConversion(l, ipt, jb, us, lc)); } // captured arguments List<Local> args = new ArrayList<Local>(); for (SootField f : capFields) { Local l = lc.generateLocal(f.getType()); us.add(jimp.newAssignStmt(l, jimp.newInstanceFieldRef(this_, f.makeRef()))); args.add(l); } // direct arguments // The MethodHandle's first argument is the receiver, if it has one. // If there are no captured arguments, use the first parameter as the receiver. final int kind = implMethod.getKind(); boolean needsReceiver = false; if (MethodHandle.Kind.REF_INVOKE_INTERFACE.getValue() == kind || MethodHandle.Kind.REF_INVOKE_VIRTUAL.getValue() == kind || MethodHandle.Kind.REF_INVOKE_SPECIAL.getValue() == kind) { // NOTE: for a method reference to a constructor, the receiver is not needed because it's // the new object needsReceiver = true; } Iterator<Local> iplItr = instParamLocals.iterator(); if (capFields.isEmpty() && iplItr.hasNext() && needsReceiver) { args.add(adapt(iplItr.next(), implMethod.getMethodRef().getDeclaringClass().getType(), jb, us, lc)); } int j = args.size(); if (needsReceiver) { // assert: if there is a receiver, it is already filled, but the alignment to parameters is // off by 1 j = args.size() - 1; } while (iplItr.hasNext()) { Local pl = iplItr.next(); args.add(adapt(pl, implMethod.getMethodRef().getParameterType(j), jb, us, lc)); j++; } invokeImplMethod(jb, us, lc, args); } private Local adapt(Local fromLocal, Type to, JimpleBody jb, PatchingChain<Unit> us, LocalGenerator lc) { Type from = fromLocal.getType(); // Implements JLS 5.3 Method Invocation Context for adapting arguments from lambda expression // to formal arguments of target implementation // an identity conversion (§5.1.1) if (from.equals(to)) { return fromLocal; } if (from instanceof ArrayType) { return wideningReferenceConversion(fromLocal); } if (from instanceof RefType && to instanceof RefType) { return wideningReferenceConversion(fromLocal); } if (from instanceof PrimType) { if (to instanceof PrimType) { // a widening primitive conversion (§5.1.2) return wideningPrimitiveConversion(fromLocal, to, jb, us, lc); } else { // a boxing conversion (§5.1.7) // a boxing conversion followed by widening reference conversion // from is PrimType // to is RefType return wideningReferenceConversion(box(fromLocal, jb, us, lc)); } } else { // an unboxing conversion (§5.1.8) // an unboxing conversion followed by a widening primitive conversion // from is RefType // to is PrimType if (!(to instanceof PrimType)) { throw new IllegalArgumentException("Expected 'to' to be a PrimType"); } // In some cases, the wrapper type is "java.lang.Object" and we first need to cast it to a // type that can be unboxed. Java, e.g., seems to accept filter predicates on boxed Boolean // types specified through generics. // Code Example: // Map<String, Boolean> map = new HashMap<>(); // map.entrySet().stream().filter(Map.Entry::getValue) // In the example, the map values are of type Object because of generic erasure, but we're // still dealing with // booleans semantically. // Actually, the wrapper type could be also be other types if wirdcards (?) are used in generic code. if (wrapper.wrapperTypes.get(from) == null) { // Insert the cast RefType boxedType = wrapper.primitiveTypes.get((PrimType) to); Local castLocal = lc.generateLocal(boxedType); us.add(Jimple.v().newAssignStmt(castLocal, Jimple.v().newCastExpr(fromLocal, boxedType))); fromLocal = castLocal; } return wideningPrimitiveConversion(unbox(fromLocal, jb, us, lc), to, jb, us, lc); } } /** * P box = P.valueOf(fromLocal); * * @param fromLocal * primitive * @param jb * @param us * @return */ private Local box(Local fromLocal, JimpleBody jb, PatchingChain<Unit> us, LocalGenerator lc) { PrimType primitiveType = (PrimType) fromLocal.getType(); SootMethod valueOfMethod = wrapper.valueOf.get(primitiveType); Local lBox = lc.generateLocal(primitiveType.boxedType()); if (lBox == null || valueOfMethod == null || us == null) { throw new NullPointerException(String.format("%s,%s,%s,%s", valueOfMethod, primitiveType, wrapper.valueOf.entrySet(), wrapper.valueOf.get(primitiveType))); } us.add(Jimple.v().newAssignStmt(lBox, Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), fromLocal))); return lBox; } /** * p unbox = fromLocal.pValue(); * * @param fromLocal * boxed * @param jb * @param us * @return */ private Local unbox(Local fromLocal, JimpleBody jb, PatchingChain<Unit> us, LocalGenerator lc) { RefType wrapperType = (RefType) fromLocal.getType(); Local lUnbox = lc.generateLocal(wrapper.wrapperTypes.get(wrapperType)); us.add(Jimple.v().newAssignStmt(lUnbox, Jimple.v().newVirtualInvokeExpr(fromLocal, wrapper.primitiveValue.get(wrapperType).makeRef()))); return lUnbox; } private Local wideningReferenceConversion(Local fromLocal) { // a widening reference conversion (JLS §5.1.5) // TODO: confirm that 'from' is a subtype of 'to' return fromLocal; } /** * T t = (T) fromLocal; * * @param fromLocal * @param to * @param jb * @param us * @return */ private Local narrowingReferenceConversion(Local fromLocal, Type to, JimpleBody jb, PatchingChain<Unit> us, LocalGenerator lc) { Type fromTy = fromLocal.getType(); if (fromTy.equals(to)) { return fromLocal; } if (!(fromTy instanceof RefType || fromTy instanceof ArrayType)) { return fromLocal; } // throw new IllegalArgumentException("Expected source to have reference type"); if (!(to instanceof RefType || to instanceof ArrayType)) { return fromLocal; // throw new IllegalArgumentException("Expected target to have reference type"); } Local l2 = lc.generateLocal(to); us.add(Jimple.v().newAssignStmt(l2, Jimple.v().newCastExpr(fromLocal, to))); return l2; } /** * T t = (T) fromLocal; * * @param fromLocal * @param to * @param jb * @param us * @return */ private Local wideningPrimitiveConversion(Local fromLocal, Type to, JimpleBody jb, PatchingChain<Unit> us, LocalGenerator lc) { if (!(fromLocal.getType() instanceof PrimType)) { throw new IllegalArgumentException("Expected source to have primitive type"); } if (!(to instanceof PrimType)) { throw new IllegalArgumentException("Expected target to have primitive type"); } Local l2 = lc.generateLocal(to); us.add(Jimple.v().newAssignStmt(l2, Jimple.v().newCastExpr(fromLocal, to))); return l2; } /** * Invocation of target implementation method. * * @param jb * @param us * @param args */ private void invokeImplMethod(JimpleBody jb, PatchingChain<Unit> us, LocalGenerator lc, List<Local> args) { Value value = _invokeImplMethod(jb, us, lc, args); if (VoidType.v().equals(implMethodType.getReturnType())) { // dispatch method is void if (value instanceof InvokeExpr) { us.add(Jimple.v().newInvokeStmt(value)); } us.add(Jimple.v().newReturnVoidStmt()); } else { // Handle special case of a constructor method-ref. The dispatch method is void <init>(), // but the created object should still be returned. // See (src/systemTest/targets/soot/lambdaMetaFactory/Issue1367.java) if (VoidType.v().equals(implMethod.getMethodRef().getReturnType())) { us.add(Jimple.v().newReturnStmt(value)); } else { // neither is void, must pass through return value Local ret = lc.generateLocal(value.getType()); us.add(Jimple.v().newAssignStmt(ret, value)); // adapt return value us.add(Jimple.v().newReturnStmt(adapt(ret, implMethodType.getReturnType(), jb, us, lc))); } } } private Value _invokeImplMethod(JimpleBody jb, PatchingChain<Unit> us, LocalGenerator lc, List<Local> args) { // A lambda capturing 'this' may be implemented by a private instance method. // A method reference to an instance method may be implemented by the instance method itself. // To use the correct invocation style, resolve the method and determine how the compiler // implemented the lambda or method reference. SootMethodRef methodRef = implMethod.getMethodRef(); switch (MethodHandle.Kind.getKind(implMethod.getKind())) { case REF_INVOKE_STATIC: return Jimple.v().newStaticInvokeExpr(methodRef, args); case REF_INVOKE_INTERFACE: return Jimple.v().newInterfaceInvokeExpr(args.get(0), methodRef, rest(args)); case REF_INVOKE_VIRTUAL: return Jimple.v().newVirtualInvokeExpr(args.get(0), methodRef, rest(args)); case REF_INVOKE_SPECIAL: final SootClass currentClass = jb.getMethod().getDeclaringClass(); final SootClass calledClass = methodRef.getDeclaringClass(); // It can be the case that the method is not in the same class (or a super class). // As such, we need a virtual call in these cases. if (currentClass == calledClass || Scene.v().getOrMakeFastHierarchy().canStoreClass(currentClass.getSuperclass(), calledClass)) { return Jimple.v().newSpecialInvokeExpr(args.get(0), methodRef, rest(args)); } else { SootMethod m = implMethod.getMethodRef().resolve(); if (!m.isPublic()) { // make sure the method is public int mod = Modifier.PUBLIC | m.getModifiers(); mod &= ~Modifier.PRIVATE; mod &= ~Modifier.PROTECTED; m.setModifiers(mod); } // In some versions of the (Open)JDK, we seem to have an interface instead of a class // for some reason if (methodRef.getDeclaringClass().isInterface()) { return Jimple.v().newInterfaceInvokeExpr(args.get(0), methodRef, rest(args)); } else { return Jimple.v().newVirtualInvokeExpr(args.get(0), methodRef, rest(args)); } } case REF_INVOKE_CONSTRUCTOR: final Jimple jimp = Jimple.v(); RefType type = methodRef.getDeclaringClass().getType(); Local newLocal = lc.generateLocal(type); us.add(jimp.newAssignStmt(newLocal, jimp.newNewExpr(type))); // NOTE: args does not include the receiver us.add(jimp.newInvokeStmt(jimp.newSpecialInvokeExpr(newLocal, methodRef, args))); return newLocal; case REF_GET_FIELD: case REF_GET_FIELD_STATIC: case REF_PUT_FIELD: case REF_PUT_FIELD_STATIC: default: } throw new IllegalArgumentException("Unexpected MethodHandle.Kind " + implMethod.getKind()); } private List<Local> rest(List<Local> args) { int first = 1; int last = args.size(); if (last < first) { return Collections.emptyList(); } else { return args.subList(first, last); } } } }
30,039
37.562259
125
java
soot
soot-master/src/main/java/soot/Local.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Numberable; /** * A local variable, used within Body classes. Intermediate representations must use an implementation of Local for their * local variables. */ public interface Local extends Value, Numberable, Immediate { /** Returns the name of the current Local variable. */ public String getName(); /** Sets the name of the current variable. */ public void setName(String name); /** Sets the type of the current variable. */ public void setType(Type t); public boolean isStackLocal(); }
1,349
30.395349
121
java
soot
soot-master/src/main/java/soot/LocalGenerator.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public abstract class LocalGenerator { /** generates a new soot local given the type */ public abstract Local generateLocal(Type type); }
955
31.965517
71
java
soot
soot-master/src/main/java/soot/LongType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java built-in type 'long'. Implemented as a singleton. */ @SuppressWarnings("serial") public class LongType extends PrimType { public static final int HASHCODE = 0x023DA077; public LongType(Singletons.Global g) { } public static LongType v() { return G.v().soot_LongType(); } @Override public boolean equals(Object t) { return this == t; } @Override public int hashCode() { return HASHCODE; } @Override public String toString() { return "long"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseLongType(this); } @Override public RefType boxedType() { return RefType.v("java.lang.Long"); } @Override public Class<?> getJavaBoxedType() { return Long.class; } @Override public Class<?> getJavaPrimitiveType() { return long.class; } }
1,725
21.128205
84
java
soot
soot-master/src/main/java/soot/Main.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2012 Raja Vallee-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 static java.net.URLEncoder.encode; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Date; import soot.options.CGOptions; import soot.options.Options; import soot.toolkits.astmetrics.ClassData; /** * Main class for Soot; provides Soot's command-line user interface. */ public class Main { public Main(Singletons.Global g) { } public static Main v() { return G.v().soot_Main(); } // TODO: the following string should be updated by the source control // No it shouldn't. Prcs is horribly broken in this respect, and causes // the code to not compile all the time. public static final String versionString = Main.class.getPackage().getImplementationVersion() == null ? "trunk" : Main.class.getPackage().getImplementationVersion(); private Date start; private long startNano; private long finishNano; private void printVersion() { System.out.println("Soot version " + versionString); System.out.println("Copyright (C) 1997-2010 Raja Vallee-Rai and others."); System.out.println("All rights reserved."); System.out.println(); System.out.println("Contributions are copyright (C) 1997-2010 by their respective contributors."); System.out.println("See the file 'credits' for a list of contributors."); System.out.println("See individual source files for details."); System.out.println(); System.out.println("Soot comes with ABSOLUTELY NO WARRANTY. Soot is free software,"); System.out.println("and you are welcome to redistribute it under certain conditions."); System.out.println("See the accompanying file 'COPYING-LESSER.txt' for details."); System.out.println("Visit the Soot website:"); System.out.println(" http://www.sable.mcgill.ca/soot/"); System.out.println("For a list of command line options, enter:"); System.out.println(" java soot.Main --help"); } private void processCmdLine(String[] args) { final Options opts = Options.v(); if (!opts.parse(args)) { throw new OptionsParseException("Option parse error"); } if (PackManager.v().onlyStandardPacks()) { for (Pack pack : PackManager.v().allPacks()) { opts.warnForeignPhase(pack.getPhaseName()); for (Transform tr : pack) { opts.warnForeignPhase(tr.getPhaseName()); } } } opts.warnNonexistentPhase(); if (opts.help()) { System.out.println(opts.getUsage()); throw new CompilationDeathException(CompilationDeathException.COMPILATION_SUCCEEDED); } if (opts.phase_list()) { System.out.println(opts.getPhaseList()); throw new CompilationDeathException(CompilationDeathException.COMPILATION_SUCCEEDED); } if (!opts.phase_help().isEmpty()) { for (String phase : opts.phase_help()) { System.out.println(opts.getPhaseHelp(phase)); } throw new CompilationDeathException(CompilationDeathException.COMPILATION_SUCCEEDED); } if ((!opts.unfriendly_mode() && (args.length == 0)) || opts.version()) { printVersion(); throw new CompilationDeathException(CompilationDeathException.COMPILATION_SUCCEEDED); } if (opts.on_the_fly()) { opts.set_whole_program(true); PhaseOptions.v().setPhaseOption("cg", "off"); } postCmdLineCheck(); } private void postCmdLineCheck() { if (Options.v().classes().isEmpty() && Options.v().process_dir().isEmpty()) { throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED, "No input classes specified!"); } } public String[] cmdLineArgs = new String[0]; /** * Entry point for cmd line invocation of soot. */ public static void main(String[] args) { try { Main.v().run(args); } catch (OptionsParseException e) { // error message has already been printed } catch (StackOverflowError e) { System.err.println("Soot has run out of stack memory."); System.err.println("To allocate more stack memory to Soot, use the -Xss switch to Java."); System.err.println("For example (for 2MB): java -Xss2m soot.Main ..."); throw e; } catch (OutOfMemoryError e) { System.err.println("Soot has run out of the memory allocated to it by the Java VM."); System.err.println("To allocate more memory to Soot, use the -Xmx switch to Java."); System.err.println("For example (for 2GB): java -Xmx2g soot.Main ..."); throw e; } catch (RuntimeException e) { e.printStackTrace(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(bos)); String stackStraceString = bos.toString(); final String TRACKER_URL = "https://github.com/soot-oss/soot/issues/new?"; String body = "Steps to reproduce:\n1.) ...\n\n" + "Files used to reproduce: \n...\n\n" + "Soot version: " + "<pre>" + escape(versionString) + "</pre>\n\n" + "Command line:\n" + "<pre>" + escape(String.join(" ", args)) + "</pre>\n\n" + "Max Memory:\n" + "<pre>" + escape((Runtime.getRuntime().maxMemory() / (1024 * 1024)) + "MB") + "</pre>\n\n" + "Stack trace:\n" + "<pre>" + escape(stackStraceString) + "</pre>"; String title = e.getClass().getName() + " when ..."; try { StringBuilder sb = new StringBuilder(); sb.append("\n\nOuuups... something went wrong! Sorry about that.\n"); sb.append("Follow these steps to fix the problem:\n"); sb.append("1.) Are you sure you used the right command line?\n"); sb.append(" Click here to double-check:\n"); sb.append(" https://github.com/soot-oss/soot/wiki/Options-and-JavaDoc\n"); sb.append('\n'); sb.append("2.) Not sure whether it's a bug? Feel free to discuss\n"); sb.append(" the issue on the Soot mailing list:\n"); sb.append(" https://github.com/soot-oss/soot/wiki/Getting-help\n"); sb.append('\n'); sb.append("3.) Sure it's a bug? Click this link to report it.\n"); sb.append(" " + TRACKER_URL + "title=").append(encode(title, "UTF-8")); sb.append("&body=").append(encode(body, "UTF-8")).append('\n'); sb.append(" Please be as precise as possible when giving us\n"); sb.append(" information on how to reproduce the problem. Thanks!"); System.err.println(sb); // Exit with an exit code 1 System.exit(1); } catch (UnsupportedEncodingException e1) { // Exit with an exit code 1 System.exit(1); } } } private static CharSequence escape(CharSequence s) { final int end = s.length(); int start = 0; StringBuilder sb = new StringBuilder(32 + (end - start)); for (int i = start; i < end; i++) { int c = s.charAt(i); switch (c) { case '<': case '>': case '"': case '\'': case '&': sb.append(s, start, i); sb.append("&#"); sb.append(c); sb.append(';'); start = i + 1; break; } } return sb.append(s, start, end); } /** * Entry point to the soot's compilation process. */ public void run(String[] args) { cmdLineArgs = args; start = new Date(); startNano = System.nanoTime(); try { Timers.v().totalTimer.start(); processCmdLine(cmdLineArgs); autoSetOptions(); System.out.println("Soot started on " + start); Scene.v().loadNecessaryClasses(); /* * By this all the java to jimple has occured so we just check ast-metrics flag * * If it is set......print the astMetrics.xml file and stop executing soot */ if (Options.v().ast_metrics()) { try (OutputStream streamOut = new FileOutputStream("../astMetrics.xml")) { PrintWriter writerOut = new PrintWriter(new OutputStreamWriter(streamOut)); writerOut.println("<?xml version='1.0'?>"); writerOut.println("<ASTMetrics>"); for (ClassData cData : G.v().ASTMetricsData) { // each is a classData object writerOut.println(cData); } writerOut.println("</ASTMetrics>"); writerOut.flush(); } catch (IOException e) { throw new CompilationDeathException("Cannot output file astMetrics", e); } return; } PackManager.v().runPacks(); if (!Options.v().oaat()) { PackManager.v().writeOutput(); } Timers.v().totalTimer.end(); // Print out time stats. if (Options.v().time()) { Timers.v().printProfilingInformation(); } } catch (CompilationDeathException e) { Timers.v().totalTimer.end(); if (e.getStatus() != CompilationDeathException.COMPILATION_SUCCEEDED) { throw e; } else { return; } } finishNano = System.nanoTime(); System.out.println("Soot finished on " + new Date()); long runtime = (finishNano - startNano) / 1000000l; System.out.println("Soot has run for " + (runtime / 60000) + " min. " + ((runtime % 60000) / 1000) + " sec."); } public void autoSetOptions() { final Options opts = Options.v(); // when no-bodies-for-excluded is enabled, also enable phantom refs if (opts.no_bodies_for_excluded()) { opts.set_allow_phantom_refs(true); } // when reflection log is enabled, also enable phantom refs CGOptions cgOptions = new CGOptions(PhaseOptions.v().getPhaseOptions("cg")); String log = cgOptions.reflection_log(); if (log != null && !log.isEmpty()) { opts.set_allow_phantom_refs(true); } // if phantom refs enabled, ignore wrong staticness in type assigner if (opts.allow_phantom_refs()) { opts.set_wrong_staticness(Options.wrong_staticness_fix); } if (opts.java_version() != Options.java_version_default) { opts.set_derive_java_version(false); } } }
11,199
32.633634
120
java
soot
soot-master/src/main/java/soot/MethodContext.java
package soot; /*- * #%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; /** * Represents a pair of a method and a context. * * @author Ondrej Lhotak */ public final class MethodContext implements MethodOrMethodContext { private SootMethod method; public SootMethod method() { return method; } private Context context; public Context context() { return context; } private MethodContext(SootMethod method, Context context) { this.method = method; this.context = context; } public int hashCode() { return method.hashCode() + context.hashCode(); } public boolean equals(Object o) { if (o instanceof MethodContext) { MethodContext other = (MethodContext) o; return method.equals(other.method) && context.equals(other.context); } return false; } public static MethodOrMethodContext v(SootMethod method, Context context) { if (context == null) { return method; } MethodContext probe = new MethodContext(method, context); Map<MethodContext, MethodContext> map = G.v().MethodContext_map; MethodContext ret = map.get(probe); if (ret == null) { map.put(probe, probe); return probe; } return ret; } public String toString() { return "Method " + method + " in context " + context; } }
2,079
25
77
java
soot
soot-master/src/main/java/soot/MethodOrMethodContext.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A common interface for either just a method, or a method with context. * * @author Ondrej Lhotak */ public interface MethodOrMethodContext { public SootMethod method(); public Context context(); }
1,026
28.342857
73
java
soot
soot-master/src/main/java/soot/MethodSource.java
package soot; /*- * #%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% */ /** A class which knows how to produce Body's for SootMethods. */ public interface MethodSource { /** Returns a filled-out body for the given SootMethod. */ public Body getBody(SootMethod m, String phaseName); }
1,027
33.266667
71
java
soot
soot-master/src/main/java/soot/MethodSubSignature.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import soot.jimple.Stmt; import soot.util.NumberedString; /** * Allows one-time parsing of method subsignatures. Note that these method sub signatures are resolved, i.e. we resolve the * complete types upon construction. * * @author Marc Miltenberger */ public class MethodSubSignature { public final String methodName; public final Type returnType; public final List<Type> parameterTypes; public final NumberedString numberedSubSig; private static final Pattern PATTERN_METHOD_SUBSIG = Pattern.compile("(?<returnType>.*?) (?<methodName>.*?)\\((?<parameters>.*?)\\)"); public MethodSubSignature(SootMethodRef r) { methodName = r.getName(); returnType = r.getReturnType(); parameterTypes = r.getParameterTypes(); numberedSubSig = r.getSubSignature(); } public MethodSubSignature(NumberedString subsig) { this.numberedSubSig = subsig; Matcher m = PATTERN_METHOD_SUBSIG.matcher(subsig.toString()); if (!m.matches()) { throw new IllegalArgumentException("Not a valid subsignature: " + subsig); } Scene sc = Scene.v(); methodName = m.group(2); returnType = sc.getTypeUnsafe(m.group(1)); String parameters = m.group(3); String[] spl = parameters.split(","); parameterTypes = new ArrayList<>(spl.length); if (parameters != null && !parameters.isEmpty()) { for (String p : spl) { parameterTypes.add(sc.getTypeUnsafe(p.trim())); } } } public MethodSubSignature(String methodName, Type returnType, List<Type> parameterTypes) { this.methodName = methodName; this.returnType = returnType; this.parameterTypes = parameterTypes; this.numberedSubSig = Scene.v().getSubSigNumberer() .findOrAdd(returnType + " " + methodName + "(" + Joiner.on(',').join(parameterTypes) + ")"); } /** * Creates a new instance of the {@link MethodSubSignature} class based on a call site. The subsignature of the callee will * be taken from the method referenced at the call site. * * @param callSite * The call site */ public MethodSubSignature(Stmt callSite) { this(callSite.getInvokeExpr().getMethodRef().getSubSignature()); } public String getMethodName() { return methodName; } public Type getReturnType() { return returnType; } public List<Type> getParameterTypes() { return parameterTypes; } public NumberedString getNumberedSubSig() { return numberedSubSig; } /** * Tries to find the exact method in a class. Returns null if cannot be found * * @param c * the class * @return the method (or null) */ public SootMethod getInClassUnsafe(SootClass c) { return c.getMethodUnsafe(numberedSubSig); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((numberedSubSig == null) ? 0 : numberedSubSig.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MethodSubSignature other = (MethodSubSignature) obj; if (numberedSubSig == null) { if (other.numberedSubSig != null) { return false; } } else if (!numberedSubSig.equals(other.numberedSubSig)) { return false; } return true; } @Override public String toString() { return numberedSubSig.toString(); } }
4,471
27.303797
125
java
soot
soot-master/src/main/java/soot/MethodToContexts.java
package soot; /*- * #%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.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Keeps track of the various contexts associated with each method. * * @author Ondrej Lhotak */ public final class MethodToContexts { private final Map<SootMethod, List<MethodOrMethodContext>> map = new HashMap<SootMethod, List<MethodOrMethodContext>>(); public void add(MethodOrMethodContext momc) { SootMethod m = momc.method(); List<MethodOrMethodContext> l = map.get(m); if (l == null) { map.put(m, l = new ArrayList<MethodOrMethodContext>()); } l.add(momc); } public MethodToContexts() { } public MethodToContexts(Iterator<MethodOrMethodContext> it) { add(it); } public void add(Iterator<MethodOrMethodContext> it) { while (it.hasNext()) { MethodOrMethodContext momc = it.next(); add(momc); } } public List<MethodOrMethodContext> get(SootMethod m) { List<MethodOrMethodContext> ret = map.get(m); if (ret == null) { ret = new ArrayList<MethodOrMethodContext>(); } return ret; } }
1,932
26.614286
122
java
soot
soot-master/src/main/java/soot/Modifier.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A class that provides static methods and constants to represent and work with with Java modifiers (ie public, final,...) * Represents Java modifiers as int constants that can be packed and combined by bitwise operations and methods to query * these. */ public class Modifier { public static final int ABSTRACT = 0x0400; public static final int FINAL = 0x0010; public static final int INTERFACE = 0x0200; public static final int NATIVE = 0x0100; public static final int PRIVATE = 0x0002; public static final int PROTECTED = 0x0004; public static final int PUBLIC = 0x0001; public static final int STATIC = 0x0008; public static final int SYNCHRONIZED = 0x0020; public static final int TRANSIENT = 0x0080; /* VARARGS for methods */ public static final int VOLATILE = 0x0040; /* BRIDGE for methods */ public static final int STRICTFP = 0x0800; public static final int ANNOTATION = 0x2000; public static final int ENUM = 0x4000; // dex specifific modifiers public static final int SYNTHETIC = 0x1000; public static final int CONSTRUCTOR = 0x10000; public static final int DECLARED_SYNCHRONIZED = 0x20000; // add // modifier for java 9 modules public static final int REQUIRES_TRANSITIVE = 0x0020; public static final int REQUIRES_STATIC = 0x0040; public static final int REQUIRES_SYNTHETIC = 0x1000; public static final int REQUIRES_MANDATED = 0x8000; private Modifier() { } public static boolean isAbstract(int m) { return (m & ABSTRACT) != 0; } public static boolean isFinal(int m) { return (m & FINAL) != 0; } public static boolean isInterface(int m) { return (m & INTERFACE) != 0; } public static boolean isNative(int m) { return (m & NATIVE) != 0; } public static boolean isPrivate(int m) { return (m & PRIVATE) != 0; } public static boolean isProtected(int m) { return (m & PROTECTED) != 0; } public static boolean isPublic(int m) { return (m & PUBLIC) != 0; } public static boolean isStatic(int m) { return (m & STATIC) != 0; } public static boolean isSynchronized(int m) { return (m & SYNCHRONIZED) != 0; } public static boolean isTransient(int m) { return (m & TRANSIENT) != 0; } public static boolean isVolatile(int m) { return (m & VOLATILE) != 0; } public static boolean isStrictFP(int m) { return (m & STRICTFP) != 0; } public static boolean isAnnotation(int m) { return (m & ANNOTATION) != 0; } public static boolean isEnum(int m) { return (m & ENUM) != 0; } public static boolean isSynthetic(int m) { return (m & SYNTHETIC) != 0; } public static boolean isConstructor(int m) { return (m & CONSTRUCTOR) != 0; } public static boolean isDeclaredSynchronized(int m) { return (m & DECLARED_SYNCHRONIZED) != 0; } /** * Converts the given modifiers to their string representation, in canonical form. * * @param m * a modifier set * @return a textual representation of the modifiers. */ public static String toString(int m) { StringBuilder buffer = new StringBuilder(); if (isPublic(m)) { buffer.append("public "); } else if (isPrivate(m)) { buffer.append("private "); } else if (isProtected(m)) { buffer.append("protected "); } if (isAbstract(m)) { buffer.append("abstract "); } if (isStatic(m)) { buffer.append("static "); } if (isFinal(m)) { buffer.append("final "); } if (isSynchronized(m)) { buffer.append("synchronized "); } if (isNative(m)) { buffer.append("native "); } if (isTransient(m)) { buffer.append("transient "); } if (isVolatile(m)) { buffer.append("volatile "); } if (isStrictFP(m)) { buffer.append("strictfp "); } if (isAnnotation(m)) { buffer.append("annotation "); } if (isEnum(m)) { buffer.append("enum "); } if (isInterface(m)) { buffer.append("interface "); } return buffer.toString().trim(); } }
4,907
24.298969
123
java
soot
soot-master/src/main/java/soot/ModulePathSourceLocator.java
/*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-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% */ package soot; import com.google.common.base.Optional; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.DirectoryStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import soot.JavaClassProvider.JarException; import soot.asm.AsmModuleClassProvider; /** * Provides utility methods to retrieve an input stream for a class , given a classfile and module * * @author Andreas Dann */ public class ModulePathSourceLocator extends SourceLocator { public static final String DUMMY_CLASSPATH_JDK9_FS = "VIRTUAL_FS_FOR_JDK"; private List<String> sourcePath; private Set<String> classesToLoad; public ModulePathSourceLocator(Singletons.Global g) { super(g); } public static ModulePathSourceLocator v() { return G.v().soot_ModulePathSourceLocator(); } @Override public ClassSource getClassSource(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return getClassSource(wrapper.getClassName(), wrapper.getModuleNameOptional()); } /** * Given a class name, uses the soot-module-path to return a ClassSource for the given class. */ public ClassSource getClassSource(String className, com.google.common.base.Optional<String> moduleName) { String appendToPath = ""; if (moduleName.isPresent()) { appendToPath = moduleName.get() + ":"; } if (classesToLoad == null) { classesToLoad = new HashSet<>(); classesToLoad.addAll(ModuleScene.v().getBasicClasses()); for (SootClass c : ModuleScene.v().getApplicationClasses()) { classesToLoad.add(c.getName()); } } if (modulePath == null) { modulePath = explodeModulePath(ModuleScene.v().getSootModulePath()); } if (classProviders == null) { setupClassProviders(); } JarException ex = null; for (ClassProvider cp : classProviders) { try { ClassSource ret = cp.find(appendToPath + className); if (ret != null) { return ret; } } catch (JarException e) { ex = e; } } if (ex != null) { throw ex; } return null; } public static List<String> explodeModulePath(String classPath) { List<String> ret = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String originalDir = tokenizer.nextToken(); String canonicalDir; try { canonicalDir = new File(originalDir).getCanonicalPath(); if (originalDir.equals(DUMMY_CLASSPATH_JDK9_FS)) { canonicalDir = "jrt:/"; } ret.add(canonicalDir); } catch (IOException e) { throw new CompilationDeathException("Couldn't resolve classpath entry " + originalDir + ": " + e); } } return ret; } public void additionalClassLoader(ClassLoader c) { additionalClassLoaders.add(c); } private List<String> modulePath; private int next = 0; private boolean modulePathHasNextEntry() { return this.next < this.modulePath.size(); } @Override public List<String> classPath() { return modulePath; } @Override public void invalidateClassPath() { modulePath = null; super.invalidateClassPath(); } @Override public List<String> sourcePath() { if (sourcePath == null) { sourcePath = new ArrayList<>(); for (String dir : modulePath) { ClassSourceType cst = getClassSourceType(dir); if (cst != ClassSourceType.apk && cst != ClassSourceType.jar && cst != ClassSourceType.zip) { sourcePath.add(dir); } } } return sourcePath; } private final HashMap<String, Path> moduleNameToPath = new HashMap<>(); /** * For backward compatibility returns classes in the form of module:classname * * @param aPath * where to search for classes * @return a String list containing entries of the form module:classname */ @Override public List<String> getClassesUnder(String aPath) { Map<String, List<String>> moduleClasses = getClassUnderModulePath(aPath); List<String> classes = new ArrayList<>(); for (Map.Entry<String, List<String>> entry : moduleClasses.entrySet()) { for (String className : entry.getValue()) { String moduleClassNameConcatenation = entry.getKey() + ":" + className; classes.add(moduleClassNameConcatenation); } } return classes; } /** * Scan the given module path entry. If the entry is a directory then it is a directory of modules or an exploded module. * If the entry is a regular file then it is assumed to be a packaged module. */ public Map<String, List<String>> getClassUnderModulePath(String aPath) { Map<String, List<String>> mapModuleClasses = new HashMap<>(); Path path = null; ClassSourceType type = getClassSourceType(aPath); switch (type) { case jar: path = Paths.get(aPath); break; case zip: path = Paths.get(aPath); break; case directory: path = Paths.get(aPath); break; case jrt: path = getRootModulesPathOfJDK(); break; case unknown: break; default: path = Paths.get(aPath); break; } if (classProviders == null) { setupClassProviders(); } if (path == null) { throw new RuntimeException("[Error] The path " + aPath + "is not a valid path."); } BasicFileAttributes attrs = null; try { attrs = Files.readAttributes(path, BasicFileAttributes.class); } catch (IOException e) { e.printStackTrace(); } if (attrs.isDirectory()) { Path mi = path.resolve(SootModuleInfo.MODULE_INFO_FILE); if (!Files.exists(mi)) { // assume a directory of modules mapModuleClasses.putAll(discoverModulesIn(path)); } else { // found an exploded module mapModuleClasses.putAll(buildModuleForExplodedModule(path)); } } // found a jar that is either a modular jar or a simple jar that must be transformed to an automatic module else if (attrs.isRegularFile() && path.getFileName().toString().endsWith(".jar")) { mapModuleClasses.putAll(buildModuleForJar(path)); } return mapModuleClasses; } public static Path getRootModulesPathOfJDK() { Path p = Paths.get(URI.create("jrt:/")); if (p.endsWith("modules")) { return p; } // Due to a bug in some JDKs, p not necessarily points to modules directly: // https://bugs.openjdk.java.net/browse/JDK-8227076 return p.resolve("modules"); } /** * Searches in a directory for module definitions currently only one level of hierarchy is traversed * * @param path * the directory * @return the found modules and their classes */ private Map<String, List<String>> discoverModulesIn(Path path) { Map<String, List<String>> mapModuleClasses = new HashMap<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { for (Path entry : stream) { BasicFileAttributes attrs; try { attrs = Files.readAttributes(entry, BasicFileAttributes.class); } catch (NoSuchFileException ignore) { continue; } if (attrs.isDirectory()) { Path mi = entry.resolve(SootModuleInfo.MODULE_INFO_FILE); if (Files.exists(mi)) { mapModuleClasses.putAll(buildModuleForExplodedModule(entry)); } } else if (attrs.isRegularFile() && entry.getFileName().toString().endsWith(".jar")) { mapModuleClasses.putAll(buildModuleForJar(entry)); } } } catch (IOException e) { e.printStackTrace(); } return mapModuleClasses; } /** * Creates a module definition for either a modular jar or an automatic module * * @param jar * the jar file * @return the module and its containing classes */ private Map<String, List<String>> buildModuleForJar(Path jar) { Map<String, List<String>> moduleClassMap = new HashMap<>(); try (FileSystem zipFileSystem = FileSystems.newFileSystem(jar, this.getClass().getClassLoader())) { Path mi = zipFileSystem.getPath(SootModuleInfo.MODULE_INFO_FILE); if (Files.exists(mi)) { FoundFile foundFile = new FoundFile(mi); for (ClassProvider cp : classProviders) { if (cp instanceof AsmModuleClassProvider) { String moduleName = ((AsmModuleClassProvider) cp).getModuleName(foundFile); SootModuleInfo moduleInfo = (SootModuleInfo) SootModuleResolver.v().makeClassRef(SootModuleInfo.MODULE_INFO, Optional.of(moduleName)); this.moduleNameToPath.put(moduleName, jar); List<String> classesInJar = super.getClassesUnder(jar.toAbsolutePath().toString()); for (String foundClass : classesInJar) { int index = foundClass.lastIndexOf('.'); if (index > 0) { String packageName = foundClass.substring(0, index); moduleInfo.addModulePackage(packageName); } } moduleClassMap.put(moduleName, classesInJar); } } } else { // no module-info treat as automatic module // create module name from jar String filename = jar.getFileName().toString(); // make module base on the filname of the jar String moduleName = createModuleNameForAutomaticModule(filename); boolean containsClass = ModuleScene.v().containsClass(SootModuleInfo.MODULE_INFO, Optional.of(moduleName)); SootModuleInfo moduleInfo; if (!containsClass) { moduleInfo = new SootModuleInfo(SootModuleInfo.MODULE_INFO, moduleName, true); Scene.v().addClass(moduleInfo); moduleInfo.setApplicationClass(); } else { moduleInfo = (SootModuleInfo) ModuleScene.v().getSootClass(SootModuleInfo.MODULE_INFO, Optional.of(moduleName)); if (!(moduleInfo.resolvingLevel() == SootClass.DANGLING)) { return moduleClassMap; } } // collect the packages in this jar and add them to the exported List<String> classesInJar = super.getClassesUnder(jar.toAbsolutePath().toString()); for (String foundClass : classesInJar) { int index = foundClass.lastIndexOf('.'); if (index > 0) { String packageName = foundClass.substring(0, index); moduleInfo.addModulePackage(packageName); } } moduleInfo.setResolvingLevel(SootClass.BODIES); moduleInfo.setAutomaticModule(true); this.moduleNameToPath.put(moduleName, jar); moduleClassMap.put(moduleName, classesInJar); } } catch (IOException e) { e.printStackTrace(); } return moduleClassMap; } /** * Creates a name for an automatic module based on the name of a jar file this is based on the jdk parsing of module name * in the JDK 9{@link ModulePathFinder} at least the patterns are the same * * @param filename * the name of the jar file * @return the name of the automatic module */ private String createModuleNameForAutomaticModule(String filename) { int i = filename.lastIndexOf(File.separator); if (i != -1) { filename = filename.substring(i + 1); } // drop teh file extension .jar String moduleName = filename.substring(0, filename.length() - 4); // find first occurrence of -${NUMBER}. or -${NUMBER}$ // according to the java 9 spec and current implementation, version numbers are ignored when naming automatic modules Matcher matcher = Pattern.compile("-(\\d+(\\.|$))").matcher(moduleName); if (matcher.find()) { int start = matcher.start(); moduleName = moduleName.substring(0, start); } moduleName = Pattern.compile("[^A-Za-z0-9]").matcher(moduleName).replaceAll("."); // remove all repeating dots moduleName = Pattern.compile("(\\.)(\\1)+").matcher(moduleName).replaceAll("."); // remove leading dots int len = moduleName.length(); if (len > 0 && moduleName.charAt(0) == '.') { moduleName = Pattern.compile("^\\.").matcher(moduleName).replaceAll(""); } // remove trailing dots len = moduleName.length(); if (len > 0 && moduleName.charAt(len - 1) == '.') { moduleName = Pattern.compile("\\.$").matcher(moduleName).replaceAll(""); } return moduleName; } /** * Creates/Discovers a module for an exploded module * * @param dir * the path of the exploded module * @return the module and its classes */ private Map<String, List<String>> buildModuleForExplodedModule(Path dir) { Map<String, List<String>> moduleClassesMap = new HashMap<>(); Path mi = dir.resolve(SootModuleInfo.MODULE_INFO_FILE); for (ClassProvider cp : classProviders) { if (cp instanceof AsmModuleClassProvider) { FoundFile foundFile = new FoundFile(mi); // try (InputStream in = Files.newInputStream(mi)) { String moduleName = ((AsmModuleClassProvider) cp).getModuleName(foundFile); SootModuleInfo moduleInfo = (SootModuleInfo) SootModuleResolver.v().makeClassRef(SootModuleInfo.MODULE_INFO, Optional.of(moduleName)); this.moduleNameToPath.put(moduleName, dir); List<String> classes = getClassesUnderDirectory(dir); for (String foundClass : classes) { int index = foundClass.lastIndexOf('.'); if (index > 0) { String packageName = foundClass.substring(0, index); moduleInfo.addModulePackage(packageName); } } moduleClassesMap.put(moduleName, classes); /* * } catch (IOException e) { e.printStackTrace(); } */ } } return moduleClassesMap; } /* This is called after sootClassPath has been defined. */ @Override public Set<String> classesInDynamicPackage(String str) { HashSet<String> set = new HashSet<>(0); StringTokenizer strtok = new StringTokenizer(ModuleScene.v().getSootModulePath(), String.valueOf(File.pathSeparatorChar)); while (strtok.hasMoreTokens()) { String path = strtok.nextToken(); // For jimple files List<String> l = super.getClassesUnder(path); for (String filename : l) { if (filename.startsWith(str)) { set.add(filename); } } // For class files; path = path + File.pathSeparatorChar; StringTokenizer tokenizer = new StringTokenizer(str, "."); while (tokenizer.hasMoreTokens()) { path = path + tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) { path = path + File.pathSeparatorChar; } } l = super.getClassesUnder(path); for (String string : l) { set.add(str + "." + string); } } return set; } /** * Searches for a file with the given name in the exploded modulePath. */ @Override public FoundFile lookupInClassPath(String fileName) { return lookUpInModulePath(fileName); } private ClassSourceType getClassSourceType(Path path) { String stringPath = path.toUri().toString(); if (stringPath.startsWith("jrt:/")) { return ClassSourceType.jrt; } return super.getClassSourceType(path.toAbsolutePath().toString()); } @Override protected ClassSourceType getClassSourceType(String path) { if (path.startsWith("jrt:/")) { return ClassSourceType.jrt; } return super.getClassSourceType(path); } public FoundFile lookUpInModulePath(String fileName) { String[] moduleAndClassName = fileName.split(":"); String className = moduleAndClassName[moduleAndClassName.length - 1]; String moduleName = moduleAndClassName[0]; if (className.isEmpty() || moduleName.isEmpty()) { throw new RuntimeException("No module given!"); } // look if we know where the module is Path foundModulePath = discoverModule(moduleName); FoundFile ret = null; if (foundModulePath == null) { return null; } // transform the path to a String to reuse the String dir = foundModulePath.toAbsolutePath().toString(); if (foundModulePath.toUri().toString().startsWith("jrt:/")) { dir = foundModulePath.toUri().toString(); } ClassSourceType cst = getClassSourceType(foundModulePath); if (cst == ClassSourceType.zip || cst == ClassSourceType.jar) { ret = lookupInArchive(dir, className); } else if (cst == ClassSourceType.directory) { ret = lookupInDir(dir, className); } else if (cst == ClassSourceType.jrt) { ret = lookUpInVirtualFileSystem(dir, className); } if (ret != null) { return ret; } return null; } /** * Searches in the modulepath for a certain module * * @param moduleName * the name of the module * @return the found path or null */ private Path discoverModule(String moduleName) { Path pathToModule = moduleNameToPath.get(moduleName); if (pathToModule != null) { return pathToModule; } while (modulePathHasNextEntry()) { String path = modulePath.get(next); getClassUnderModulePath(path); next++; pathToModule = moduleNameToPath.get(moduleName); if (pathToModule != null) { return pathToModule; } } return null; } protected FoundFile lookupInDir(String dir, String fileName) { Path dirPath = Paths.get(dir); Path foundFile = dirPath.resolve(fileName); if (foundFile != null && Files.isRegularFile(foundFile)) { return new FoundFile(foundFile); } return null; } /** * Looks up classes in an archive file * * @param archivePath * path to the zip/jar * @param fileName * the filename to search * @return the FoundFile */ protected FoundFile lookupInArchive(String archivePath, String fileName) { Path archive = Paths.get(archivePath); try (FileSystem zipFileSystem = FileSystems.newFileSystem(archive, this.getClass().getClassLoader())) { Path entry = zipFileSystem.getPath(fileName); if (entry == null || !Files.isRegularFile(entry)) { return null; } return new FoundFile(archive.toAbsolutePath().toString(), fileName); } catch (IOException e) { throw new RuntimeException( "Caught IOException " + e + " looking in archive file " + archivePath + " for file " + fileName); } } /** * Looks up classes in Java 9's virtual filesystem jrt:/ * * @param archivePath * path to the filesystem * @param fileName * the file to search * @return the FoundFile */ public FoundFile lookUpInVirtualFileSystem(String archivePath, String fileName) { // FileSystem fs = FileSystems.getFileSystem(URI.create(archivePath)); Path foundFile = Paths.get(URI.create(archivePath)).resolve(fileName); if (foundFile != null && Files.isRegularFile(foundFile)) { return new FoundFile(foundFile); } return null; } @Override protected void setupClassProviders() { classProviders = new LinkedList<>(); ClassProvider classFileClassProvider = new AsmModuleClassProvider(); classProviders.add(classFileClassProvider); } /** * Replaces super.getClassesUnder in order to deal with the virtual filesystem jrt * * @param aPath * the directory * @return List of found classes */ private List<String> getClassesUnderDirectory(Path aPath) { List<String> classes = new ArrayList<>(); ClassSourceType cst = getClassSourceType(aPath); if (cst == ClassSourceType.directory || cst == ClassSourceType.jrt) { FileVisitor<Path> fileVisitor = new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Note that some FileSystem implementations used by Path use even on Windows // "/" as path separator. Therefore we have to use the file-system specific path separator // instead of the system specific one (File.separatorChar). String fileName = aPath.relativize(file).toString().replace(file.getFileSystem().getSeparator(), "."); if (fileName.endsWith(".class")) { int index = fileName.lastIndexOf(".class"); classes.add(fileName.substring(0, index)); } if (fileName.endsWith(".jimple")) { int index = fileName.lastIndexOf(".jimple"); classes.add(fileName.substring(0, index)); } if (fileName.endsWith(".java")) { int index = fileName.lastIndexOf(".java"); classes.add(fileName.substring(0, index)); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(aPath, fileVisitor); } catch (IOException e) { e.printStackTrace(); } } else { throw new RuntimeException("Invalid class source type"); } return classes; } }
23,108
30.962656
124
java
soot
soot-master/src/main/java/soot/ModuleRefType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-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.base.Optional; import java.util.LinkedList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.options.Options; /** * A class that models Java's reference types. RefTypes are parameterized by a class name. Two RefType are equal iff they are * parameterized by the same class name as a String. Extends RefType in order to deal with Java 9 modules. * * @author Andreas Dann */ public class ModuleRefType extends RefType { private static final Logger logger = LoggerFactory.getLogger(ModuleRefType.class); private String moduleName; public ModuleRefType(Singletons.Global g) { super(g); } protected ModuleRefType(String className, String moduleName) { super(className); this.moduleName = moduleName; } public static RefType v(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return v(wrapper.getClassName(), wrapper.getModuleNameOptional()); } public static RefType v(String className, Optional<String> moduleName) { final boolean isPresent = moduleName.isPresent(); String module = isPresent ? ModuleUtil.v().declaringModule(className, moduleName.get()) : null; if (!isPresent && Options.v().verbose()) { logger.warn("ModuleRefType called with empty module for: " + className); } RefType rt = ModuleScene.v().getRefTypeUnsafe(className, Optional.fromNullable(module)); if (rt == null) { rt = new ModuleRefType(className, isPresent ? module : null); ModuleScene.v().addRefType(rt); } return rt; } public String getModuleName() { return moduleName; } /** * Get the SootClass object corresponding to this RefType. * * @return the corresponding SootClass */ @Override public SootClass getSootClass() { if (super.sootClass == null) { super.setSootClass(SootModuleResolver.v().makeClassRef(getClassName(), Optional.fromNullable(this.moduleName))); } return super.getSootClass(); } /** * Returns the least common superclass of this type and other. */ @Override public Type merge(Type other, Scene cm) { if (UnknownType.v().equals(other) || this.equals(other)) { return this; } if (!(other instanceof RefType)) { throw new RuntimeException("illegal type merge: " + this + " and " + other); } { // Return least common superclass final ModuleScene cmMod = (ModuleScene) cm; final SootClass javalangObject = cm.getObjectType().getSootClass(); LinkedList<SootClass> thisHierarchy = new LinkedList<>(); LinkedList<SootClass> otherHierarchy = new LinkedList<>(); // Build thisHierarchy for (SootClass sc = cmMod.getSootClass(getClassName(), Optional.fromNullable(this.moduleName));;) { thisHierarchy.addFirst(sc); if (sc == javalangObject) { break; } sc = sc.hasSuperclass() ? sc.getSuperclass() : javalangObject; } // Build otherHierarchy for (SootClass sc = cmMod.getSootClass(((RefType) other).getClassName(), Optional.fromNullable(this.moduleName));;) { otherHierarchy.addFirst(sc); if (sc == javalangObject) { break; } sc = sc.hasSuperclass() ? sc.getSuperclass() : javalangObject; } // Find least common superclass { SootClass commonClass = null; while (!otherHierarchy.isEmpty() && !thisHierarchy.isEmpty() && otherHierarchy.getFirst() == thisHierarchy.getFirst()) { commonClass = otherHierarchy.removeFirst(); thisHierarchy.removeFirst(); } if (commonClass == null) { throw new RuntimeException("Could not find a common superclass for " + this + " and " + other); } return commonClass.getType(); } } } @Override public Type getArrayElementType() { switch (getClassName()) { case "java.lang.Object": case "java.io.Serializable": case "java.lang.Cloneable": return ModuleRefType.v("java.lang.Object", Optional.of("java.base")); default: throw new RuntimeException("Attempt to get array base type of a non-array"); } } }
5,064
30.65625
125
java
soot
soot-master/src/main/java/soot/ModuleScene.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-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.base.Optional; import java.io.File; import java.nio.file.Paths; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.options.Options; import soot.util.Chain; import soot.util.HashChain; /** * Manages the SootClasses of the application being analyzed for Java 9 modules. * * @author Andreas Dann */ public class ModuleScene extends Scene { private static final Logger logger = LoggerFactory.getLogger(Scene.class); /* * holds the references to SootClass 1: String the class name 2: Map<String, RefType>: The String represents the module * that holds the corresponding RefType since multiple modules may contain the same class this is a map (for fast look ups) * TODO: evaluate if Guava's multimap is faster */ private final Map<String, Map<String, RefType>> nameToClass = new HashMap<>(); // instead of using a class path, java 9 uses a module path private String modulePath = null; public ModuleScene(Singletons.Global g) { super(g); String smp = System.getProperty("soot.module.path"); if (smp != null) { setSootModulePath(smp); } // this is a new Class in JAVA 9; that is added to Soot Basic Classes in loadNecessaryClasses method addBasicClass("java.lang.invoke.StringConcatFactory"); } public static ModuleScene v() { return G.v().soot_ModuleScene(); } @Override public SootMethod getMainMethod() { if (!hasMainClass()) { throw new RuntimeException("There is no main class set!"); } SootMethod mainMethod = mainClass.getMethodUnsafe("main", Collections.singletonList(ArrayType.v(ModuleRefType.v("java.lang.String", Optional.of("java.base")), 1)), VoidType.v()); if (mainMethod == null) { throw new RuntimeException("Main class declares no main method!"); } return mainMethod; } @Override public void extendSootClassPath(String newPathElement) { this.extendSootModulePath(newPathElement); } public void extendSootModulePath(String newPathElement) { modulePath += File.pathSeparatorChar + newPathElement; ModulePathSourceLocator.v().extendClassPath(newPathElement); } @Override public String getSootClassPath() { return getSootModulePath(); } @Override public void setSootClassPath(String p) { this.setSootModulePath(p); } public String getSootModulePath() { if (modulePath == null) { // First, check Options for a module path String cp = Options.v().soot_modulepath(); // If no module path is given via Options, just use the default. // Otherwise, if the prepend flag is set, append the default. if (cp == null || cp.isEmpty()) { cp = defaultJavaModulePath(); } else if (Options.v().prepend_classpath()) { cp += File.pathSeparatorChar + defaultJavaModulePath(); } // add process-dirs (if applicable) List<String> dirs = Options.v().process_dir(); if (!dirs.isEmpty()) { StringBuilder pds = new StringBuilder(); for (String path : dirs) { if (!cp.contains(path)) { pds.append(path).append(File.pathSeparatorChar); } } cp = pds.append(cp).toString(); } // Set the new module path modulePath = cp; } return modulePath; } public void setSootModulePath(String p) { ModulePathSourceLocator.v().invalidateClassPath(); modulePath = p; } private String defaultJavaModulePath() { StringBuilder sb = new StringBuilder(); // test for java 9 File rtJar = Paths.get(System.getProperty("java.home"), "lib", "jrt-fs.jar").toFile(); if ((rtJar.exists() && rtJar.isFile()) || !Options.v().soot_modulepath().isEmpty()) { sb.append(ModulePathSourceLocator.DUMMY_CLASSPATH_JDK9_FS); } else { throw new RuntimeException("Error: cannot find jrt-fs.jar."); } return sb.toString(); } @Override protected void addClassSilent(SootClass c) { if (c.isInScene()) { throw new RuntimeException("already managed: " + c.getName()); } final String className = c.getName(); if (containsClass(className, Optional.fromNullable(c.moduleName))) { throw new RuntimeException("duplicate class: " + className); } classes.add(c); Map<String, RefType> map = nameToClass.get(className); if (map == null) { nameToClass.put(className, map = new HashMap<>()); } map.put(c.moduleName, c.getType()); c.getType().setSootClass(c); c.setInScene(true); // Phantom classes are not really part of the hierarchy anyway, so // we can keep the old one if (!c.isPhantom) { modifyHierarchy(); } } @Override public boolean containsClass(String className) { // TODO: since this code is called from MethodNodeFactory.caseStringConstants // check if the wrapper is actually required ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return containsClass(wrapper.getClassName(), wrapper.getModuleNameOptional()); } public boolean containsClass(String className, Optional<String> moduleName) { RefType type = null; Map<String, RefType> map = nameToClass.get(className); if (map != null && !map.isEmpty()) { if (moduleName.isPresent()) { type = map.get(ModuleUtil.v().declaringModule(className, moduleName.get())); } else { // return first element type = map.values().iterator().next(); if (Options.v().verbose() && ModuleUtil.module_mode()) { logger.warn("containsClass called with empty module for: " + className); } } } return type != null && type.hasSootClass() && type.getSootClass().isInScene(); } @Override public boolean containsType(String className) { return nameToClass.containsKey(className); } /** * Attempts to load the given class and all of the required support classes. Returns the original class if it was loaded, * or null otherwise. */ public SootClass tryLoadClass(String className, int desiredLevel, Optional<String> moduleName) { setPhantomRefs(true); ClassSource source = ModulePathSourceLocator.v().getClassSource(className, moduleName); try { if (!getPhantomRefs() && source == null) { setPhantomRefs(false); return null; } } finally { if (source != null) { source.close(); } } SootClass toReturn = SootModuleResolver.v().resolveClass(className, desiredLevel, moduleName); setPhantomRefs(false); return toReturn; } /** * Loads the given class and all of the required support classes. Returns the first class. */ @Override public SootClass loadClassAndSupport(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return loadClassAndSupport(wrapper.getClassName(), wrapper.getModuleNameOptional()); } public SootClass loadClassAndSupport(String className, Optional<String> moduleName) { SootClass ret = loadClass(className, SootClass.SIGNATURES, moduleName); if (!ret.isPhantom()) { ret = loadClass(className, SootClass.BODIES, moduleName); } return ret; } @Override public SootClass loadClass(String className, int desiredLevel) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return loadClass(wrapper.getClassName(), desiredLevel, wrapper.getModuleNameOptional()); } public SootClass loadClass(String className, int desiredLevel, Optional<String> moduleName) { /* * if(Options.v().time()) Main.v().resolveTimer.start(); */ setPhantomRefs(true); SootClass toReturn = SootModuleResolver.v().resolveClass(className, desiredLevel, moduleName); setPhantomRefs(false); return toReturn; /* * if(Options.v().time()) Main.v().resolveTimer.end(); */ } /** * Returns the RefType with the given class name or primitive type. * * @throws RuntimeException * if the Type for this name cannot be found. Use {@link #getRefTypeUnsafe(String, Optional)} to check if type is * an registered RefType. */ public Type getType(String arg, Optional<String> moduleName) { String type = arg.replaceAll("([^\\[\\]]*)(.*)", "$1"); Type result = getRefTypeUnsafe(type, moduleName); if (result == null) { switch (type) { case "long": result = LongType.v(); break; case "short": result = ShortType.v(); break; case "double": result = DoubleType.v(); break; case "int": result = IntType.v(); break; case "float": result = FloatType.v(); break; case "byte": result = ByteType.v(); break; case "char": result = CharType.v(); break; case "void": result = VoidType.v(); break; case "boolean": result = BooleanType.v(); break; default: throw new RuntimeException("unknown type: '" + type + "'"); } } int arrayCount = arg.contains("[") ? arg.replaceAll("([^\\[\\]]*)(.*)", "$2").length() / 2 : 0; return (arrayCount == 0) ? result : ArrayType.v(result, arrayCount); } /** * Returns the RefType with the given className. * * @throws IllegalStateException * if the RefType for this class cannot be found. Use {@link #containsType(String)} to check if type is * registered */ public RefType getRefType(String className, Optional<String> moduleName) { RefType refType = getRefTypeUnsafe(className, moduleName); if (refType == null) { throw new IllegalStateException("RefType " + className + " not loaded. " + "If you tried to get the RefType of a library class, did you call loadNecessaryClasses()? " + "Otherwise please check Soot's classpath."); } return refType; } @Override public RefType getRefType(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return getRefType(wrapper.getClassName(), wrapper.getModuleNameOptional()); } @Override public RefType getObjectType() { return getRefType("java.lang.Object", Optional.of("java.base")); } /** * Returns the RefType with the given className. Returns null if no type with the given name can be found. */ public RefType getRefTypeUnsafe(String className, Optional<String> moduleName) { // RefType refType = nameToClass.get(className); RefType refType = null; Map<String, RefType> map = nameToClass.get(className); if (map != null && !map.isEmpty()) { if (moduleName.isPresent()) { refType = map.get(moduleName.get()); } else { // return first element refType = map.values().iterator().next(); if (Options.v().verbose() && ModuleUtil.module_mode()) { logger.warn("getRefTypeUnsafe called with empty module for: " + className); } } } return refType; } @Override public RefType getRefTypeUnsafe(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return getRefTypeUnsafe(wrapper.getClassName(), wrapper.getModuleNameOptional()); } public void addRefType(RefType type) { final String className = type.getClassName(); Map<String, RefType> map = nameToClass.get(className); if (map == null) { nameToClass.put(className, map = new HashMap<>()); } map.put(((ModuleRefType) type).getModuleName(), type); } @Override public SootClass getSootClassUnsafe(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return getSootClassUnsafe(wrapper.getClassName(), wrapper.getModuleNameOptional()); } public SootClass getSootClassUnsafe(String className, Optional<String> moduleName) { RefType type = null; Map<String, RefType> map = nameToClass.get(className); if (map != null && !map.isEmpty()) { if (moduleName.isPresent()) { type = map.get(ModuleUtil.v().declaringModule(className, moduleName.get())); } else { // return first element type = map.values().iterator().next(); if (Options.v().verbose() && ModuleUtil.module_mode()) { logger.warn("getSootClassUnsafe called with empty for: " + className); } } } if (type != null) { SootClass tsc = type.getSootClass(); if (tsc != null) { return tsc; } } if (allowsPhantomRefs() || SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME.equals(className)) { SootClass c = new SootClass(className); addClassSilent(c); c.setPhantomClass(); return c; } return null; } @Override public SootClass getSootClass(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return getSootClass(wrapper.getClassName(), wrapper.getModuleNameOptional()); } public SootClass getSootClass(String className, Optional<String> moduleName) { SootClass sc = getSootClassUnsafe(className, moduleName); if (sc != null) { return sc; } throw new RuntimeException(System.lineSeparator() + "Aborting: can't find classfile " + className); } @Override public void loadBasicClasses() { addReflectionTraceClasses(); final ModuleUtil modU = ModuleUtil.v(); int loadedClasses = 0; for (int i = SootClass.BODIES; i >= SootClass.HIERARCHY; i--) { for (String name : basicclasses[i]) { ModuleUtil.ModuleClassNameWrapper wrapper = modU.makeWrapper(name); SootClass sootClass = tryLoadClass(wrapper.getClassName(), i, wrapper.getModuleNameOptional()); if (sootClass != null && !sootClass.isPhantom()) { loadedClasses++; } } } if (loadedClasses == 0) { // Missing basic classes means no Exceptions could be loaded and no Exception hierarchy can // lead to non-deterministic Jimple code generation: catch blocks may be removed because of // non-existing Exception hierarchy. throw new RuntimeException("None of the basic classes could be loaded! Check your Soot class path!"); } } /** * Load the set of classes that soot needs, including those specified on the command-line. This is the standard way of * initialising the list of classes soot should use. */ @Override public void loadNecessaryClasses() { loadBasicClasses(); final Options opts = Options.v(); for (String name : opts.classes()) { loadNecessaryClass(name); } loadDynamicClasses(); if (opts.oaat()) { if (opts.process_dir().isEmpty()) { throw new IllegalArgumentException("If switch -oaat is used, then also -process-dir must be given."); } } else { for (String path : opts.process_dir()) { for (Map.Entry<String, List<String>> entry : ModulePathSourceLocator.v().getClassUnderModulePath(path).entrySet()) { for (String cl : entry.getValue()) { SootClass theClass = loadClassAndSupport(cl, Optional.fromNullable(entry.getKey())); theClass.setApplicationClass(); } } } } prepareClasses(); setDoneResolving(); } @Override public void loadDynamicClasses() { final ArrayList<SootClass> dynamicClasses = new ArrayList<>(); final Options opts = Options.v(); final Map<String, List<String>> temp = new HashMap<>(); temp.put(null, opts.dynamic_class()); final ModulePathSourceLocator msloc = ModulePathSourceLocator.v(); for (String path : opts.dynamic_dir()) { temp.putAll(msloc.getClassUnderModulePath(path)); } final SourceLocator sloc = SourceLocator.v(); for (String pkg : opts.dynamic_package()) { temp.get(null).addAll(sloc.classesInDynamicPackage(pkg)); } for (Map.Entry<String, List<String>> entry : temp.entrySet()) { for (String className : entry.getValue()) { dynamicClasses.add(loadClassAndSupport(className, Optional.fromNullable(entry.getKey()))); } } // remove non-concrete classes that may accidentally have been loaded for (Iterator<SootClass> iterator = dynamicClasses.iterator(); iterator.hasNext();) { SootClass c = iterator.next(); if (!c.isConcrete()) { if (opts.verbose()) { logger.warn("dynamic class " + c.getName() + " is abstract or an interface, and it will not be considered."); } iterator.remove(); } } this.dynamicClasses = dynamicClasses; } /** * Generate classes to process, adding or removing package marked by command line options. */ @Override protected void prepareClasses() { final List<String> optionsClasses = Options.v().classes(); // Remove/add all classes from packageInclusionMask as per -i option Chain<SootClass> processedClasses = new HashChain<>(); while (true) { Chain<SootClass> unprocessedClasses = new HashChain<>(getClasses()); unprocessedClasses.removeAll(processedClasses); if (unprocessedClasses.isEmpty()) { break; } processedClasses.addAll(unprocessedClasses); for (SootClass s : unprocessedClasses) { if (s.isPhantom()) { continue; } if (Options.v().app()) { s.setApplicationClass(); } if (optionsClasses.contains(s.getName())) { s.setApplicationClass(); continue; } if (s.isApplicationClass() && isExcluded(s)) { s.setLibraryClass(); } if (isIncluded(s)) { s.setApplicationClass(); } if (s.isApplicationClass()) { // make sure we have the support loadClassAndSupport(s.getName(), Optional.fromNullable(s.moduleName)); } } } } @Override public void setMainClassFromOptions() { if (mainClass == null) { String optsMain = Options.v().main_class(); if (optsMain != null && !optsMain.isEmpty()) { setMainClass(getSootClass(optsMain, null)); } else { final List<Type> mainArgs = Collections.singletonList(ArrayType.v(ModuleRefType.v("java.lang.String", Optional.of("java.base")), 1)); // try to infer a main class from the command line if none is given for (String s : Options.v().classes()) { SootClass c = getSootClass(s, null); if (c.declaresMethod("main", mainArgs, VoidType.v())) { logger.debug("No main class given. Inferred '" + c.getName() + "' as main class."); setMainClass(c); return; } } // try to infer a main class from the usual classpath if none is given for (SootClass c : getApplicationClasses()) { if (c.declaresMethod("main", mainArgs, VoidType.v())) { logger.debug("No main class given. Inferred '" + c.getName() + "' as main class."); setMainClass(c); return; } } } } } @Override public SootClass forceResolve(String className, int level) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return forceResolve(wrapper.getClassName(), level, wrapper.getModuleNameOptional()); } public SootClass forceResolve(String className, int level, Optional<String> moduleName) { boolean tmp = doneResolving; doneResolving = false; SootClass c; try { c = SootModuleResolver.v().resolveClass(className, level, moduleName); } finally { doneResolving = tmp; } return c; } @Override public SootClass makeSootClass(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return makeSootClass(wrapper.getClassName(), wrapper.getModuleName()); } public SootClass makeSootClass(String name, String moduleName) { return new SootClass(name, moduleName); } public RefType getOrAddRefType(RefType tp) { RefType existing = getRefType(tp.getClassName(), Optional.fromNullable(((ModuleRefType) tp).getModuleName())); if (existing != null) { return existing; } this.addRefType(tp); return tp; } public RefType getOrAddRefType(String className, Optional<String> moduleName) { RefType existing = getRefType(className, moduleName); if (existing != null) { return existing; } RefType tp = ModuleRefType.v(className, moduleName); this.addRefType(tp); return tp; } }
21,714
32.102134
125
java
soot
soot-master/src/main/java/soot/ModuleUtil.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-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.base.Optional; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.options.Options; /** * A utility class for dealing with java 9 modules and module dependencies. * * @author Andreas Dann */ public class ModuleUtil { private static final Logger logger = LoggerFactory.getLogger(ModuleUtil.class); /* * Soot has hard coded class names as string constants that are now contained in the java.base module, this list serves as * a lookup for these string constants. */ private static final List<String> packagesJavaBaseModule = parseJavaBasePackage(); private static final String JAVABASEFILE = "javabase.txt"; private final Cache<String, String> modulePackageCache = CacheBuilder.newBuilder().initialCapacity(60).maximumSize(800) .concurrencyLevel(Runtime.getRuntime().availableProcessors()).build(); private final LoadingCache<String, ModuleClassNameWrapper> wrapperCache = CacheBuilder.newBuilder().initialCapacity(100) .maximumSize(1000).concurrencyLevel(Runtime.getRuntime().availableProcessors()) .build(new CacheLoader<String, ModuleClassNameWrapper>() { @Override public ModuleClassNameWrapper load(String key) throws Exception { return new ModuleClassNameWrapper(key); } }); public ModuleUtil(Singletons.Global g) { } public static ModuleUtil v() { return G.v().soot_ModuleUtil(); } public final ModuleClassNameWrapper makeWrapper(String className) { try { return wrapperCache.get(className); } catch (ExecutionException e) { throw new RuntimeException(e); } } /** * Check if Soot is run with module mode enabled. * * @return true, if module mode is used */ public static boolean module_mode() { return !Options.v().soot_modulepath().isEmpty(); } /** * Finds the module that exports the given class to the given module. * * @param className * the requested class * @param toModuleName * the module from which the request is made * @return the module's name that exports the class to the given module */ public final String declaringModule(String className, String toModuleName) { if (SootModuleInfo.MODULE_INFO.equalsIgnoreCase(className)) { return toModuleName; } final ModuleScene modSc = ModuleScene.v(); final SootModuleInfo modInfo; if (modSc.containsClass(SootModuleInfo.MODULE_INFO, Optional.fromNullable(toModuleName))) { SootClass temp = modSc.getSootClass(SootModuleInfo.MODULE_INFO, Optional.fromNullable(toModuleName)); if (temp.resolvingLevel() < SootClass.BODIES) { modInfo = (SootModuleInfo) SootModuleResolver.v().resolveClass(SootModuleInfo.MODULE_INFO, SootClass.BODIES, Optional.fromNullable(toModuleName)); } else { modInfo = (SootModuleInfo) temp; } } else { modInfo = (SootModuleInfo) SootModuleResolver.v().resolveClass(SootModuleInfo.MODULE_INFO, SootClass.BODIES, Optional.fromNullable(toModuleName)); } if (modInfo == null) { return null; } final String packageName = getPackageName(className); final String chacheKey = modInfo.getModuleName() + '/' + packageName; String moduleName = modulePackageCache.getIfPresent(chacheKey); if (moduleName != null) { return moduleName; } if (modInfo.exportsPackage(packageName, toModuleName)) { return modInfo.getModuleName(); } if (modInfo.isAutomaticModule()) { // shortcut, an automatic module is allowed to access any other class if (modSc.containsClass(className)) { String foundModuleName = modSc.getSootClass(className).getModuleInformation().getModuleName(); modulePackageCache.put(chacheKey, foundModuleName); return foundModuleName; } } for (SootModuleInfo modInf : modInfo.retrieveRequiredModules().keySet()) { if (modInf.exportsPackage(packageName, toModuleName)) { modulePackageCache.put(chacheKey, modInf.getModuleName()); return modInf.getModuleName(); } else { String tModuleName = checkTransitiveChain(modInf, packageName, toModuleName, new HashSet<>()); if (tModuleName != null) { modulePackageCache.put(chacheKey, tModuleName); return tModuleName; } } } // if the class is not exported by any package, it has to internal to this module return toModuleName; } /** * recycle check if exported packages is "requires transitive" case. "requires transitive" module will transmit, need chain * check until transitive finished. * * @param modInfo * moudleinfo * @param packageName * package name * @param toModuleName * defined moduleName */ private String checkTransitiveChain(SootModuleInfo modInfo, String packageName, String toModuleName, Set<String> hasCheckedModule) { for (Map.Entry<SootModuleInfo, Integer> entry : modInfo.retrieveRequiredModules().entrySet()) { if ((entry.getValue() & Modifier.REQUIRES_TRANSITIVE) != 0) { // check if module is exported via "requires public" final SootModuleInfo key = entry.getKey(); final String moduleName = key.getModuleName(); if (!hasCheckedModule.contains(moduleName)) { hasCheckedModule.add(moduleName); if (key.exportsPackage(packageName, toModuleName)) { return moduleName; } else { return checkTransitiveChain(key, packageName, toModuleName, hasCheckedModule); } } } } return null; } /** * Returns the package name of a full qualified class name. * * @param className * a full qualified className * @return the package name */ private static String getPackageName(String className) { int index = className.lastIndexOf('.'); return (index > 0) ? className.substring(0, index) : ""; } private static List<String> parseJavaBasePackage() { List<String> packages = new ArrayList<>(); Path excludeFile = Paths.get(JAVABASEFILE); try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.exists(excludeFile) ? Files.newInputStream(excludeFile) : ModuleUtil.class.getResourceAsStream('/' + JAVABASEFILE)))) { for (String line; (line = reader.readLine()) != null;) { packages.add(line); } } catch (IOException x) { logger.warn("Cannot open file specifying the packages of module 'java.base'", x); } return packages; } /** * Wrapper class for backward compatibility with existing soot code In existing soot code classes are resolved based on * their name without specifying a module to avoid changing all occurrences of String constants in Soot this classes deals * with these String constants. * * @author Andreas Dann */ public static final class ModuleClassNameWrapper { // check for occurrence of full qualified class names private static final String fullQualifiedName = "([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$][a-zA-Z\\d_$]*"; private static final Pattern fqnClassNamePattern = Pattern.compile(fullQualifiedName); // check for occurrence of module name private static final String qualifiedModuleName = "([a-zA-Z_$])([a-zA-Z\\d_$\\.]*)+"; private static final Pattern qualifiedModuleNamePattern = Pattern.compile(qualifiedModuleName); private final String className; private final String moduleName; private ModuleClassNameWrapper(String className) { if (SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME.equals(className)) { this.className = className; this.moduleName = null; return; } String refinedClassName = className; String refinedModuleName = null; if (className.contains(":")) { String[] split = className.split(":"); if (split.length == 2) { // check if first is valid module name if (qualifiedModuleNamePattern.matcher(split[0]).matches()) { // check if second is fq classname if (fqnClassNamePattern.matcher(split[1]).matches()) { refinedModuleName = split[0]; refinedClassName = split[1]; } } } } else if (fqnClassNamePattern.matcher(className).matches()) { if (packagesJavaBaseModule.contains(ModuleUtil.getPackageName(className))) { refinedModuleName = "java.base"; } } this.className = refinedClassName; this.moduleName = refinedModuleName; ModuleUtil.v().wrapperCache.put(className, this); } public String getClassName() { return this.className; } public String getModuleName() { return this.moduleName; } public Optional<String> getModuleNameOptional() { return Optional.fromNullable(this.moduleName); } } }
10,351
34.696552
125
java
soot
soot-master/src/main/java/soot/NopUnit.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public interface NopUnit extends Unit { }
864
31.037037
71
java
soot
soot-master/src/main/java/soot/NormalUnitPrinter.java
package soot; /*- * #%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 soot.jimple.CaughtExceptionRef; import soot.jimple.IdentityRef; import soot.jimple.ParameterRef; import soot.jimple.ThisRef; /** * UnitPrinter implementation for normal (full) Jimple, Grimp, and Baf */ public class NormalUnitPrinter extends LabeledUnitPrinter { public NormalUnitPrinter(Body body) { super(body); } @Override public void type(Type t) { handleIndent(); output.append(t == null ? "<null>" : t.toQuotedString()); } @Override public void methodRef(SootMethodRef m) { handleIndent(); output.append(m.getSignature()); } @Override public void fieldRef(SootFieldRef f) { handleIndent(); output.append(f.getSignature()); } @Override public void identityRef(IdentityRef r) { handleIndent(); if (r instanceof ThisRef) { literal("@this: "); type(r.getType()); } else if (r instanceof ParameterRef) { ParameterRef pr = (ParameterRef) r; literal("@parameter" + pr.getIndex() + ": "); type(r.getType()); } else if (r instanceof CaughtExceptionRef) { literal("@caughtexception"); } else { throw new RuntimeException(); } } @Override public void literal(String s) { handleIndent(); output.append(s); } }
2,075
24.95
71
java
soot
soot-master/src/main/java/soot/NullType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java type 'null'. Implemented as a singleton. */ @SuppressWarnings("serial") public class NullType extends RefLikeType { public NullType(Singletons.Global g) { } public static NullType v() { return G.v().soot_NullType(); } @Override public int hashCode() { return 0x9891DFE1; } @Override public boolean equals(Object t) { return this == t; } @Override public String toString() { return "null_type"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseNullType(this); } @Override public Type getArrayElementType() { throw new RuntimeException("Attempt to get array base type of a non-array"); } }
1,561
23.030769
80
java
soot
soot-master/src/main/java/soot/OptionsParseException.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2015 Steven Arzt * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class OptionsParseException extends RuntimeException { private static final long serialVersionUID = -8274657472953193866L; public OptionsParseException(String msg) { super(msg); } }
1,012
29.69697
71
java
soot
soot-master/src/main/java/soot/Pack.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai and 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.Iterator; import java.util.List; import java.util.Map; /** * A wrapper object for a pack of optimizations. Provides chain-like operations, except that the key is the phase name. */ public abstract class Pack implements HasPhaseOptions, Iterable<Transform> { private final List<Transform> opts = new ArrayList<Transform>(); private final String name; @Override public String getPhaseName() { return name; } public Pack(String name) { this.name = name; } @Override public Iterator<Transform> iterator() { return opts.iterator(); } public void add(Transform t) { if (!t.getPhaseName().startsWith(getPhaseName() + ".")) { throw new RuntimeException( "Transforms in pack '" + getPhaseName() + "' must have a phase name that starts with '" + getPhaseName() + ".'."); } PhaseOptions.v().getPM().notifyAddPack(); if (get(t.getPhaseName()) != null) { throw new RuntimeException("Phase " + t.getPhaseName() + " already in pack"); } opts.add(t); } public void insertAfter(Transform t, String phaseName) { PhaseOptions.v().getPM().notifyAddPack(); for (Transform tr : opts) { if (tr.getPhaseName().equals(phaseName)) { opts.add(opts.indexOf(tr) + 1, t); return; } } throw new RuntimeException("phase " + phaseName + " not found!"); } public void insertBefore(Transform t, String phaseName) { PhaseOptions.v().getPM().notifyAddPack(); for (Transform tr : opts) { if (tr.getPhaseName().equals(phaseName)) { opts.add(opts.indexOf(tr), t); return; } } throw new RuntimeException("phase " + phaseName + " not found!"); } public Transform get(String phaseName) { for (Transform tr : opts) { if (tr.getPhaseName().equals(phaseName)) { return tr; } } return null; } public boolean remove(String phaseName) { for (Transform tr : opts) { if (tr.getPhaseName().equals(phaseName)) { opts.remove(tr); return true; } } return false; } protected void internalApply() { throw new RuntimeException("wrong type of pack"); } protected void internalApply(Body b) { throw new RuntimeException("wrong type of pack"); } public final void apply() { Map<String, String> options = PhaseOptions.v().getPhaseOptions(this); if (!PhaseOptions.getBoolean(options, "enabled")) { return; } internalApply(); } public final void apply(Body b) { Map<String, String> options = PhaseOptions.v().getPhaseOptions(this); if (!PhaseOptions.getBoolean(options, "enabled")) { return; } internalApply(b); } @Override public String getDeclaredOptions() { return soot.options.Options.getDeclaredOptionsForPhase(getPhaseName()); } @Override public String getDefaultOptions() { return soot.options.Options.getDefaultOptionsForPhase(getPhaseName()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(name); sb.append(" { "); for (int i = 0; i < opts.size(); i++) { sb.append(opts.get(i).getPhaseName()); if (i < opts.size() - 1) { sb.append(","); } sb.append(" "); } sb.append(" }"); return sb.toString(); } }
4,201
26.109677
124
java
soot
soot-master/src/main/java/soot/PackManager.java
package soot; /*- * #%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 heros.solver.CountingThreadPoolExecutor; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.baf.Baf; import soot.baf.BafASMBackend; import soot.baf.BafBody; import soot.baf.toolkits.base.LoadStoreOptimizer; import soot.baf.toolkits.base.PeepholeOptimizer; import soot.baf.toolkits.base.StoreChainOptimizer; import soot.dava.Dava; import soot.dava.DavaBody; import soot.dava.DavaBuildFile; import soot.dava.DavaPrinter; import soot.dava.DavaStaticBlockCleaner; import soot.dava.toolkits.base.AST.interProcedural.InterProceduralAnalyses; import soot.dava.toolkits.base.AST.transformations.RemoveEmptyBodyDefaultConstructor; import soot.dava.toolkits.base.AST.transformations.VoidReturnRemover; import soot.dava.toolkits.base.misc.PackageNamer; import soot.dava.toolkits.base.misc.ThrowFinder; import soot.grimp.Grimp; import soot.grimp.GrimpBody; import soot.grimp.toolkits.base.ConstructorFolder; import soot.jimple.JimpleBody; import soot.jimple.paddle.PaddleHook; import soot.jimple.spark.SparkTransformer; import soot.jimple.spark.fieldrw.FieldTagAggregator; import soot.jimple.spark.fieldrw.FieldTagger; import soot.jimple.toolkits.annotation.AvailExprTagger; import soot.jimple.toolkits.annotation.DominatorsTagger; import soot.jimple.toolkits.annotation.LineNumberAdder; import soot.jimple.toolkits.annotation.arraycheck.ArrayBoundsChecker; import soot.jimple.toolkits.annotation.arraycheck.RectangularArrayFinder; import soot.jimple.toolkits.annotation.callgraph.CallGraphGrapher; import soot.jimple.toolkits.annotation.callgraph.CallGraphTagger; import soot.jimple.toolkits.annotation.defs.ReachingDefsTagger; import soot.jimple.toolkits.annotation.fields.UnreachableFieldsTagger; import soot.jimple.toolkits.annotation.liveness.LiveVarsTagger; import soot.jimple.toolkits.annotation.logic.LoopInvariantFinder; import soot.jimple.toolkits.annotation.methods.UnreachableMethodsTagger; import soot.jimple.toolkits.annotation.nullcheck.NullCheckEliminator; import soot.jimple.toolkits.annotation.nullcheck.NullPointerChecker; import soot.jimple.toolkits.annotation.nullcheck.NullPointerColorer; import soot.jimple.toolkits.annotation.parity.ParityTagger; import soot.jimple.toolkits.annotation.profiling.ProfilingGenerator; import soot.jimple.toolkits.annotation.purity.PurityAnalysis; import soot.jimple.toolkits.annotation.qualifiers.TightestQualifiersTagger; import soot.jimple.toolkits.annotation.tags.ArrayNullTagAggregator; import soot.jimple.toolkits.base.Aggregator; import soot.jimple.toolkits.base.RenameDuplicatedClasses; import soot.jimple.toolkits.callgraph.CHATransformer; import soot.jimple.toolkits.callgraph.CallGraphPack; import soot.jimple.toolkits.callgraph.UnreachableMethodTransformer; import soot.jimple.toolkits.invoke.StaticInliner; import soot.jimple.toolkits.invoke.StaticMethodBinder; import soot.jimple.toolkits.pointer.CastCheckEliminatorDumper; import soot.jimple.toolkits.pointer.DependenceTagAggregator; import soot.jimple.toolkits.pointer.ParameterAliasTagger; import soot.jimple.toolkits.pointer.SideEffectTagger; import soot.jimple.toolkits.reflection.ConstantInvokeMethodBaseTransformer; import soot.jimple.toolkits.scalar.CommonSubexpressionEliminator; import soot.jimple.toolkits.scalar.ConditionalBranchFolder; import soot.jimple.toolkits.scalar.ConstantPropagatorAndFolder; import soot.jimple.toolkits.scalar.CopyPropagator; import soot.jimple.toolkits.scalar.DeadAssignmentEliminator; import soot.jimple.toolkits.scalar.EmptySwitchEliminator; import soot.jimple.toolkits.scalar.LocalNameStandardizer; import soot.jimple.toolkits.scalar.NopEliminator; import soot.jimple.toolkits.scalar.UnconditionalBranchFolder; import soot.jimple.toolkits.scalar.UnreachableCodeEliminator; import soot.jimple.toolkits.scalar.pre.BusyCodeMotion; import soot.jimple.toolkits.scalar.pre.LazyCodeMotion; import soot.jimple.toolkits.thread.mhp.MhpTransformer; import soot.jimple.toolkits.thread.synchronization.LockAllocator; import soot.jimple.toolkits.typing.TypeAssigner; import soot.options.Options; import soot.shimple.Shimple; import soot.shimple.ShimpleBody; import soot.shimple.ShimpleTransformer; import soot.shimple.toolkits.scalar.SConstantPropagatorAndFolder; import soot.sootify.TemplatePrinter; import soot.tagkit.InnerClassTagAggregator; import soot.tagkit.LineNumberTagAggregator; import soot.toDex.DexPrinter; import soot.toolkits.exceptions.DuplicateCatchAllTrapRemover; import soot.toolkits.exceptions.TrapTightener; import soot.toolkits.graph.interaction.InteractionHandler; import soot.toolkits.scalar.ConstantInitializerToTagTransformer; import soot.toolkits.scalar.ConstantValueToInitializerTransformer; import soot.toolkits.scalar.LocalPacker; import soot.toolkits.scalar.LocalSplitter; import soot.toolkits.scalar.SharedInitializationLocalSplitter; import soot.toolkits.scalar.UnusedLocalEliminator; import soot.util.EscapedWriter; import soot.util.JasminOutputStream; import soot.util.PhaseDumper; import soot.xml.TagCollector; import soot.xml.XMLPrinter; /** * Manages the Packs containing the various phases and their options. */ public class PackManager { private static final Logger logger = LoggerFactory.getLogger(PackManager.class); public static boolean DEBUG = false; private final Map<String, Pack> packNameToPack = new HashMap<String, Pack>(); private final List<Pack> packList = new LinkedList<Pack>(); private boolean onlyStandardPacks = false; private JarOutputStream jarFile = null; protected DexPrinter dexPrinter = null; public PackManager(Singletons.Global g) { PhaseOptions.v().setPackManager(this); init(); } public static PackManager v() { return G.v().soot_PackManager(); } public boolean onlyStandardPacks() { return onlyStandardPacks; } void notifyAddPack() { onlyStandardPacks = false; } private void init() { Pack p; // Jimple body creation addPack(p = new JimpleBodyPack()); { p.add(new Transform("jb.tt", TrapTightener.v())); p.add(new Transform("jb.dtr", DuplicateCatchAllTrapRemover.v())); p.add(new Transform("jb.ese", EmptySwitchEliminator.v())); p.add(new Transform("jb.ls", LocalSplitter.v())); p.add(new Transform("jb.sils", SharedInitializationLocalSplitter.v())); p.add(new Transform("jb.a", Aggregator.v())); p.add(new Transform("jb.ule", UnusedLocalEliminator.v())); p.add(new Transform("jb.tr", TypeAssigner.v())); p.add(new Transform("jb.ulp", LocalPacker.v())); p.add(new Transform("jb.lns", LocalNameStandardizer.v())); p.add(new Transform("jb.cp", CopyPropagator.v())); p.add(new Transform("jb.dae", DeadAssignmentEliminator.v())); p.add(new Transform("jb.cp-ule", UnusedLocalEliminator.v())); p.add(new Transform("jb.lp", LocalPacker.v())); p.add(new Transform("jb.ne", NopEliminator.v())); p.add(new Transform("jb.uce", UnreachableCodeEliminator.v())); p.add(new Transform("jb.cbf", ConditionalBranchFolder.v())); } // Java to Jimple - Jimple body creation addPack(p = new JavaToJimpleBodyPack()); { p.add(new Transform("jj.ls", LocalSplitter.v())); p.add(new Transform("jj.sils", SharedInitializationLocalSplitter.v())); p.add(new Transform("jj.a", Aggregator.v())); p.add(new Transform("jj.ule", UnusedLocalEliminator.v())); p.add(new Transform("jj.ne", NopEliminator.v())); p.add(new Transform("jj.tr", TypeAssigner.v())); // p.add(new Transform("jj.ct", CondTransformer.v())); p.add(new Transform("jj.ulp", LocalPacker.v())); p.add(new Transform("jj.lns", LocalNameStandardizer.v())); p.add(new Transform("jj.cp", CopyPropagator.v())); p.add(new Transform("jj.dae", DeadAssignmentEliminator.v())); p.add(new Transform("jj.cp-ule", UnusedLocalEliminator.v())); p.add(new Transform("jj.lp", LocalPacker.v())); p.add(new Transform("jj.uce", UnreachableCodeEliminator.v())); } // Whole-Jimple Pre-processing Pack addPack(p = new ScenePack("wjpp")); { p.add(new Transform("wjpp.cimbt", ConstantInvokeMethodBaseTransformer.v())); } // Whole-Shimple Pre-processing Pack addPack(p = new ScenePack("wspp")); // Call graph pack addPack(p = new CallGraphPack("cg")); { p.add(new Transform("cg.cha", CHATransformer.v())); p.add(new Transform("cg.spark", SparkTransformer.v())); p.add(new Transform("cg.paddle", PaddleHook.v())); } // Whole-Shimple transformation pack addPack(p = new ScenePack("wstp")); // Whole-Shimple Optimization pack addPack(p = new ScenePack("wsop")); // Whole-Jimple transformation pack addPack(p = new ScenePack("wjtp")); { p.add(new Transform("wjtp.mhp", MhpTransformer.v())); p.add(new Transform("wjtp.tn", LockAllocator.v())); p.add(new Transform("wjtp.rdc", RenameDuplicatedClasses.v())); } // Whole-Jimple Optimization pack addPack(p = new ScenePack("wjop")); { p.add(new Transform("wjop.smb", StaticMethodBinder.v())); p.add(new Transform("wjop.si", StaticInliner.v())); } // Give another chance to do Whole-Jimple transformation // The RectangularArrayFinder will be put into this package. addPack(p = new ScenePack("wjap")); { p.add(new Transform("wjap.ra", RectangularArrayFinder.v())); p.add(new Transform("wjap.umt", UnreachableMethodsTagger.v())); p.add(new Transform("wjap.uft", UnreachableFieldsTagger.v())); p.add(new Transform("wjap.tqt", TightestQualifiersTagger.v())); p.add(new Transform("wjap.cgg", CallGraphGrapher.v())); p.add(new Transform("wjap.purity", PurityAnalysis.v())); // [AM] } // Shimple pack addPack(p = new BodyPack(Shimple.PHASE)); // Shimple transformation pack addPack(p = new BodyPack("stp")); // Shimple optimization pack addPack(p = new BodyPack("sop")); { p.add(new Transform("sop.cpf", SConstantPropagatorAndFolder.v())); } // Jimple transformation pack addPack(p = new BodyPack("jtp")); // Jimple optimization pack addPack(p = new BodyPack("jop")); { p.add(new Transform("jop.cse", CommonSubexpressionEliminator.v())); p.add(new Transform("jop.bcm", BusyCodeMotion.v())); p.add(new Transform("jop.lcm", LazyCodeMotion.v())); p.add(new Transform("jop.cp", CopyPropagator.v())); p.add(new Transform("jop.cpf", ConstantPropagatorAndFolder.v())); p.add(new Transform("jop.cbf", ConditionalBranchFolder.v())); p.add(new Transform("jop.dae", DeadAssignmentEliminator.v())); p.add(new Transform("jop.nce", new NullCheckEliminator())); p.add(new Transform("jop.uce1", UnreachableCodeEliminator.v())); p.add(new Transform("jop.ubf1", UnconditionalBranchFolder.v())); p.add(new Transform("jop.uce2", UnreachableCodeEliminator.v())); p.add(new Transform("jop.ubf2", UnconditionalBranchFolder.v())); p.add(new Transform("jop.ule", UnusedLocalEliminator.v())); } // Jimple annotation pack addPack(p = new BodyPack("jap")); { p.add(new Transform("jap.npc", NullPointerChecker.v())); p.add(new Transform("jap.npcolorer", NullPointerColorer.v())); p.add(new Transform("jap.abc", ArrayBoundsChecker.v())); p.add(new Transform("jap.profiling", ProfilingGenerator.v())); p.add(new Transform("jap.sea", SideEffectTagger.v())); p.add(new Transform("jap.fieldrw", FieldTagger.v())); p.add(new Transform("jap.cgtagger", CallGraphTagger.v())); p.add(new Transform("jap.parity", ParityTagger.v())); p.add(new Transform("jap.pat", ParameterAliasTagger.v())); p.add(new Transform("jap.rdtagger", ReachingDefsTagger.v())); p.add(new Transform("jap.lvtagger", LiveVarsTagger.v())); p.add(new Transform("jap.che", CastCheckEliminatorDumper.v())); p.add(new Transform("jap.umt", new UnreachableMethodTransformer())); p.add(new Transform("jap.lit", LoopInvariantFinder.v())); p.add(new Transform("jap.aet", AvailExprTagger.v())); p.add(new Transform("jap.dmt", DominatorsTagger.v())); } // CFG Viewer // addPack(p = new BodyPack("cfg")); // { // p.add(new Transform("cfg.output", CFGPrinter.v())); // } // Grimp body creation addPack(p = new BodyPack("gb")); { p.add(new Transform("gb.a1", Aggregator.v())); p.add(new Transform("gb.cf", ConstructorFolder.v())); p.add(new Transform("gb.a2", Aggregator.v())); p.add(new Transform("gb.ule", UnusedLocalEliminator.v())); } // Grimp optimization pack addPack(p = new BodyPack("gop")); // Baf body creation addPack(p = new BodyPack("bb")); { p.add(new Transform("bb.lso", LoadStoreOptimizer.v())); p.add(new Transform("bb.pho", PeepholeOptimizer.v())); p.add(new Transform("bb.ule", UnusedLocalEliminator.v())); p.add(new Transform("bb.lp", LocalPacker.v())); p.add(new Transform("bb.sco", StoreChainOptimizer.v())); p.add(new Transform("bb.ne", NopEliminator.v())); } // Baf optimization pack addPack(p = new BodyPack("bop")); // Code attribute tag aggregation pack addPack(p = new BodyPack("tag")); { p.add(new Transform("tag.ln", LineNumberTagAggregator.v())); p.add(new Transform("tag.an", ArrayNullTagAggregator.v())); p.add(new Transform("tag.dep", DependenceTagAggregator.v())); p.add(new Transform("tag.fieldrw", FieldTagAggregator.v())); } // Dummy Dava Phase /* * Nomair A. Naeem 13th Feb 2006 Added so that Dava Options can be added as phase options rather than main soot options * since they only make sense when decompiling The db phase options are added in soot_options.xml */ addPack(p = new BodyPack("db")); { p.add(new Transform("db.transformations", null)); p.add(new Transform("db.renamer", null)); p.add(new Transform("db.deobfuscate", null)); p.add(new Transform("db.force-recompile", null)); } onlyStandardPacks = true; } private void addPack(Pack p) { if (packNameToPack.containsKey(p.getPhaseName())) { throw new RuntimeException("Duplicate pack " + p.getPhaseName()); } packNameToPack.put(p.getPhaseName(), p); packList.add(p); } public boolean hasPack(String phaseName) { return getPhase(phaseName) != null; } public Pack getPack(String phaseName) { Pack p = packNameToPack.get(phaseName); return p; } public boolean hasPhase(String phaseName) { return getPhase(phaseName) != null; } public HasPhaseOptions getPhase(String phaseName) { int index = phaseName.indexOf('.'); if (index < 0) { return getPack(phaseName); } String packName = phaseName.substring(0, index); return hasPack(packName) ? getPack(packName).get(phaseName) : null; } public Transform getTransform(String phaseName) { return (Transform) getPhase(phaseName); } public Collection<Pack> allPacks() { return Collections.unmodifiableList(packList); } public void runPacks() { if (Options.v().oaat()) { runPacksForOneClassAtATime(); } else { runPacksNormally(); } } private void runPacksForOneClassAtATime() { if (Options.v().src_prec() == Options.src_prec_class && Options.v().keep_line_number()) { LineNumberAdder.v().internalTransform("", null); } setupJAR(); final boolean validate = Options.v().validate(); final SourceLocator srcLoc = SourceLocator.v(); final Scene scene = Scene.v(); for (String path : Options.v().process_dir()) { // hack1: resolve to signatures only for (String cl : srcLoc.getClassesUnder(path)) { SootClass clazz = scene.forceResolve(cl, SootClass.SIGNATURES); clazz.setApplicationClass(); } // hack2: for each class one after another: // a) resolve to bodies // b) run packs // c) write class // d) remove bodies for (String cl : srcLoc.getClassesUnder(path)) { SootClass clazz = null; ClassSource source = srcLoc.getClassSource(cl); if (source == null) { throw new RuntimeException("Could not locate class source"); } try { clazz = scene.getSootClass(cl); clazz.setResolvingLevel(SootClass.BODIES); source.resolve(clazz); } finally { source.close(); } // Create tags from all values we only have in code assingments now for (SootClass sc : scene.getApplicationClasses()) { if (validate) { sc.validate(); } if (!sc.isPhantom) { ConstantInitializerToTagTransformer.v().transformClass(sc, true); } } runBodyPacks(clazz); // generate output writeClass(clazz); if (!Options.v().no_writeout_body_releasing()) { releaseBodies(clazz); } } // for (String cl : SourceLocator.v().getClassesUnder(path)) { // SootClass clazz = Scene.v().forceResolve(cl, SootClass.BODIES); // releaseBodies(clazz); // Scene.v().removeClass(clazz); // } } tearDownJAR(); handleInnerClasses(); } private void runPacksNormally() { if (Options.v().src_prec() == Options.src_prec_class && Options.v().keep_line_number()) { LineNumberAdder.v().internalTransform("", null); } if (Options.v().whole_program() || Options.v().whole_shimple()) { runWholeProgramPacks(); } retrieveAllBodies(); // Create tags from all values we only have in code assignments now final boolean validate = Options.v().validate(); for (SootClass sc : Scene.v().getApplicationClasses()) { if (validate) { sc.validate(); } if (!sc.isPhantom) { ConstantInitializerToTagTransformer.v().transformClass(sc, true); } } // if running coffi cfg metrics, print out results and exit if (soot.jbco.Main.metrics) { coffiMetrics(); System.exit(0); } preProcessDAVA(); if (Options.v().interactive_mode()) { if (InteractionHandler.v().getInteractionListener() == null) { logger.debug("Cannot run in interactive mode. No listeners available. Continuing in regular mode."); Options.v().set_interactive_mode(false); } else { logger.debug("Running in interactive mode."); } } runBodyPacks(); handleInnerClasses(); } public void coffiMetrics() { int tV = 0, tE = 0, hM = 0; double aM = 0; HashMap<SootMethod, int[]> hashVem = soot.coffi.CFG.methodsToVEM; for (int[] vem : hashVem.values()) { tV += vem[0]; tE += vem[1]; aM += vem[2]; if (vem[2] > hM) { hM = vem[2]; } } if (hashVem.size() > 0) { aM /= hashVem.size(); } logger.debug("Vertices, Edges, Avg Degree, Highest Deg: " + tV + " " + tE + " " + aM + " " + hM); } public void runBodyPacks() { runBodyPacks(reachableClasses()); } public JarOutputStream getJarFile() { return jarFile; } public void writeOutput() { setupJAR(); if (Options.v().verbose()) { PhaseDumper.v().dumpBefore("output"); } switch (Options.v().output_format()) { case Options.output_format_dava: postProcessDAVA(); outputDava(); break; case Options.output_format_dex: case Options.output_format_force_dex: writeDexOutput(); break; default: writeOutput(reachableClasses()); tearDownJAR(); break; } postProcessXML(reachableClasses()); if (!Options.v().no_writeout_body_releasing()) { releaseBodies(reachableClasses()); } if (Options.v().verbose()) { PhaseDumper.v().dumpAfter("output"); } } protected void writeDexOutput() { dexPrinter = new DexPrinter(); writeOutput(reachableClasses()); dexPrinter.print(); dexPrinter = null; } private void setupJAR() { if (Options.v().output_jar()) { String outFileName = SourceLocator.v().getOutputJarName(); try { jarFile = new JarOutputStream(new FileOutputStream(outFileName)); } catch (IOException e) { throw new CompilationDeathException("Cannot open output Jar file " + outFileName); } } else { jarFile = null; } } private void runWholeProgramPacks() { if (Options.v().whole_shimple()) { ShimpleTransformer.v().transform(); getPack("wspp").apply(); getPack("cg").apply(); getPack("wstp").apply(); getPack("wsop").apply(); } else { getPack("wjpp").apply(); getPack("cg").apply(); getPack("wjtp").apply(); getPack("wjop").apply(); getPack("wjap").apply(); } PaddleHook.v().finishPhases(); } /* preprocess classes for DAVA */ private void preProcessDAVA() { if (Options.v().output_format() == Options.output_format_dava) { if (!PhaseOptions.getBoolean(PhaseOptions.v().getPhaseOptions("db"), "source-is-javac")) { /* * It turns out that the exception attributes of a method i.e. those exceptions that a method can throw are only * checked by the Java compiler and not the JVM * * Javac does place this information into the attributes but other compilers dont hence if the source is not javac * then we have to do this fancy analysis to find all the potential exceptions that might get thrown * * BY DEFAULT the option javac of db is set to true so we assume that the source is javac * * See ThrowFinder for more details */ if (DEBUG) { System.out.println("Source is not Javac hence invoking ThrowFinder"); } ThrowFinder.v().find(); } else { if (DEBUG) { System.out.println("Source is javac hence we dont need to invoke ThrowFinder"); } } PackageNamer.v().fixNames(); } } private void runBodyPacks(final Iterator<SootClass> classes) { int threadNum = Options.v().num_threads(); if (threadNum < 1) { threadNum = Runtime.getRuntime().availableProcessors(); } CountingThreadPoolExecutor executor = new CountingThreadPoolExecutor(threadNum, threadNum, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); while (classes.hasNext()) { final SootClass c = classes.next(); executor.execute(() -> runBodyPacks(c)); } // Wait till all packs have been executed try { executor.awaitCompletion(); executor.shutdown(); } catch (InterruptedException e) { // Something went horribly wrong throw new RuntimeException("Could not wait for pack threads to finish: " + e.getMessage(), e); } // If something went wrong, we tell the world Throwable exception = executor.getException(); if (exception != null) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException(exception); } } } private void handleInnerClasses() { InnerClassTagAggregator.v().internalTransform("", null); } protected void writeOutput(Iterator<SootClass> classes) { // If we're writing individual class files, we can write them // concurrently. Otherwise, we need to synchronize for not destroying // the shared output stream. int threadNum = Options.v().output_format() == Options.output_format_class && jarFile == null ? Runtime.getRuntime().availableProcessors() : 1; CountingThreadPoolExecutor executor = new CountingThreadPoolExecutor(threadNum, threadNum, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); while (classes.hasNext()) { final SootClass c = classes.next(); executor.execute(() -> writeClass(c)); } // Wait till all classes have been written try { executor.awaitCompletion(); executor.shutdown(); } catch (InterruptedException e) { // Something went horribly wrong throw new RuntimeException("Could not wait for writer threads to finish: " + e.getMessage(), e); } // If something went wrong, we tell the world Throwable exception = executor.getException(); if (exception != null) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException(exception); } } } private void tearDownJAR() { try { if (jarFile != null) { jarFile.close(); } } catch (IOException e) { throw new CompilationDeathException("Error closing output jar: " + e); } } private void releaseBodies(Iterator<SootClass> classes) { while (classes.hasNext()) { releaseBodies(classes.next()); } } private Iterator<SootClass> reachableClasses() { return Scene.v().getApplicationClasses().snapshotIterator(); } /* post process for DAVA */ private void postProcessDAVA() { final boolean transformations = PhaseOptions.getBoolean(PhaseOptions.v().getPhaseOptions("db.transformations"), "enabled"); /* * apply analyses etc */ for (SootClass s : Scene.v().getApplicationClasses()) { /* * Nomair A. Naeem 5-Jun-2005 Added to remove the *final* bug in Dava (often seen in AspectJ programs) */ DavaStaticBlockCleaner.v().staticBlockInlining(s); // remove returns from void methods VoidReturnRemover.cleanClass(s); // remove the default constructor if this is the only one present RemoveEmptyBodyDefaultConstructor.checkAndRemoveDefault(s); /* * Nomair A. Naeem 1st March 2006 Check if we want to apply transformations one reason we might not want to do this is * when gathering old metrics data!! */ // debug("analyzeAST","Advanced Analyses ALL DISABLED"); logger.debug("Analyzing " + SourceLocator.v().getFileNameFor(s, Options.v().output_format()) + "... "); /* * Nomair A. Naeem 29th Jan 2006 Added hook into going through each decompiled method again Need it for all the * implemented AST analyses */ for (SootMethod m : s.getMethods()) { /* * 3rd April 2006 Fixing RuntimeException caused when you retrieve an active body when one is not present */ if (m.hasActiveBody()) { DavaBody body = (DavaBody) m.getActiveBody(); // System.out.println("body"+body.toString()); if (transformations) { body.analyzeAST(); } else { body.applyBugFixes(); } } } } // going through all classes /* * Nomair A. Naeem March 6th, 2006 * * SHOULD BE INVOKED ONLY ONCE!!! If interprocedural analyses are turned off they are checked within this method. * * HAVE TO invoke this analysis since this invokes the renamer!! */ if (transformations) { InterProceduralAnalyses.applyInterProceduralAnalyses(); } } private void outputDava() { /* * Generate decompiled code */ String pathForBuild = null; ArrayList<String> decompiledClasses = new ArrayList<String>(); for (SootClass s : Scene.v().getApplicationClasses()) { String fileName = SourceLocator.v().getFileNameFor(s, Options.v().output_format()); decompiledClasses.add(fileName.substring(fileName.lastIndexOf('/') + 1)); if (pathForBuild == null) { pathForBuild = fileName.substring(0, fileName.lastIndexOf('/') + 1); // System.out.println(pathForBuild); } if (Options.v().gzip()) { fileName = fileName + ".gz"; } PrintWriter writerOut = null; try { OutputStream streamOut; if (jarFile != null) { jarFile.putNextEntry(new JarEntry(fileName.replace('\\', '/'))); streamOut = jarFile; } else { streamOut = new FileOutputStream(fileName); } if (Options.v().gzip()) { streamOut = new GZIPOutputStream(streamOut); } writerOut = new PrintWriter(new OutputStreamWriter(streamOut)); } catch (IOException e) { throw new CompilationDeathException("Cannot output file " + fileName, e); } logger.debug("Generating " + fileName + "... "); DavaPrinter.v().printTo(s, writerOut); try { writerOut.flush(); if (jarFile == null) { writerOut.close(); } else { jarFile.closeEntry(); } } catch (IOException e) { throw new CompilationDeathException("Cannot close output file " + fileName); } } // going through all classes /* * Create the build.xml for Dava */ if (pathForBuild != null) { // path for build is probably ending in sootoutput/dava/src // definetly remove the src if (pathForBuild.endsWith("src/")) { pathForBuild = pathForBuild.substring(0, pathForBuild.length() - 4); } String fileName = pathForBuild + "build.xml"; try (OutputStream streamOut = new FileOutputStream(fileName)) { PrintWriter writerOut = new PrintWriter(new OutputStreamWriter(streamOut)); DavaBuildFile.generate(writerOut, decompiledClasses); writerOut.flush(); } catch (IOException e) { throw new CompilationDeathException("Cannot open output file " + fileName, e); } } } @SuppressWarnings("fallthrough") private void runBodyPacks(SootClass c) { final int format = Options.v().output_format(); if (format == Options.output_format_dava) { logger.debug("Decompiling {}...", c.getName()); // January 13th, 2006 SootMethodAddedByDava is set to false for // SuperFirstStmtHandler G.v().SootMethodAddedByDava = false; } else { logger.debug("Transforming {}...", c.getName()); } boolean produceBaf = false, produceGrimp = false, produceDava = false, produceJimple = true, produceShimple = false; switch (format) { case Options.output_format_none: case Options.output_format_xml: case Options.output_format_jimple: case Options.output_format_jimp: case Options.output_format_template: case Options.output_format_dex: case Options.output_format_force_dex: break; case Options.output_format_shimp: case Options.output_format_shimple: produceShimple = true; // FLIP produceJimple produceJimple = false; break; case Options.output_format_dava: produceDava = true; // FALL THROUGH case Options.output_format_grimp: case Options.output_format_grimple: produceGrimp = true; break; case Options.output_format_baf: case Options.output_format_b: produceBaf = true; break; case Options.output_format_jasmin: case Options.output_format_class: case Options.output_format_asm: produceGrimp = Options.v().via_grimp(); produceBaf = !produceGrimp; break; default: throw new RuntimeException(); } TagCollector tc = (format != Options.output_format_jimple && Options.v().xml_attributes()) ? new TagCollector() : null; boolean wholeShimple = Options.v().whole_shimple(); if (Options.v().via_shimple()) { produceShimple = true; } // here we create a copy of the methods so that transformers are able // to add method bodies during the following iteration; // such adding of methods happens in rare occasions: for instance when // resolving a method reference to a non-existing method, then this // method is created as a phantom method when phantom-refs are enabled for (SootMethod m : new ArrayList<SootMethod>(c.getMethods())) { if (DEBUG) { if (!m.getExceptions().isEmpty()) { System.out.println("PackManager printing out jimple body exceptions for method " + m.toString() + " " + m.getExceptions().toString()); } } if (!m.isConcrete()) { continue; } if (produceShimple || wholeShimple) { ShimpleBody sBody; // whole shimple or not? { Body body = m.retrieveActiveBody(); if (!m.hasActiveBody()) { continue; } if (body instanceof ShimpleBody) { sBody = (ShimpleBody) body; if (!sBody.isSSA()) { sBody.rebuild(); } } else { sBody = Shimple.v().newBody(body); } } m.setActiveBody(sBody); getPack("stp").apply(sBody); getPack("sop").apply(sBody); if (produceJimple || (wholeShimple && !produceShimple)) { m.setActiveBody(sBody.toJimpleBody()); } } if (produceJimple) { Body body = m.retrieveActiveBody(); getTransform("jb.cp").apply(body); // CopyPropagator getTransform("jb.cbf").apply(body); // ConditionalBranchFolder getTransform("jb.uce").apply(body); // UnreachableCodeEliminator getTransform("jb.dae").apply(body); // DeadAssignmentEliminator getTransform("jb.cp-ule").apply(body); // UnusedLocalEliminator getPack("jtp").apply(body); if (Options.v().validate()) { body.validate(); } getPack("jop").apply(body); getPack("jap").apply(body); if (tc != null) { tc.collectBodyTags(body); } } // getPack("cfg").apply(m.retrieveActiveBody()); if (m.hasActiveBody()) { if (produceGrimp) { GrimpBody newBody = Grimp.v().newBody(m.getActiveBody(), "gb"); m.setActiveBody(newBody); getPack("gop").apply(newBody); } else if (produceBaf) { m.setActiveBody(convertJimpleBodyToBaf(m)); } } } if (tc != null) { processXMLForClass(c, tc); } if (produceDava) { for (SootMethod m : c.getMethods()) { if (!m.isConcrete() || !m.hasActiveBody()) { //note: abnormal class can have a concrete method without body. continue; } // all the work done in decompilation is done in DavaBody which // is invoked from within newBody m.setActiveBody(Dava.v().newBody(m.getActiveBody())); } /* * January 13th, 2006 SuperFirstStmtHandler might have set SootMethodAddedByDava if it needs to create a new method. */ // could use G to add new method................... if (G.v().SootMethodAddedByDava) { // System.out.println("PACKMANAGER SAYS:----------------Have to // add the new method(s)"); for (SootMethod m : G.v().SootMethodsAdded) { c.addMethod(m); } G.v().SootMethodsAdded = new ArrayList<SootMethod>(); G.v().SootMethodAddedByDava = false; } } // end if produceDava } public BafBody convertJimpleBodyToBaf(SootMethod m) { JimpleBody body = (JimpleBody) m.getActiveBody().clone(); // Change // ConditionalBranchFolder.v().transform(body); // UnreachableCodeEliminator.v().transform(body); // DeadAssignmentEliminator.v().transform(body); // UnusedLocalEliminator.v().transform(body); BafBody bafBody = Baf.v().newBody(body); getPack("bop").apply(bafBody); getPack("tag").apply(bafBody); if (Options.v().validate()) { bafBody.validate(); } return bafBody; } protected void writeClass(SootClass c) { final int format = Options.v().output_format(); switch (format) { case Options.output_format_none: case Options.output_format_dava: return; case Options.output_format_dex: case Options.output_format_force_dex: // just add the class to the dex printer, writing is done after // adding all classes dexPrinter.add(c); return; case Options.output_format_jimple: // Create code assignments for those values we only have in code assignments if (!c.isPhantom) { ConstantValueToInitializerTransformer.v().transformClass(c); } break; default: break; } String fileName = SourceLocator.v().getFileNameFor(c, format); if (Options.v().gzip()) { fileName = fileName + ".gz"; } OutputStream streamOut = null; PrintWriter writerOut = null; try { if (jarFile != null) { // Fix path delimiters according to ZIP specification fileName = fileName.replace("\\", "/"); JarEntry entry = new JarEntry(fileName); entry.setMethod(ZipEntry.DEFLATED); jarFile.putNextEntry(entry); streamOut = jarFile; } else { new File(fileName).getParentFile().mkdirs(); streamOut = new FileOutputStream(fileName); } if (Options.v().gzip()) { streamOut = new GZIPOutputStream(streamOut); } if (format == Options.output_format_class) { if (Options.v().jasmin_backend()) { streamOut = new JasminOutputStream(streamOut); } } writerOut = new PrintWriter(new OutputStreamWriter(streamOut)); logger.debug("Writing to " + fileName); } catch (IOException e) { throw new CompilationDeathException("Cannot output file " + fileName, e); } if (Options.v().xml_attributes()) { Printer.v().setOption(Printer.ADD_JIMPLE_LN); } switch (format) { case Options.output_format_class: if (!Options.v().jasmin_backend()) { createASMBackend(c).generateClassFile(streamOut); break; } case Options.output_format_jasmin: createJasminBackend(c).print(writerOut); break; case Options.output_format_jimp: case Options.output_format_shimp: case Options.output_format_b: case Options.output_format_grimp: Printer.v().setOption(Printer.USE_ABBREVIATIONS); Printer.v().printTo(c, writerOut); break; case Options.output_format_baf: case Options.output_format_jimple: case Options.output_format_shimple: case Options.output_format_grimple: writerOut = new PrintWriter(new EscapedWriter(new OutputStreamWriter(streamOut))); Printer.v().printTo(c, writerOut); break; case Options.output_format_xml: writerOut = new PrintWriter(new EscapedWriter(new OutputStreamWriter(streamOut))); XMLPrinter.v().printJimpleStyleTo(c, writerOut); break; case Options.output_format_template: writerOut = new PrintWriter(new OutputStreamWriter(streamOut)); TemplatePrinter.v().printTo(c, writerOut); break; case Options.output_format_asm: createASMBackend(c).generateTextualRepresentation(writerOut); break; default: throw new RuntimeException(); } try { writerOut.flush(); if (jarFile == null) { streamOut.close(); writerOut.close(); } else { jarFile.closeEntry(); } } catch (IOException e) { throw new CompilationDeathException("Cannot close output file " + fileName); } } /** * Factory method for creating a new backend on top of Jasmin * * @param c * The class for which to create a Jasmin-based backend * @return The Jasmin-based backend for writing the given class into bytecode */ private AbstractJasminClass createJasminBackend(SootClass c) { if (c.containsBafBody()) { return new soot.baf.JasminClass(c); } else { return new soot.jimple.JasminClass(c); } } /** * Factory method for creating a new backend on top of ASM. At the moment, we always start from BAF. Custom implementations * can use other techniques. * * @param c * The class for which to create the ASM backend * @return The ASM backend for writing the class into bytecode */ protected BafASMBackend createASMBackend(SootClass c) { return new BafASMBackend(c, Options.v().java_version()); } private void postProcessXML(Iterator<SootClass> classes) { if (!Options.v().xml_attributes()) { return; } if (Options.v().output_format() != Options.output_format_jimple) { return; } while (classes.hasNext()) { SootClass c = classes.next(); processXMLForClass(c); } } private void processXMLForClass(SootClass c, TagCollector tc) { int ofmt = Options.v().output_format(); final int format = ofmt != Options.output_format_none ? ofmt : Options.output_format_jimple; String fileName = SourceLocator.v().getFileNameFor(c, format); XMLAttributesPrinter xap = new XMLAttributesPrinter(fileName, SourceLocator.v().getOutputDir()); xap.printAttrs(c, tc); } /** * assumption: only called when <code>Options.v().output_format() == Options.output_format_jimple</code> */ private void processXMLForClass(SootClass c) { final int format = Options.v().output_format(); String fileName = SourceLocator.v().getFileNameFor(c, format); XMLAttributesPrinter xap = new XMLAttributesPrinter(fileName, SourceLocator.v().getOutputDir()); xap.printAttrs(c); } private void releaseBodies(SootClass cl) { for (Iterator<SootMethod> methodIt = cl.methodIterator(); methodIt.hasNext();) { SootMethod m = methodIt.next(); if (m.hasActiveBody()) { m.releaseActiveBody(); } } } private void retrieveAllBodies() { // The old coffi front-end is not thread-safe int threadNum = Options.v().coffi() ? 1 : Runtime.getRuntime().availableProcessors(); CountingThreadPoolExecutor executor = new CountingThreadPoolExecutor(threadNum, threadNum, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); for (Iterator<SootClass> clIt = reachableClasses(); clIt.hasNext();) { SootClass cl = clIt.next(); // note: the following is a snapshot iterator; // this is necessary because it can happen that phantom methods // are added during resolution for (SootMethod m : new ArrayList<SootMethod>(cl.getMethods())) { if (m.isConcrete()) { executor.execute(() -> m.retrieveActiveBody()); } } } // Wait till all method bodies have been loaded try { executor.awaitCompletion(); executor.shutdown(); } catch (InterruptedException e) { // Something went horribly wrong throw new RuntimeException("Could not wait for loader threads to finish: " + e.getMessage(), e); } // If something went wrong, we tell the world Throwable exception = executor.getException(); if (exception != null) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException(exception); } } } }
44,505
33.87931
125
java
soot
soot-master/src/main/java/soot/PatchingChain.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import soot.util.Chain; /** * An implementation of a Chain which can contain only Units, and handles patching to deal with element insertions and * removals. This is done by calling Unit.redirectJumpsToThisTo at strategic times. */ @SuppressWarnings("serial") public class PatchingChain<E extends Unit> extends AbstractCollection<E> implements Chain<E> { protected final Chain<E> innerChain; /** Constructs a PatchingChain from the given Chain. */ public PatchingChain(Chain<E> aChain) { innerChain = aChain; } /** * Returns the inner chain used by the PatchingChain. In general, this should not be used. However, direct access to the * inner chain may be necessary if you wish to perform certain operations (such as control-flow manipulations) without * interference from the patching algorithms. **/ public Chain<E> getNonPatchingChain() { return innerChain; } /** Adds the given object to this Chain. */ @Override public boolean add(E o) { return innerChain.add(o); } /** Replaces <code>out</code> in the Chain by <code>in</code>. */ @Override public void swapWith(E out, E in) { innerChain.swapWith(out, in); out.redirectJumpsToThisTo(in); } /** Inserts <code>toInsert</code> in the Chain after <code>point</code>. */ @Override public void insertAfter(E toInsert, E point) { innerChain.insertAfter(toInsert, point); } /** Inserts <code>toInsert</code> in the Chain after <code>point</code>. */ @Override public void insertAfter(List<E> toInsert, E point) { innerChain.insertAfter(toInsert, point); } @Override public void insertAfter(Chain<E> toInsert, E point) { innerChain.insertAfter(toInsert, point); } @Override public void insertAfter(Collection<? extends E> toInsert, E point) { innerChain.insertAfter(toInsert, point); } /** Inserts <code>toInsert</code> in the Chain before <code>point</code>. */ @Override public void insertBefore(List<E> toInsert, E point) { if (!toInsert.isEmpty()) { // Insert toInsert backwards into the list E previousPoint = point; for (ListIterator<E> it = toInsert.listIterator(toInsert.size()); it.hasPrevious();) { E o = it.previous(); insertBeforeNoRedirect(o, previousPoint); previousPoint = o; } point.redirectJumpsToThisTo(toInsert.get(0)); } } /** Inserts <code>toInsert</code> in the Chain before <code>point</code>. */ @Override public void insertBefore(Chain<E> toInsert, E point) { if (!toInsert.isEmpty()) { // Insert toInsert backwards into the list E previousPoint = point; for (E o = toInsert.getLast(); o != null; o = toInsert.getPredOf(o)) { insertBeforeNoRedirect(o, previousPoint); previousPoint = o; } point.redirectJumpsToThisTo(toInsert.getFirst()); } } /** Inserts <code>toInsert</code> in the Chain before <code>point</code>. */ @Override public void insertBefore(E toInsert, E point) { point.redirectJumpsToThisTo(toInsert); innerChain.insertBefore(toInsert, point); } @Override public void insertBefore(Collection<? extends E> toInsert, E point) { if (toInsert instanceof Chain) { @SuppressWarnings("unchecked") final Chain<E> temp = (Chain<E>) toInsert; insertBefore(temp, point); } else if (toInsert instanceof List) { @SuppressWarnings("unchecked") final List<E> temp = (List<E>) toInsert; insertBefore(temp, point); } else { insertBefore(new ArrayList<>(toInsert), point); } } /** Inserts <code>toInsert</code> in the Chain before <code>point</code> WITHOUT redirecting jumps. */ public void insertBeforeNoRedirect(E toInsert, E point) { innerChain.insertBefore(toInsert, point); } /** Inserts <code>toInsert</code> in the Chain before <code>point</code> WITHOUT redirecting jumps. */ public void insertBeforeNoRedirect(List<E> toInsert, E point) { if (!toInsert.isEmpty()) { // Insert toInsert backwards into the list E previousPoint = point; for (ListIterator<E> it = toInsert.listIterator(toInsert.size()); it.hasPrevious();) { E o = it.previous(); insertBeforeNoRedirect(o, previousPoint); previousPoint = o; } } } /** Returns true if object <code>a</code> follows object <code>b</code> in the Chain. */ @Override public boolean follows(E a, E b) { return innerChain.follows(a, b); } /** Removes the given object from this Chain. */ @Override public boolean remove(Object obj) { if (contains(obj)) { @SuppressWarnings("unchecked") E objCast = (E) obj; patchBeforeRemoval(innerChain, objCast); return innerChain.remove(objCast); } else { return false; } } protected static <E extends Unit> void patchBeforeRemoval(Chain<E> chain, E removing) { Unit successor = chain.getSuccOf(removing); if (successor == null) { successor = chain.getPredOf(removing); } // Note that redirecting to the last unit in the method // like this is probably incorrect when dealing with a Trap. // I.e., let's say that the final unit in the method used to // be U10, preceded by U9, and that there was a Trap which // returned U10 as getEndUnit(). I.e., before the trap covered U9. // When we redirect the Trap's end unit to U9, the trap will no // longer cover U9. I know this is incorrect, but I'm not sure how // to fix it, so I'm leaving this comment in the hopes that some // future maintainer will see the right course to take. removing.redirectJumpsToThisTo(successor); } /** Returns true if this patching chain contains the specified element. */ @Override public boolean contains(Object u) { return innerChain.contains(u); } /** Adds the given object at the beginning of the Chain. */ @Override public void addFirst(E u) { innerChain.addFirst(u); } /** Adds the given object at the end of the Chain. */ @Override public void addLast(E u) { innerChain.addLast(u); } /** Removes the first object from this Chain. */ @Override public void removeFirst() { remove(innerChain.getFirst()); } /** Removes the last object from this Chain. */ @Override public void removeLast() { remove(innerChain.getLast()); } /** Returns the first object in this Chain. */ @Override public E getFirst() { return innerChain.getFirst(); } /** Returns the last object in this Chain. */ @Override public E getLast() { return innerChain.getLast(); } /** Returns the object immediately following <code>point</code>. */ @Override public E getSuccOf(E point) { return innerChain.getSuccOf(point); } /** Returns the object immediately preceding <code>point</code>. */ @Override public E getPredOf(E point) { return innerChain.getPredOf(point); } /** Returns the size of this Chain. */ @Override public int size() { return innerChain.size(); } /** Returns the number of times this chain has been modified. */ @Override public long getModificationCount() { return innerChain.getModificationCount(); } @Override public Collection<E> getElementsUnsorted() { return innerChain.getElementsUnsorted(); } /** * Returns an iterator over a copy of this chain. This avoids ConcurrentModificationExceptions from being thrown if the * underlying Chain is modified during iteration. Do not use this to remove elements which have not yet been iterated over! */ @Override public Iterator<E> snapshotIterator() { return innerChain.snapshotIterator(); } /** Returns an iterator over this Chain. */ @Override public Iterator<E> iterator() { return new PatchingIterator(innerChain); } /** Returns an iterator over this Chain, starting at the given object. */ @Override public Iterator<E> iterator(E u) { return new PatchingIterator(innerChain, u); } /** Returns an iterator over this Chain, starting at head and reaching tail (inclusive). */ @Override public Iterator<E> iterator(E head, E tail) { return new PatchingIterator(innerChain, head, tail); } protected class PatchingIterator implements Iterator<E> { protected final Chain<E> innerChain; protected final Iterator<E> innerIterator; protected E lastObject; protected boolean state = false; protected PatchingIterator(Chain<E> innerChain) { this.innerChain = innerChain; this.innerIterator = innerChain.iterator(); } protected PatchingIterator(Chain<E> innerChain, E u) { this.innerChain = innerChain; this.innerIterator = innerChain.iterator(u); } protected PatchingIterator(Chain<E> innerChain, E head, E tail) { this.innerChain = innerChain; this.innerIterator = innerChain.iterator(head, tail); } @Override public boolean hasNext() { return innerIterator.hasNext(); } @Override public E next() { lastObject = innerIterator.next(); state = true; return lastObject; } @Override public void remove() { if (!state) { throw new IllegalStateException("remove called before first next() call"); } else { state = false; patchBeforeRemoval(innerChain, lastObject); innerIterator.remove(); } } } }
10,400
29.412281
125
java
soot
soot-master/src/main/java/soot/PhaseOptions.java
package soot; /*- * #%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.Map; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Manages the phase options of the various soot phases. */ public class PhaseOptions { private static final Logger logger = LoggerFactory.getLogger(PhaseOptions.class); /** * Needed for preventing infinite recursion in constructor. Termination is assured: each constructor is called exactly * once. Here is a case analysis. a. PackManager used first. Then its constructor needs PhaseOptions, which also needs a * PackManager; OK because we store the PackManager being initialized in a field. b. PhaseOptions used first. Then getPM() * calls PackManager.v(), which calls the constr, which sets the .pm field here, uses PhaseOptions (which uses * PackManager), and returns. OK. */ private PackManager pm; public void setPackManager(PackManager m) { this.pm = m; } PackManager getPM() { if (pm == null) { PackManager.v(); } return pm; } public PhaseOptions(Singletons.Global g) { } public static PhaseOptions v() { return G.v().soot_PhaseOptions(); } private final Map<HasPhaseOptions, Map<String, String>> phaseToOptionMap = new HashMap<HasPhaseOptions, Map<String, String>>(); public Map<String, String> getPhaseOptions(String phaseName) { return getPhaseOptions(getPM().getPhase(phaseName)); } public Map<String, String> getPhaseOptions(HasPhaseOptions phase) { Map<String, String> ret = phaseToOptionMap.get(phase); if (ret == null) { ret = new HashMap<String, String>(); } else { ret = new HashMap<String, String>(ret); } for (StringTokenizer st = new StringTokenizer(phase.getDefaultOptions()); st.hasMoreTokens();) { String opt = st.nextToken(); String key = getKey(opt); String value = getValue(opt); ret.putIfAbsent(key, value); } return Collections.unmodifiableMap(ret); } public boolean processPhaseOptions(String phaseName, String option) { for (StringTokenizer st = new StringTokenizer(option, ","); st.hasMoreTokens();) { if (!setPhaseOption(phaseName, st.nextToken())) { return false; } } return true; } /** * This method returns true iff key "name" is in options and maps to "true". */ public static boolean getBoolean(Map<String, String> options, String name) { String val = options.get(name); return val != null && "true".equals(val); } /** * If key "name" is in options, this method returns true iff it maps to "true". If the key "name" is not in options, the * given default value is returned. */ public static boolean getBoolean(Map<String, String> options, String name, boolean defaultValue) { String val = options.get(name); return val != null ? "true".equals(val) : defaultValue; } /** * This method returns the value of "name" in options or "" if "name" is not found. */ public static String getString(Map<String, String> options, String name) { String val = options.get(name); return val != null ? val : ""; } /** * This method returns the float value of "name" in options or 1.0 if "name" is not found. */ public static float getFloat(Map<String, String> options, String name) { String val = options.get(name); return val != null ? Float.parseFloat(val) : 1.0f; } /** * This method returns the integer value of "name" in options or 0 if "name" is not found. */ public static int getInt(Map<String, String> options, String name) { String val = options.get(name); return val != null ? Integer.parseInt(val) : 0; } private Map<String, String> mapForPhase(String phaseName) { HasPhaseOptions phase = getPM().getPhase(phaseName); return phase != null ? mapForPhase(phase) : null; } private Map<String, String> mapForPhase(HasPhaseOptions phase) { Map<String, String> optionMap = phaseToOptionMap.get(phase); if (optionMap == null) { phaseToOptionMap.put(phase, optionMap = new HashMap<String, String>()); } return optionMap; } private String getKey(String option) { int delimLoc = option.indexOf(':'); if (delimLoc < 0) { if ("on".equals(option) || "off".equals(option)) { return "enabled"; } else { return option; } } else { return option.substring(0, delimLoc); } } private String getValue(String option) { int delimLoc = option.indexOf(':'); if (delimLoc < 0) { if ("off".equals(option)) { return "false"; } else { return "true"; } } else { return option.substring(delimLoc + 1); } } private void resetRadioPack(String phaseName) { for (Pack p : getPM().allPacks()) { if (p instanceof RadioScenePack) { if (p.get(phaseName) != null) { for (Transform t : p) { setPhaseOption(t.getPhaseName(), "enabled:false"); } } } } } private boolean checkParentEnabled(String phaseName) { // for (Pack p : getPM().allPacks()) { // if (!getBoolean(getPhaseOptions(p), "enabled")) { // for (Transform t : p) { // if (t.getPhaseName().equals(phaseName)) { // logger.debug("Attempt to set option for phase " + phaseName + " of disabled pack " + p.getPhaseName()); // return false; // } // } // } // } return true; } public boolean setPhaseOption(String phaseName, String option) { HasPhaseOptions phase = getPM().getPhase(phaseName); if (phase == null) { logger.debug("Option " + option + " given for nonexistent phase " + phaseName); return false; } else { return setPhaseOption(phase, option); } } public boolean setPhaseOption(HasPhaseOptions phase, String option) { Map<String, String> optionMap = mapForPhase(phase); if (!checkParentEnabled(phase.getPhaseName())) { return false; } if (optionMap == null) { logger.debug("Option " + option + " given for nonexistent phase " + phase.getPhaseName()); return false; } String key = getKey(option); if ("enabled".equals(key) && "true".equals(getValue(option))) { resetRadioPack(phase.getPhaseName()); } if (declaresOption(phase, key)) { optionMap.put(key, getValue(option)); return true; } logger.debug("Invalid option " + option + " for phase " + phase.getPhaseName()); return false; } private boolean declaresOption(String phaseName, String option) { HasPhaseOptions phase = getPM().getPhase(phaseName); return declaresOption(phase, option); } private boolean declaresOption(HasPhaseOptions phase, String option) { String declareds = phase.getDeclaredOptions(); for (StringTokenizer st = new StringTokenizer(declareds); st.hasMoreTokens();) { if (st.nextToken().equals(option)) { return true; } } return false; } public void setPhaseOptionIfUnset(String phaseName, String option) { Map<String, String> optionMap = mapForPhase(phaseName); if (optionMap == null) { throw new RuntimeException("No such phase " + phaseName); } if (optionMap.containsKey(getKey(option))) { return; } if (!declaresOption(phaseName, getKey(option))) { throw new RuntimeException("No option " + option + " for phase " + phaseName); } optionMap.put(getKey(option), getValue(option)); } }
8,326
30.904215
124
java
soot
soot-master/src/main/java/soot/PointsToAnalysis.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A generic interface to any type of pointer analysis. * * @author Ondrej Lhotak */ public interface PointsToAnalysis { /** Returns the set of objects pointed to by variable l. */ public PointsToSet reachingObjects(Local l); /** Returns the set of objects pointed to by variable l in context c. */ public PointsToSet reachingObjects(Context c, Local l); /** Returns the set of objects pointed to by static field f. */ public PointsToSet reachingObjects(SootField f); /** * Returns the set of objects pointed to by instance field f of the objects in the PointsToSet s. */ public PointsToSet reachingObjects(PointsToSet s, SootField f); /** * Returns the set of objects pointed to by instance field f of the objects pointed to by l. */ public PointsToSet reachingObjects(Local l, SootField f); /** * Returns the set of objects pointed to by instance field f of the objects pointed to by l in context c. */ public PointsToSet reachingObjects(Context c, Local l, SootField f); /** * Returns the set of objects pointed to by elements of the arrays in the PointsToSet s. */ public PointsToSet reachingObjectsOfArrayElement(PointsToSet s); public static final String THIS_NODE = "THIS_NODE"; public static final int RETURN_NODE = -2; public static final String THROW_NODE = "THROW_NODE"; public static final String ARRAY_ELEMENTS_NODE = "ARRAY_ELEMENTS_NODE"; public static final String CAST_NODE = "CAST_NODE"; public static final String STRING_ARRAY_NODE = "STRING_ARRAY_NODE"; public static final String STRING_NODE = "STRING_NODE"; public static final String STRING_NODE_LOCAL = "STRING_NODE_LOCAL"; public static final String EXCEPTION_NODE = "EXCEPTION_NODE"; public static final String RETURN_STRING_CONSTANT_NODE = "RETURN_STRING_CONSTANT_NODE"; public static final String STRING_ARRAY_NODE_LOCAL = "STRING_ARRAY_NODE_LOCAL"; public static final String MAIN_THREAD_NODE = "MAIN_THREAD_NODE"; public static final String MAIN_THREAD_NODE_LOCAL = "MAIN_THREAD_NODE_LOCAL"; public static final String MAIN_THREAD_GROUP_NODE = "MAIN_THREAD_GROUP_NODE"; public static final String MAIN_THREAD_GROUP_NODE_LOCAL = "MAIN_THREAD_GROUP_NODE_LOCAL"; public static final String MAIN_CLASS_NAME_STRING = "MAIN_CLASS_NAME_STRING"; public static final String MAIN_CLASS_NAME_STRING_LOCAL = "MAIN_CLASS_NAME_STRING_LOCAL"; public static final String DEFAULT_CLASS_LOADER = "DEFAULT_CLASS_LOADER"; public static final String DEFAULT_CLASS_LOADER_LOCAL = "DEFAULT_CLASS_LOADER_LOCAL"; public static final String FINALIZE_QUEUE = "FINALIZE_QUEUE"; public static final String CANONICAL_PATH = "CANONICAL_PATH"; public static final String CANONICAL_PATH_LOCAL = "CANONICAL_PATH_LOCAL"; public static final String PRIVILEGED_ACTION_EXCEPTION = "PRIVILEGED_ACTION_EXCEPTION"; public static final String PRIVILEGED_ACTION_EXCEPTION_LOCAL = "PRIVILEGED_ACTION_EXCEPTION_LOCAL"; public static final String PHI_NODE = "PHI_NODE"; }
3,837
43.114943
107
java
soot
soot-master/src/main/java/soot/PointsToSet.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Set; import soot.jimple.ClassConstant; /** * A generic interface to some set of runtime objects computed by a pointer analysis. * * @author Ondrej Lhotak */ public interface PointsToSet { /** Returns true if this set contains no run-time objects. */ public boolean isEmpty(); /** Returns true if this set shares some objects with other. */ public boolean hasNonEmptyIntersection(PointsToSet other); /** Set of all possible run-time types of objects in the set. */ public Set<Type> possibleTypes(); /** * If this points-to set consists entirely of string constants, returns a set of these constant strings. If this point-to * set may contain something other than constant strings, returns null. */ public Set<String> possibleStringConstants(); /** * If this points-to set consists entirely of objects of type java.lang.Class of a known class, returns a set of * ClassConstant's that are these classes. If this point-to set may contain something else, returns null. */ public Set<ClassConstant> possibleClassConstants(); }
1,899
32.928571
123
java
soot
soot-master/src/main/java/soot/PolymorphicMethodRef.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.tagkit.AnnotationTag; import soot.tagkit.Tag; import soot.tagkit.VisibilityAnnotationTag; /** * Special class to treat the methods with polymorphic signatures in the classes {@link java.lang.invoke.MethodHandle} and * {@link java.lang.invoke.VarHandle}. As described in * https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.4.4 method references to the methods with a * polymorphic signature, which are the methods in `java.lang.invoke.MethodHandle` and `java.lang.invoke.VarHandle`, require * special treatment * * @author Andreas Dann created on 06.02.19 * @author Manuel Benz 27.2.19 */ public class PolymorphicMethodRef extends SootMethodRefImpl { public static final String METHODHANDLE_SIGNATURE = "java.lang.invoke.MethodHandle"; public static final String VARHANDLE_SIGNATURE = "java.lang.invoke.VarHandle"; public static final String POLYMORPHIC_SIGNATURE = "java/lang/invoke/MethodHandle$PolymorphicSignature"; /** * Check if the declaring class "has the rights" to declare polymorphic methods * {@see http://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.4.4} * * @param declaringClass * the class to check * @return if the class is allowed according to the JVM Spec */ public static boolean handlesClass(SootClass declaringClass) { return handlesClass(declaringClass.getName()); } public static boolean handlesClass(String declaringClassName) { return PolymorphicMethodRef.METHODHANDLE_SIGNATURE.equals(declaringClassName) || PolymorphicMethodRef.VARHANDLE_SIGNATURE.equals(declaringClassName); } /** * Constructor. * * @param declaringClass * the declaring class. Must not be {@code null} * @param name * the method name. Must not be {@code null} * @param parameterTypes * the types of parameters. May be {@code null} * @param returnType * the type of return value. Must not be {@code null} * @param isStatic * the static modifier value * @throws IllegalArgumentException * is thrown when {@code declaringClass}, or {@code name}, or {@code returnType} is null */ public PolymorphicMethodRef(SootClass declaringClass, String name, List<Type> parameterTypes, Type returnType, boolean isStatic) { super(declaringClass, name, parameterTypes, returnType, isStatic); } @Override public SootMethod resolve() { SootMethod method = getDeclaringClass().getMethodUnsafe(getName(), getParameterTypes(), getReturnType()); if (method != null) { return method; } // No method with matching parameter types or return types found for polymorphic methods, // we don't care about the return or parameter types. We just check if a method with the // name exists and has a polymorphic type signature. // Note(MB): We cannot use getMethodByName here since the method name is ambiguous after // adding the first method with same name and refined signature. for (SootMethod candidateMethod : getDeclaringClass().getMethods()) { if (candidateMethod.getName().equals(getName())) { Tag annotationsTag = candidateMethod.getTag(VisibilityAnnotationTag.NAME); if (annotationsTag != null) { for (AnnotationTag annotation : ((VisibilityAnnotationTag) annotationsTag).getAnnotations()) { // check the annotation's type if (('L' + POLYMORPHIC_SIGNATURE + ';').equals(annotation.getType())) { // The method is polymorphic, add a fitting method to the MethodHandle // or VarHandle class, as the JVM does on runtime. return addPolyMorphicMethod(candidateMethod); } } } } } return super.resolve(); } private SootMethod addPolyMorphicMethod(SootMethod originalPolyMorphicMethod) { SootMethod newMethod = new SootMethod(getName(), getParameterTypes(), getReturnType(), originalPolyMorphicMethod.modifiers); getDeclaringClass().addMethod(newMethod); return newMethod; } }
4,944
38.56
124
java
soot
soot-master/src/main/java/soot/PrimType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Abstract class for Soot classes that that model Java primitive types (ie all types except void, null, reference types, and * array types) * * @author Ondrej Lhotak */ @SuppressWarnings("serial") public abstract class PrimType extends Type { public abstract RefType boxedType(); public abstract Class<?> getJavaBoxedType(); public abstract Class<?> getJavaPrimitiveType(); @Override public boolean isAllowedInFinalCode() { return true; } }
1,283
27.533333
125
java
soot
soot-master/src/main/java/soot/Printer.java
package soot; /*- * #%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.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.function.Function; import soot.options.Options; import soot.tagkit.Host; import soot.tagkit.JimpleLineNumberTag; import soot.tagkit.Tag; import soot.toolkits.graph.UnitGraph; import soot.util.Chain; import soot.util.DeterministicHashMap; /** * Prints out a class and all its methods. */ public class Printer { public static final int USE_ABBREVIATIONS = 0x0001, ADD_JIMPLE_LN = 0x0010; private int options = 0; private int jimpleLnNum = 0; // actual line number private Function<Body, LabeledUnitPrinter> customUnitPrinter; private Function<SootClass, String> customClassSignaturePrinter; private Function<SootMethod, String> customMethodSignaturePrinter; public Printer(Singletons.Global g) { } public static Printer v() { return G.v().soot_Printer(); } public boolean useAbbreviations() { return (options & USE_ABBREVIATIONS) != 0; } public boolean addJimpleLn() { return (options & ADD_JIMPLE_LN) != 0; } public void setOption(int opt) { options |= opt; } public void clearOption(int opt) { options &= ~opt; } public int getJimpleLnNum() { return jimpleLnNum; } public void setJimpleLnNum(int newVal) { jimpleLnNum = newVal; } public void incJimpleLnNum() { jimpleLnNum++; // logger.debug("jimple Ln Num: " + jimpleLnNum); } public void printTo(SootClass cl, PrintWriter out) { // add jimple line number tags setJimpleLnNum(1); // Print class name + modifiers { StringBuilder sb = new StringBuilder(); for (StringTokenizer st = new StringTokenizer(Modifier.toString(cl.getModifiers())); st.hasMoreTokens();) { String tok = st.nextToken(); if (!cl.isInterface() || !"abstract".equals(tok)) { sb.append(tok).append(' '); } } sb.append(cl.isInterface() ? " " : "class ").append(printSignature(cl)); out.print(sb.toString()); } // Print extension if (cl.hasSuperclass()) { out.print(" extends " + printSignature(cl.getSuperclass())); } // Print interfaces { Iterator<SootClass> interfaceIt = cl.getInterfaces().iterator(); if (interfaceIt.hasNext()) { out.print(" implements " + printSignature(interfaceIt.next())); while (interfaceIt.hasNext()) { out.print(", " + printSignature(interfaceIt.next())); } } } out.println(); incJimpleLnNum(); // if (!addJimpleLn()) { // for (Tag t : cl.getTags()) { // out.println(t); // } // } out.println('{'); incJimpleLnNum(); final boolean printTagsInOutput = Options.v().print_tags_in_output(); if (printTagsInOutput) { for (Tag t : cl.getTags()) { out.println("/*" + t.toString() + "*/"); } } // Print fields for (SootField f : cl.getFields()) { if (!f.isPhantom()) { if (printTagsInOutput) { for (Tag t : f.getTags()) { out.println("/*" + t.toString() + "*/"); } } out.println(" " + f.getDeclaration() + ";"); if (addJimpleLn()) { setJimpleLnNum(addJimpleLnTags(getJimpleLnNum(), f)); } // incJimpleLnNum(); } } // Print methods { Iterator<SootMethod> methodIt = cl.methodIterator(); if (methodIt.hasNext()) { if (cl.getMethodCount() != 0) { out.println(); incJimpleLnNum(); } do { // condition already checked SootMethod method = methodIt.next(); if (method.isPhantom()) { continue; } if (!Modifier.isAbstract(method.getModifiers()) && !Modifier.isNative(method.getModifiers())) { Body body = method.retrieveActiveBody(); // force loading the body if (body == null) { // in case we don't have it throw new RuntimeException("method " + method.getName() + " has no active body!"); } if (printTagsInOutput) { for (Tag t : method.getTags()) { out.println("/*" + t.toString() + "*/"); } } printTo(body, out); } else { if (printTagsInOutput) { for (Tag t : method.getTags()) { out.println("/*" + t.toString() + "*/"); } } out.println(" " + method.getDeclaration() + ";"); incJimpleLnNum(); } if (methodIt.hasNext()) { out.println(); incJimpleLnNum(); } } while (methodIt.hasNext()); } } out.println("}"); incJimpleLnNum(); } /** * Prints out the method corresponding to the {@link Body}, (declaration and body) in the textual format corresponding to * the IR used to encode the {@link Body}. * * @param b * the Body instance to print. * @param out * a PrintWriter instance to print to. */ public void printTo(Body b, PrintWriter out) { // b.validate(); out.println(" " + printSignature(b.getMethod())); // incJimpleLnNum(); if (addJimpleLn()) { setJimpleLnNum(addJimpleLnTags(getJimpleLnNum(), b.getMethod())); // logger.debug("added jimple ln tag for method: " + b.getMethod().toString() + " " + // b.getMethod().getDeclaringClass().getName()); } else { // only print tags if not printing attributes in a file // for (Tag t : b.getMethod().getTags()) { // out.println(t); // incJimpleLnNum(); // } } out.println(" {"); incJimpleLnNum(); LabeledUnitPrinter up = getUnitPrinter(b); if (addJimpleLn()) { up.setPositionTagger(new AttributesUnitPrinter(getJimpleLnNum())); } printLocalsInBody(b, up); printStatementsInBody(b, out, up, new soot.toolkits.graph.BriefUnitGraph(b)); out.println(" }"); incJimpleLnNum(); } public void setCustomUnitPrinter(Function<Body, LabeledUnitPrinter> customUnitPrinter) { this.customUnitPrinter = customUnitPrinter; } public void setCustomClassSignaturePrinter(Function<SootClass, String> customPrinter) { this.customClassSignaturePrinter = customPrinter; } public void setCustomMethodSignaturePrinter(Function<SootMethod, String> customPrinter) { this.customMethodSignaturePrinter = customPrinter; } private LabeledUnitPrinter getUnitPrinter(Body b) { if (customUnitPrinter != null) { return customUnitPrinter.apply(b); } else if (useAbbreviations()) { return new BriefUnitPrinter(b); } else { return new NormalUnitPrinter(b); } } private String printSignature(SootClass sootClass) { if (customClassSignaturePrinter != null) { return customClassSignaturePrinter.apply(sootClass); } else { return Scene.v().quotedNameOf(sootClass.getName()); } } private String printSignature(SootMethod sootMethod) { if (customMethodSignaturePrinter != null) { return customMethodSignaturePrinter.apply(sootMethod); } else { return sootMethod.getDeclaration(); } } /** * Prints the given <code>JimpleBody</code> to the specified <code>PrintWriter</code>. */ private void printStatementsInBody(Body body, java.io.PrintWriter out, LabeledUnitPrinter up, UnitGraph unitGraph) { final Chain<Unit> units = body.getUnits(); final Unit firstUnit = units.getFirst(); for (final Unit currentStmt : units) { // Print appropriate header. { // Put an empty line if the previous node was a branch node, the current node is a join node // or the previous statement does not have body statement as a successor, or if // body statement has a label on it if (currentStmt != firstUnit) { List<Unit> succs = unitGraph.getSuccsOf(currentStmt); if (succs.size() != 1 || succs.get(0) != currentStmt || unitGraph.getPredsOf(currentStmt).size() != 1 || up.labels().containsKey(currentStmt)) { up.newline(); } } if (up.labels().containsKey(currentStmt)) { up.unitRef(currentStmt, true); up.literal(":"); up.newline(); } if (up.references().containsKey(currentStmt)) { up.unitRef(currentStmt, false); } } up.startUnit(currentStmt); currentStmt.toString(up); up.endUnit(currentStmt); up.literal(";"); up.newline(); // only print them if not generating attributes files // because they mess up line number // if (!addJimpleLn()) { if (Options.v().print_tags_in_output()) { for (Tag t : currentStmt.getTags()) { up.noIndent(); up.literal("/*"); up.literal(t.toString()); up.literal("*/"); up.newline(); } // for (ValueBox temp : currentStmt.getUseAndDefBoxes()) { // for (Tag t : temp.getTags()) { // up.noIndent(); // up.literal("VB Tag: " + t.toString()); // up.newline(); // } // } } } out.print(up.toString()); if (addJimpleLn()) { setJimpleLnNum(up.getPositionTagger().getEndLn()); } // Print out exceptions { Iterator<Trap> trapIt = body.getTraps().iterator(); if (trapIt.hasNext()) { out.println(); incJimpleLnNum(); do { // condition already checked Trap trap = trapIt.next(); Map<Unit, String> lbls = up.labels(); out.println(" catch " + printSignature(trap.getException()) + " from " + lbls.get(trap.getBeginUnit()) + " to " + lbls.get(trap.getEndUnit()) + " with " + lbls.get(trap.getHandlerUnit()) + ";"); incJimpleLnNum(); } while (trapIt.hasNext()); } } } private int addJimpleLnTags(int lnNum, Host h) { h.addTag(new JimpleLineNumberTag(lnNum)); return lnNum + 1; } /** * Prints the Locals in the given <code>JimpleBody</code> to the specified <code>PrintWriter</code>. */ private void printLocalsInBody(Body body, UnitPrinter up) { Map<Type, List<Local>> typeToLocals = new DeterministicHashMap<Type, List<Local>>(body.getLocalCount() * 2 + 1, 0.7f); // Collect locals for (Local local : body.getLocals()) { Type t = local.getType(); List<Local> localList = typeToLocals.get(t); if (localList == null) { typeToLocals.put(t, localList = new ArrayList<Local>()); } localList.add(local); } // Print locals for (Map.Entry<Type, List<Local>> e : typeToLocals.entrySet()) { up.type(e.getKey()); up.literal(" "); for (Iterator<Local> it = e.getValue().iterator(); it.hasNext();) { Local l = it.next(); up.local(l); if (it.hasNext()) { up.literal(", "); } } up.literal(";"); up.newline(); } if (!typeToLocals.isEmpty()) { up.newline(); } } }
11,987
28.820896
123
java
soot
soot-master/src/main/java/soot/RadioScenePack.java
package soot; /*- * #%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.LinkedList; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A wrapper object for a pack of optimizations. Provides chain-like operations, except that the key is the phase name. */ public class RadioScenePack extends ScenePack { private static final Logger logger = LoggerFactory.getLogger(RadioScenePack.class); public RadioScenePack(String name) { super(name); } @Override protected void internalApply() { LinkedList<Transform> enabled = new LinkedList<Transform>(); for (Transform t : this) { Map<String, String> opts = PhaseOptions.v().getPhaseOptions(t); if (PhaseOptions.getBoolean(opts, "enabled")) { enabled.add(t); } } if (enabled.isEmpty()) { logger.debug("Exactly one phase in the pack " + getPhaseName() + " must be enabled. Currently, none of them are."); throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED); } if (enabled.size() > 1) { logger .debug("Only one phase in the pack " + getPhaseName() + " may be enabled. The following are enabled currently: "); for (Transform t : enabled) { logger.debug(" " + t.getPhaseName()); } throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED); } for (Transform t : enabled) { t.apply(); } } @Override public void add(Transform t) { super.add(t); checkEnabled(t); } @Override public void insertAfter(Transform t, String phaseName) { super.insertAfter(t, phaseName); checkEnabled(t); } @Override public void insertBefore(Transform t, String phaseName) { super.insertBefore(t, phaseName); checkEnabled(t); } private void checkEnabled(Transform t) { Map<String, String> options = PhaseOptions.v().getPhaseOptions(t); if (PhaseOptions.getBoolean(options, "enabled")) { // Enabling this one will disable all the others PhaseOptions.v().setPhaseOption(t, "enabled:true"); } } }
2,870
29.542553
124
java
soot
soot-master/src/main/java/soot/RefLikeType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Abstract class for Soot classes that model subtypes of java.lang.Object (ie. object references and arrays) * * @author Ondrej Lhotak */ @SuppressWarnings("serial") public abstract class RefLikeType extends Type { /** * If I have a variable x of declared type t, what is a good declared type for the expression ((Object[]) x)[i]? The * getArrayElementType() method in RefLikeType was introduced even later to answer this question for all classes * implementing RefLikeType. If t is an array, then the answer is the same as getElementType(). But t could also be Object, * Serializable, or Cloneable, which can all hold any array, so then the answer is Object. */ public abstract Type getArrayElementType(); }
1,550
36.829268
125
java
soot
soot-master/src/main/java/soot/RefType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import com.google.common.base.Optional; import java.util.ArrayDeque; import soot.util.Switch; /** * A class that models Java's reference types. RefTypes are parameterized by a class name. Two RefType are equal iff they are * parameterized by the same class name as a String. */ @SuppressWarnings("serial") public class RefType extends RefLikeType implements Comparable<RefType> { /** * the class name that parameterizes this RefType */ private String className; private AnySubType anySubType; protected volatile SootClass sootClass; public RefType(Singletons.Global g) { this.className = ""; } protected RefType(String className) { if (!className.isEmpty()) { if (className.charAt(0) == '[') { throw new RuntimeException("Attempt to create RefType whose name starts with [ --> " + className); } if (className.indexOf('/') >= 0) { throw new RuntimeException("Attempt to create RefType containing a / --> " + className); } if (className.indexOf(';') >= 0) { throw new RuntimeException("Attempt to create RefType containing a ; --> " + className); } } this.className = className; } public static RefType v() { if (ModuleUtil.module_mode()) { return G.v().soot_ModuleRefType(); } else { return G.v().soot_RefType(); } } /** * Create a RefType for a class. * * @param className * The name of the class used to parameterize the created RefType. * @return a RefType for the given class name. */ public static RefType v(String className) { if (ModuleUtil.module_mode()) { return ModuleRefType.v(className); } else { return Scene.v().getOrAddRefType(className); } } /** * Create a RefType for a class. * * @param c * A SootClass for which to create a RefType. * @return a RefType for the given SootClass.. */ public static RefType v(SootClass c) { if (ModuleUtil.module_mode()) { return ModuleRefType.v(c.getName(), Optional.fromNullable(c.moduleName)); } else { return v(c.getName()); } } public String getClassName() { return className; } @Override public int compareTo(RefType t) { return this.toString().compareTo(t.toString()); } /** * Get the SootClass object corresponding to this RefType. * * @return the corresponding SootClass */ public SootClass getSootClass() { if (sootClass == null) { // System.out.println( "wrning: "+this+" has no sootclass" ); sootClass = SootResolver.v().makeClassRef(className); } return sootClass; } public boolean hasSootClass() { return sootClass != null; } public void setClassName(String className) { this.className = className; } /** * Set the SootClass object corresponding to this RefType. * * @param sootClass * The SootClass corresponding to this RefType. */ public void setSootClass(SootClass sootClass) { this.sootClass = sootClass; } /** * Two RefTypes are considered equal if they are parameterized by the same class name String. * * @param t * an object to test for equality. @ return true if t is a RefType parameterized by the same name as this. */ @Override public boolean equals(Object t) { return ((t instanceof RefType) && className.equals(((RefType) t).className)); } @Override public String toString() { return className; } /** * Returns a textual representation, quoted as needed, of this type for serialization, e.g. to .jimple format */ @Override public String toQuotedString() { return Scene.v().quotedNameOf(className); } @Override public int hashCode() { return className.hashCode(); } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseRefType(this); } /** * Returns the least common superclass of this type and other. */ @Override public Type merge(Type other, Scene cm) { if (other.equals(UnknownType.v()) || this.equals(other)) { return this; } if (!(other instanceof RefType)) { throw new RuntimeException("illegal type merge: " + this + " and " + other); } { // Return least common superclass final SootClass javalangObject = cm.getObjectType().getSootClass(); ArrayDeque<SootClass> thisHierarchy = new ArrayDeque<>(); ArrayDeque<SootClass> otherHierarchy = new ArrayDeque<>(); // Build thisHierarchy // This should never be null, so we could also use "while // (true)"; but better be safe than sorry. for (SootClass sc = cm.getSootClass(this.className); sc != null;) { thisHierarchy.addFirst(sc); if (sc == javalangObject) { break; } sc = sc.getSuperclassUnsafe(); if (sc == null) { sc = javalangObject; } } // Build otherHierarchy // This should never be null, so we could also use "while // (true)"; but better be safe than sorry. for (SootClass sc = cm.getSootClass(((RefType) other).className); sc != null;) { otherHierarchy.addFirst(sc); if (sc == javalangObject) { break; } sc = sc.getSuperclassUnsafe(); if (sc == null) { sc = javalangObject; } } // Find least common superclass { SootClass commonClass = null; while (!otherHierarchy.isEmpty() && !thisHierarchy.isEmpty() && otherHierarchy.getFirst() == thisHierarchy.getFirst()) { commonClass = otherHierarchy.removeFirst(); thisHierarchy.removeFirst(); } if (commonClass == null) { throw new RuntimeException("Could not find a common superclass for " + this + " and " + other); } return commonClass.getType(); } } } @Override public Type getArrayElementType() { if ("java.lang.Object".equals(className) || "java.io.Serializable".equals(className) || "java.lang.Cloneable".equals(className)) { return RefType.v("java.lang.Object"); } throw new RuntimeException("Attempt to get array base type of a non-array"); } public AnySubType getAnySubType() { return anySubType; } public void setAnySubType(AnySubType anySubType) { this.anySubType = anySubType; } @Override public boolean isAllowedInFinalCode() { return true; } }
7,280
26.684411
125
java
soot
soot-master/src/main/java/soot/ResolutionFailedException.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Exception thrown when resolving a method or field reference fails. */ public class ResolutionFailedException extends RuntimeException { private static final long serialVersionUID = -5920478779446526550L; protected ResolutionFailedException(String message) { super(message); } }
1,111
29.888889
71
java
soot
soot-master/src/main/java/soot/Scene.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.MagicNumberFileFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pxb.android.axml.AxmlReader; import pxb.android.axml.AxmlVisitor; import pxb.android.axml.NodeVisitor; import soot.dexpler.DalvikThrowAnalysis; import soot.javaToJimple.DefaultLocalGenerator; import soot.jimple.spark.internal.ClientAccessibilityOracle; import soot.jimple.spark.internal.PublicAndProtectedAccessibility; import soot.jimple.spark.pag.SparkField; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.ContextSensitiveCallGraph; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.jimple.toolkits.pointer.DumbPointerAnalysis; import soot.jimple.toolkits.pointer.SideEffectAnalysis; import soot.jimple.toolkits.scalar.DefaultLocalCreation; import soot.jimple.toolkits.scalar.LocalCreation; import soot.options.CGOptions; import soot.options.Options; import soot.toolkits.exceptions.PedanticThrowAnalysis; import soot.toolkits.exceptions.ThrowAnalysis; import soot.toolkits.exceptions.UnitThrowAnalysis; import soot.util.ArrayNumberer; import soot.util.Chain; import soot.util.HashChain; import soot.util.IterableNumberer; import soot.util.MapNumberer; import soot.util.Numberer; import soot.util.StringNumberer; import soot.util.WeakMapNumberer; /** * Manages the SootClasses of the application being analyzed. */ public class Scene { private static final Logger logger = LoggerFactory.getLogger(Scene.class); private static final int defaultSdkVersion = 15; private static final Pattern arrayPattern = Pattern.compile("([^\\[\\]]*)(.*)"); protected final Map<String, RefType> nameToClass = new ConcurrentHashMap<String, RefType>(); protected final ArrayNumberer<Kind> kindNumberer = new ArrayNumberer<Kind>( new Kind[] { Kind.INVALID, Kind.STATIC, Kind.VIRTUAL, Kind.INTERFACE, Kind.SPECIAL, Kind.CLINIT, Kind.THREAD, Kind.EXECUTOR, Kind.ASYNCTASK, Kind.FINALIZE, Kind.INVOKE_FINALIZE, Kind.PRIVILEGED, Kind.NEWINSTANCE }); protected final Set<String> reservedNames = new HashSet<String>(); @SuppressWarnings("unchecked") protected final Set<String>[] basicclasses = new Set[4]; protected Chain<SootClass> classes = new HashChain<SootClass>(); protected Chain<SootClass> applicationClasses = new HashChain<SootClass>(); protected Chain<SootClass> libraryClasses = new HashChain<SootClass>(); protected Chain<SootClass> phantomClasses = new HashChain<SootClass>(); protected IterableNumberer<Type> typeNumberer = new ArrayNumberer<Type>(); protected Numberer<Unit> unitNumberer = new MapNumberer<Unit>(); protected StringNumberer subSigNumberer = new StringNumberer(); protected IterableNumberer<SootClass> classNumberer; protected Numberer<SparkField> fieldNumberer; protected IterableNumberer<SootMethod> methodNumberer; protected IterableNumberer<Local> localNumberer; protected Numberer<Context> contextNumberer; protected Hierarchy activeHierarchy; protected FastHierarchy activeFastHierarchy; protected SideEffectAnalysis activeSideEffectAnalysis; protected PointsToAnalysis activePointsToAnalysis; protected CallGraph activeCallGraph; protected ReachableMethods reachableMethods; protected List<SootMethod> entryPoints; protected ContextSensitiveCallGraph cscg; protected ClientAccessibilityOracle accessibilityOracle; protected String sootClassPath; protected List<SootClass> dynamicClasses; protected LinkedList<String> excludedPackages; protected boolean allowsPhantomRefs = false; protected SootClass mainClass; protected boolean incrementalBuild = false; protected boolean doneResolving = false; // Two default values for constructing ExceptionalUnitGraphs: private ThrowAnalysis defaultThrowAnalysis; private List<String> pkgList; private int stateCount = 0; private final Map<String, Integer> maxAPIs = new HashMap<String, Integer>(); private AndroidVersionInfo androidSDKVersionInfo; private int androidAPIVersion = -1; public Scene(Singletons.Global g) { setReservedNames(); // load soot.class.path system property, if defined String scp = System.getProperty("soot.class.path"); if (scp != null) { setSootClassPath(scp); } if (Options.v().weak_map_structures()) { this.classNumberer = new WeakMapNumberer<SootClass>(); this.fieldNumberer = new WeakMapNumberer<SparkField>(); this.methodNumberer = new WeakMapNumberer<SootMethod>(); this.localNumberer = new WeakMapNumberer<Local>(); } else { this.classNumberer = new ArrayNumberer<SootClass>(); this.fieldNumberer = new ArrayNumberer<SparkField>(); this.methodNumberer = new ArrayNumberer<SootMethod>(); this.localNumberer = new ArrayNumberer<Local>(); } addSootBasicClasses(); determineExcludedPackages(); } public static Scene v() { if (ModuleUtil.module_mode()) { return G.v().soot_ModuleScene(); } else { return G.v().soot_Scene(); } } private void determineExcludedPackages() { final Options options = Options.v(); LinkedList<String> excludedPackages; { List<String> exclude = options.exclude(); if (exclude == null) { excludedPackages = new LinkedList<String>(); } else { excludedPackages = new LinkedList<String>(exclude); } } // do not kill contents of the APK if we want a working new APK afterwards if (!options.include_all()) { int fmt = options.output_format(); if (fmt != Options.output_format_dex && fmt != Options.output_format_force_dex) { excludedPackages.add("java.*"); excludedPackages.add("sun.*"); excludedPackages.add("javax.*"); excludedPackages.add("com.sun.*"); excludedPackages.add("com.ibm.*"); excludedPackages.add("org.xml.*"); excludedPackages.add("org.w3c.*"); excludedPackages.add("apple.awt.*"); excludedPackages.add("com.apple.*"); } } this.excludedPackages = excludedPackages; } public void setMainClass(SootClass m) { mainClass = m; if (!m.declaresMethod(getSubSigNumberer().findOrAdd("void main(java.lang.String[])"))) { throw new RuntimeException("Main-class has no main method!"); } } /** * Returns a set of tokens which are reserved. Any field, class, method, or local variable with such a name will be quoted. */ public Set<String> getReservedNames() { return reservedNames; } /** * If this name is in the set of reserved names, then return a quoted version of it. Else pass it through. If the name * consists of multiple parts separated by dots, the individual names are checked as well. */ public String quotedNameOf(String s) { // Pre-check: Is there a chance that we need to escape something? // If not, skip the transformation altogether. boolean found = s.indexOf('-') > -1; if (!found) { for (String token : reservedNames) { if (s.contains(token)) { found = true; break; } } } if (!found) { return s; } StringBuilder res = new StringBuilder(s.length()); for (String part : s.split("\\.")) { if (res.length() > 0) { res.append('.'); } if ((!part.isEmpty() && part.charAt(0) == '-') || reservedNames.contains(part)) { res.append('\'').append(part).append('\''); } else { res.append(part); } } return res.toString(); } /** * This method is the inverse of quotedNameOf(). It takes a possible escaped class and reconstructs the original version of * it. * * @param s * The possibly escaped name * @return The original, non-escaped name */ public static String unescapeName(String s) { // If the name is not escaped, there is nothing to do here if (s.indexOf('\'') < 0) { return s; } StringBuilder res = new StringBuilder(s.length()); for (String part : s.split("\\.")) { if (res.length() > 0) { res.append('.'); } int len = part.length(); if (len > 1 && part.charAt(0) == '\'' && part.charAt(len - 1) == '\'') { res.append(part.substring(1, len - 1)); } else { res.append(part); } } return res.toString(); } public boolean hasMainClass() { if (mainClass == null) { setMainClassFromOptions(); } return mainClass != null; } public SootClass getMainClass() { if (!hasMainClass()) { throw new RuntimeException("There is no main class set!"); } return mainClass; } public SootMethod getMainMethod() { if (!hasMainClass()) { throw new RuntimeException("There is no main class set!"); } SootMethod mainMethod = mainClass.getMethodUnsafe("main", Collections.singletonList(ArrayType.v(RefType.v("java.lang.String"), 1)), VoidType.v()); if (mainMethod == null) { throw new RuntimeException("Main class declares no main method!"); } return mainMethod; } public void setSootClassPath(String p) { sootClassPath = p; SourceLocator.v().invalidateClassPath(); } public void extendSootClassPath(String newPathElement) { sootClassPath += File.pathSeparatorChar + newPathElement; SourceLocator.v().extendClassPath(newPathElement); } public String getSootClassPath() { if (sootClassPath == null) { // First, check Options for a classpath String cp = Options.v().soot_classpath(); // If no classpath is given via Options, just use the default. // Otherwise, if the prepend flag is set, append the default. if (cp == null || cp.isEmpty()) { cp = defaultClassPath(); } else if (Options.v().prepend_classpath()) { cp += File.pathSeparatorChar + defaultClassPath(); } List<String> dirs = new LinkedList<String>(); dirs.addAll(Options.v().process_dir()); // Add process-jar-dirs List<String> jarDirs = Options.v().process_jar_dir(); if (!jarDirs.isEmpty()) { for (String jarDirName : jarDirs) { File jarDir = new File(jarDirName); File[] contents = jarDir.listFiles(); for (File f : contents) { if (f.getAbsolutePath().endsWith(".jar")) { dirs.add(f.getAbsolutePath()); } } } } // Add process-dirs (if applicable) if (!dirs.isEmpty()) { StringBuilder pds = new StringBuilder(); for (String path : dirs) { if (!cp.contains(path)) { pds.append(path).append(File.pathSeparatorChar); } } cp = pds.append(cp).toString(); } // Set the new classpath sootClassPath = cp; } return sootClassPath; } /** * Returns the max Android API version number available in directory 'dir' * * @param dir * @return */ private int getMaxAPIAvailable(String dir) { Integer mapi = this.maxAPIs.get(dir); if (mapi != null) { return mapi; } File d = new File(dir); if (!d.exists()) { throw new AndroidPlatformException( String.format("The Android platform directory you have specified (%s) does not exist. Please check.", dir)); } File[] files = d.listFiles(); if (files == null) { return -1; } int maxApi = -1; for (File f : files) { String name = f.getName(); if (f.isDirectory() && name.startsWith("android-")) { try { int v = Integer.decode(name.split("android-")[1]); if (v > maxApi) { maxApi = v; } } catch (NumberFormatException ex) { // We simply ignore directories that do not follow the // Android naming structure } } } this.maxAPIs.put(dir, maxApi); return maxApi; } public String getAndroidJarPath(String jars, String apk) { int APIVersion = getAndroidAPIVersion(jars, apk); String jarPath = jars + File.separatorChar + "android-" + APIVersion + File.separatorChar + "android.jar"; // check that jar exists File f = new File(jarPath); if (!f.isFile()) { throw new AndroidPlatformException(String.format("error: target android.jar %s does not exist.", jarPath)); } return jarPath; } public int getAndroidAPIVersion() { return androidAPIVersion > 0 ? androidAPIVersion : (Options.v().android_api_version() > 0 ? Options.v().android_api_version() : defaultSdkVersion); } private int getAndroidAPIVersion(String jars, String apk) { // Do we already have an API version? if (androidAPIVersion > 0) { return androidAPIVersion; } // get path to appropriate android.jar File jarsF = new File(jars); if (!jarsF.exists()) { throw new AndroidPlatformException( String.format("Android platform directory '%s' does not exist!", jarsF.getAbsolutePath())); } if (apk != null && !(new File(apk)).exists()) { throw new RuntimeException("file '" + apk + "' does not exist!"); } // Use the default if we don't have any other information androidAPIVersion = defaultSdkVersion; // Do we have an explicit API version? if (Options.v().android_api_version() > 0) { androidAPIVersion = Options.v().android_api_version(); } else if (apk != null) { if (apk.toLowerCase().endsWith(".apk")) { androidAPIVersion = getTargetSDKVersion(apk, jars); } } // If we don't have that API version installed, we take the most recent one we have final int maxAPI = getMaxAPIAvailable(jars); if (maxAPI > 0 && androidAPIVersion > maxAPI) { androidAPIVersion = maxAPI; } // If the platform version is missing in the middle, we take the next one while (androidAPIVersion < maxAPI) { String jarPath = jars + File.separatorChar + "android-" + androidAPIVersion + File.separatorChar + "android.jar"; if (new File(jarPath).exists()) { break; } androidAPIVersion++; } return androidAPIVersion; } public static class AndroidVersionInfo { public int sdkTargetVersion = -1; public int minSdkVersion = -1; public int platformBuildVersionCode = -1; private static AndroidVersionInfo get(InputStream manifestIS) { final AndroidVersionInfo versionInfo = new AndroidVersionInfo(); final AxmlVisitor axmlVisitor = new AxmlVisitor() { private String nodeName = null; @Override public void attr(String ns, String name, int resourceId, int type, Object obj) { super.attr(ns, name, resourceId, type, obj); if (nodeName != null && name != null) { if (nodeName.equals("manifest")) { if (name.equals("platformBuildVersionCode")) { versionInfo.platformBuildVersionCode = Integer.valueOf("" + obj); } } else if (nodeName.equals("uses-sdk")) { // Obfuscated APKs often remove the attribute names and use the resourceId instead // Therefore it is better to check for both variants if (name.equals("targetSdkVersion") || (name.isEmpty() && resourceId == 16843376)) { versionInfo.sdkTargetVersion = Integer.valueOf(String.valueOf(obj)); } else if (name.equals("minSdkVersion") || (name.isEmpty() && resourceId == 16843276)) { versionInfo.minSdkVersion = Integer.valueOf(String.valueOf(obj)); } } } } @Override public NodeVisitor child(String ns, String name) { nodeName = name; return this; } }; try { AxmlReader xmlReader = new AxmlReader(IOUtils.toByteArray(manifestIS)); xmlReader.accept(axmlVisitor); } catch (Exception e) { logger.error(e.getMessage(), e); } return versionInfo; } } private int getTargetSDKVersion(String apkFile, String platformJARs) { // get AndroidManifest ZipFile archive = null; try { InputStream manifestIS = null; try { archive = new ZipFile(apkFile); for (Enumeration<? extends ZipEntry> entries = archive.entries(); entries.hasMoreElements();) { ZipEntry entry = entries.nextElement(); // We are dealing with the Android manifest if ("AndroidManifest.xml".equals(entry.getName())) { manifestIS = archive.getInputStream(entry); break; } } } catch (Exception e) { throw new RuntimeException("Error when looking for manifest in apk: " + e); } if (manifestIS == null) { logger.debug("Could not find sdk version in Android manifest! Using default: " + defaultSdkVersion); return defaultSdkVersion; } // process AndroidManifest.xml androidSDKVersionInfo = AndroidVersionInfo.get(manifestIS); } finally { if (archive != null) { try { archive.close(); } catch (IOException e) { throw new RuntimeException("Error when looking for manifest in apk: " + e); } } } int maxAPI = getMaxAPIAvailable(platformJARs); int APIVersion = -1; if (androidSDKVersionInfo.sdkTargetVersion != -1) { if (androidSDKVersionInfo.sdkTargetVersion > maxAPI && androidSDKVersionInfo.minSdkVersion != -1 && androidSDKVersionInfo.minSdkVersion <= maxAPI) { logger.warn("Android API version '" + androidSDKVersionInfo.sdkTargetVersion + "' not available, using minApkVersion '" + androidSDKVersionInfo.minSdkVersion + "' instead"); APIVersion = androidSDKVersionInfo.minSdkVersion; } else { APIVersion = androidSDKVersionInfo.sdkTargetVersion; } } else if (androidSDKVersionInfo.platformBuildVersionCode != -1) { if (androidSDKVersionInfo.platformBuildVersionCode > maxAPI && androidSDKVersionInfo.minSdkVersion != -1 && androidSDKVersionInfo.minSdkVersion <= maxAPI) { logger.warn("Android API version '" + androidSDKVersionInfo.platformBuildVersionCode + "' not available, using minApkVersion '" + androidSDKVersionInfo.minSdkVersion + "' instead"); APIVersion = androidSDKVersionInfo.minSdkVersion; } else { APIVersion = androidSDKVersionInfo.platformBuildVersionCode; } } else if (androidSDKVersionInfo.minSdkVersion != -1) { APIVersion = androidSDKVersionInfo.minSdkVersion; } else { logger.debug("Could not find sdk version in Android manifest! Using default: " + defaultSdkVersion); APIVersion = defaultSdkVersion; } if (APIVersion <= 2) { APIVersion = 3; } return APIVersion; } public AndroidVersionInfo getAndroidSDKVersionInfo() { return androidSDKVersionInfo; } public String defaultClassPath() { if (Options.v().src_prec() != Options.src_prec_apk) { // If we have an apk file on the process dir and do not have a src-prec // option that loads APK files, we give a warning for (String entry : Options.v().process_dir()) { if (entry.toLowerCase().endsWith(".apk")) { System.err.println("APK file on process dir, but chosen src-prec does not support loading APKs"); break; } } String path = defaultJavaClassPath(); if (path == null) { throw new RuntimeException("Error: cannot find rt.jar."); } return path; } else { return defaultAndroidClassPath(); } } private String defaultAndroidClassPath() { // check that android.jar is not in classpath String androidJars = Options.v().android_jars(); String forceAndroidJar = Options.v().force_android_jar(); if ((androidJars == null || androidJars.isEmpty()) && (forceAndroidJar == null || forceAndroidJar.isEmpty())) { throw new RuntimeException("You are analyzing an Android application but did " + "not define android.jar. Options -android-jars or -force-android-jar should be used."); } // Get the platform JAR file. It either directly specified, or // we detect it from the target version of the APK we are // analyzing String jarPath = ""; if (forceAndroidJar != null && !forceAndroidJar.isEmpty()) { jarPath = forceAndroidJar; if (Options.v().android_api_version() > 0) { androidAPIVersion = Options.v().android_api_version(); } else if (forceAndroidJar.contains("android-")) { Pattern pt = Pattern.compile("\\" + File.separatorChar + "android-(\\d+)" + "\\" + File.separatorChar); Matcher m = pt.matcher(forceAndroidJar); if (m.find()) { androidAPIVersion = Integer.valueOf(m.group(1)); } } else { androidAPIVersion = defaultSdkVersion; } } else if (androidJars != null && !androidJars.isEmpty()) { List<String> classPathEntries = new ArrayList<String>(Arrays.asList(Options.v().soot_classpath().split(File.pathSeparator))); classPathEntries.addAll(Options.v().process_dir()); String targetApk = ""; Set<String> targetDexs = new HashSet<String>(); for (String entry : classPathEntries) { if (isApk(new File(entry))) { if (targetApk != null && !targetApk.isEmpty()) { throw new RuntimeException("only one Android application can be analyzed when using option -android-jars."); } targetApk = entry; } if (entry.toLowerCase().endsWith(".dex")) { // names are case-insensitive targetDexs.add(entry); } } // We need at least one file to process if (targetApk == null || targetApk.isEmpty()) { if (targetDexs.isEmpty()) { throw new RuntimeException("no apk file given"); } jarPath = getAndroidJarPath(androidJars, null); } else { jarPath = getAndroidJarPath(androidJars, targetApk); } } // We must have a platform JAR file when analyzing Android apps if (jarPath.isEmpty()) { throw new RuntimeException("android.jar not found."); } // Check the platform JAR file File f = new File(jarPath); if (!f.exists()) { throw new RuntimeException("file '" + jarPath + "' does not exist!"); } else { logger.debug("Using '" + jarPath + "' as android.jar"); } return jarPath; } public static boolean isApk(File apk) { // first check magic number // Note that there are multiple magic numbers for different versions of ZIP files, but all of them // have "PK" at the beginning. In order to not decline possible future versions of ZIP files which // may be supported by the JVM, we only check these two bytes. MagicNumberFileFilter apkFilter = new MagicNumberFileFilter(new byte[] { (byte) 0x50, (byte) 0x4B }); if (!apkFilter.accept(apk)) { return false; } // second check if contains dex file. try (ZipFile zf = new ZipFile(apk)) { for (Enumeration<? extends ZipEntry> en = zf.entries(); en.hasMoreElements();) { ZipEntry z = en.nextElement(); if ("classes.dex".equals(z.getName())) { return true; } } } catch (IOException e) { logger.error(e.getMessage(), e); } return false; } /** * Checks if the version number indicates a Java version >= 9 in order to handle the new virtual filesystem jrt:/ * * @param version * @return */ public static boolean isJavaGEQ9(String version) { try { // We may have versions such as "14-ea" int idx = version.indexOf('-'); if (idx > 0) { version = version.substring(0, idx); } String[] elements = version.split("\\."); // string has the form 9.x.x.... Integer firstVersionDigest = Integer.valueOf(elements[0]); if (firstVersionDigest >= 9) { return true; } if (firstVersionDigest == 1 && elements.length > 1) { // string has the form 1.9.x.xxx return Integer.valueOf(elements[1]) >= 9; } else { throw new IllegalArgumentException(String.format("Unknown Version number schema %s", version)); } } catch (NumberFormatException ex) { throw new IllegalArgumentException(String.format("Unknown Version number schema %s", version), ex); } } /** * Returns the default class path used for this JVM. * * @return the default class path (or null if none could be found) */ public static String defaultJavaClassPath() { final String javaHome = System.getProperty("java.home"); StringBuilder sb = new StringBuilder(); if ("Mac OS X".equals(System.getProperty("os.name"))) { // in older Mac OS X versions, rt.jar was split into classes.jar and // ui.jar String prefix = javaHome + File.separatorChar + ".." + File.separatorChar + "Classes" + File.separatorChar; File classesJar = new File(prefix + "classes.jar"); if (classesJar.exists()) { sb.append(classesJar.getAbsolutePath()).append(File.pathSeparatorChar); } File uiJar = new File(prefix + "ui.jar"); if (uiJar.exists()) { sb.append(uiJar.getAbsolutePath()).append(File.pathSeparatorChar); } } // behavior for Java versions >=9, which do not have a rt.jar file final boolean javaGEQ9 = isJavaGEQ9(System.getProperty("java.version")); if (javaGEQ9) { sb.append(ModulePathSourceLocator.DUMMY_CLASSPATH_JDK9_FS); // this is a new basic class in java >= 9 that needs to be laoded Scene.v().addBasicClass("java.lang.invoke.StringConcatFactory"); } else { File rtJar = new File(javaHome + File.separatorChar + "lib" + File.separatorChar + "rt.jar"); if (rtJar.exists() && rtJar.isFile()) { // logger.debug("Using JRE runtime: " + rtJar.getAbsolutePath()); sb.append(rtJar.getAbsolutePath()); } else { // in case we're not in JRE environment, try JDK rtJar = new File(javaHome + File.separatorChar + "jre" + File.separatorChar + "lib" + File.separatorChar + "rt.jar"); if (rtJar.exists() && rtJar.isFile()) { // logger.debug("Using JDK runtime: " + rtJar.getAbsolutePath()); sb.append(rtJar.getAbsolutePath()); } else { // not in JDK either return null; } } } if (!javaGEQ9 && (Options.v().whole_program() || Options.v().whole_shimple() || Options.v().output_format() == Options.output_format_dava)) { // add jce.jar, which is necessary for whole program mode // (java.security.Signature from rt.jar imports javax.crypto.Cipher from jce.jar) sb.append(File.pathSeparatorChar).append(javaHome).append(File.separatorChar).append("lib").append(File.separatorChar) .append("jce.jar"); } return sb.toString(); } public int getState() { return this.stateCount; } protected synchronized void modifyHierarchy() { this.stateCount++; this.activeHierarchy = null; this.activeFastHierarchy = null; this.activeSideEffectAnalysis = null; this.activePointsToAnalysis = null; } /** * Adds the given class to the Scene. This method marks the given class as a library class and invalidates the class * hierarchy. * * @param c * The class to add */ public void addClass(SootClass c) { addClassSilent(c); c.setLibraryClass(); modifyHierarchy(); } /** * Adds the given class to the Scene. This method does not handle any dependencies such as invalidating the hierarchy. The * class is neither marked as application class, nor library class. * * @param c * The class to add */ protected void addClassSilent(SootClass c) { synchronized (c) { if (c.isInScene()) { throw new RuntimeException("already managed: " + c.getName()); } if (containsClass(c.getName())) { throw new RuntimeException("duplicate class: " + c.getName()); } classes.add(c); c.getType().setSootClass(c); c.setInScene(true); // Phantom classes are not really part of the hierarchy anyway, so // we can keep the old one if (!c.isPhantom) { modifyHierarchy(); } nameToClass.computeIfAbsent(c.getName(), k -> c.getType()); } } public void removeClass(SootClass c) { if (!c.isInScene()) { throw new RuntimeException(); } classes.remove(c); if (c.isLibraryClass()) { libraryClasses.remove(c); } else if (c.isPhantomClass()) { phantomClasses.remove(c); } else if (c.isApplicationClass()) { applicationClasses.remove(c); } c.getType().setSootClass(null); c.setInScene(false); modifyHierarchy(); } public boolean containsClass(String className) { RefType type = nameToClass.get(className); return type != null && type.hasSootClass() && type.getSootClass().isInScene(); } public boolean containsType(String className) { return nameToClass.containsKey(className); } private static int signatureSeparatorIndex(String sig) { int len = sig.length(); if (len < 3 || sig.charAt(0) != '<' || sig.charAt(len - 1) != '>') { throw new RuntimeException("oops " + sig); } int index = sig.indexOf(':'); if (index < 0) { throw new RuntimeException("oops " + sig); } return index; } private static String sepIndexToClass(String sig, int index) { // Must unescape the class name from a signature because the // Scene does not contain the escaped versions of the classes. return unescapeName(sig.substring(1, index)); } private static String sepIndexToSubsignature(String sig, int index) { return sig.substring(index + 2, sig.length() - 1); } public static String signatureToClass(String sig) { return sepIndexToClass(sig, signatureSeparatorIndex(sig)); } public static String signatureToSubsignature(String sig) { return sepIndexToSubsignature(sig, signatureSeparatorIndex(sig)); } public SootField grabField(String fieldSignature) { int index = signatureSeparatorIndex(fieldSignature); String cname = sepIndexToClass(fieldSignature, index); if (!containsClass(cname)) { return null; } String fname = sepIndexToSubsignature(fieldSignature, index); return getSootClass(cname).getFieldUnsafe(fname); } public boolean containsField(String fieldSignature) { return grabField(fieldSignature) != null; } public SootMethod grabMethod(String methodSignature) { int index = signatureSeparatorIndex(methodSignature); String cname = sepIndexToClass(methodSignature, index); if (!containsClass(cname)) { return null; } String mname = sepIndexToSubsignature(methodSignature, index); return getSootClass(cname).getMethodUnsafe(mname); } public boolean containsMethod(String methodSignature) { return grabMethod(methodSignature) != null; } public SootField getField(String fieldSignature) { SootField f = grabField(fieldSignature); if (f != null) { return f; } throw new RuntimeException("tried to get nonexistent field " + fieldSignature); } public SootMethod getMethod(String methodSignature) { SootMethod m = grabMethod(methodSignature); if (m != null) { return m; } throw new RuntimeException("tried to get nonexistent method " + methodSignature); } /** * Attempts to load the given class and all of the required support classes. Returns the original class if it was loaded, * or null otherwise. */ public SootClass tryLoadClass(String className, int desiredLevel) { /* * if(Options.v().time()) Main.v().resolveTimer.start(); */ setPhantomRefs(true); ClassSource source = SourceLocator.v().getClassSource(className); try { if (!getPhantomRefs() && source == null) { setPhantomRefs(false); return null; } } finally { if (source != null) { source.close(); } } SootClass toReturn = SootResolver.v().resolveClass(className, desiredLevel); setPhantomRefs(false); return toReturn; /* * if(Options.v().time()) Main.v().resolveTimer.end(); */ } /** Loads the given class and all of the required support classes. Returns the first class. */ public SootClass loadClassAndSupport(String className) { SootClass ret = loadClass(className, SootClass.SIGNATURES); if (!ret.isPhantom()) { ret = loadClass(className, SootClass.BODIES); } return ret; } public SootClass loadClass(String className, int desiredLevel) { /* * if(Options.v().time()) Main.v().resolveTimer.start(); */ setPhantomRefs(true); SootClass toReturn = SootResolver.v().resolveClass(className, desiredLevel); setPhantomRefs(false); return toReturn; /* * if(Options.v().time()) Main.v().resolveTimer.end(); */ } /** * Returns the RefType with the given class name or primitive type. * * @throws RuntimeException * if the Type for this name cannot be found. Use {@link #getRefTypeUnsafe(String)} to check if type is an * registered RefType. */ public Type getType(String arg) { Type t = getTypeUnsafe(arg, false); // Set to false to preserve the original functionality just in case if (t == null) { throw new RuntimeException("Unknown Type: '" + t + "'"); } return t; } /** * Returns a Type object representing the given type string. It will first attempt to resolve the type as a reference type * that currently exists in the Scene. If this fails it will attempt to resolve the type as a java primitive type. Lastly, * if phantom refs are allowed it will construct a phantom class for the given type and return a reference type based on * the phantom class. Otherwise, this method will return null. Note, if the resolved base type is not null and the string * representation of the type is an array, the returned type will be an ArrayType with the base type resolved as described * above. * * @param arg * A string description of the type * @return The Type if it can be resolved and null otherwise */ public Type getTypeUnsafe(String arg) { return getTypeUnsafe(arg, true); } /** * Returns a Type object representing the given type string. It will first attempt to resolve the type as a reference type * that currently exists in the Scene. If this fails it will attempt to resolve the type as a java primitive type. Lastly, * if phantom refs are allowed and phantomNonExist=true it will construct a phantom class for the given type and return a * reference type based on the phantom class. Otherwise, this method will return null. Note, if the resolved base type is * not null and the string representation of the type is an array, the returned type will be an ArrayType with the base * type resolved as described above. * * @param arg * A string description of the type * @param phantomNonExist * Indicates that a phantom class should be created for the given type string and a Type object should be created * based on the phantom class if a class matching the type name does not exists in the scene and phantom refs are * allowed * @return The Type if it can be resolved and null otherwise */ public Type getTypeUnsafe(String arg, boolean phantomNonExist) { String type = arg; int arrayCount = -1; if (arg.contains("[")) { Matcher m = arrayPattern.matcher(arg); if (m.matches()) { type = m.group(1); arrayCount = m.group(2).length() / 2; } } Type result = getRefTypeUnsafe(type); if (result == null) { switch (type) { case "long": result = LongType.v(); break; case "short": result = ShortType.v(); break; case "double": result = DoubleType.v(); break; case "int": result = IntType.v(); break; case "float": result = FloatType.v(); break; case "byte": result = ByteType.v(); break; case "char": result = CharType.v(); break; case "void": result = VoidType.v(); break; case "boolean": result = BooleanType.v(); break; default: if (phantomNonExist && allowsPhantomRefs()) { getSootClassUnsafe(type, phantomNonExist); result = getRefTypeUnsafe(type); } break; } } if (result != null && arrayCount > 0) { result = ArrayType.v(result, arrayCount); } return result; } /** * Returns the RefType with the given className. * * @throws IllegalStateException * if the RefType for this class cannot be found. Use {@link #containsType(String)} to check if type is * registered */ public RefType getRefType(String className) { RefType refType = getRefTypeUnsafe(className); if (refType == null) { throw new IllegalStateException("RefType " + className + " not loaded. " + "If you tried to get the RefType of a library class, did you call loadNecessaryClasses()? " + "Otherwise please check Soot's classpath."); } return refType; } /** * Returns the RefType with the given className. Returns null if no type with the given name can be found. */ public RefType getRefTypeUnsafe(String className) { return nameToClass.get(className); } /** Returns the {@link RefType} for {@link Object}. */ public RefType getObjectType() { return getRefType("java.lang.Object"); } /** * Returns the SootClass with the given className. If no class with the given name exists, null is returned unless phantom * refs are allowed. In this case, a new phantom class is created. * * The difference with the getSootClass() version is that this version doesn't throw a RuntimeException if the requested * class doesn't exist in the Scene. Instead it returns null. * * @param className * The name of the class to get * @return The class if it exists, otherwise null */ public SootClass getSootClassUnsafe(String className) { return getSootClassUnsafe(className, true); } /** * Returns the SootClass with the given className. If no class with the given name exists, null is returned unless * phantomNonExist=true and phantom refs are allowed. In this case, a new phantom class is created and returned. * * The difference with the getSootClass() version is that this version doesn't throw a RuntimeException if the requested * class doesn't exist in the Scene. Instead it returns null or a phantom class, depending on the flag. * * @param className * The name of the class to get * @param phantomNonExist * Indicates that a phantom class should be created if a class with the given name does not exist and phantom refs * are allowed * * @return The class if it exists, otherwise null */ public SootClass getSootClassUnsafe(String className, boolean phantomNonExist) { RefType type = nameToClass.get(className); if (type != null) { synchronized (type) { if (type.hasSootClass() || !SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME.equals(className)) { SootClass tsc = type.getSootClass(); if (tsc != null) { return tsc; } } } } if ((phantomNonExist && allowsPhantomRefs()) || SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME.equals(className)) { type = getOrAddRefType(className); synchronized (type) { if (type.hasSootClass()) { return type.getSootClass(); } SootClass c = new SootClass(className); c.isPhantom = true; addClassSilent(c); c.setPhantomClass(); return c; } } return null; } /** * Returns the SootClass with the given className. * * @param className * The name of the class to get; throws RuntimeException if this class does not exist. */ public SootClass getSootClass(String className) { SootClass sc = getSootClassUnsafe(className); if (sc != null) { return sc; } throw new RuntimeException(System.lineSeparator() + "Aborting: can't find classfile " + className); } /** Returns an backed chain of the classes in this manager. */ public Chain<SootClass> getClasses() { return classes; } /* The four following chains are mutually disjoint. */ /** * Returns a chain of the application classes in this scene. These classes are the ones which can be freely analysed & * modified. */ public Chain<SootClass> getApplicationClasses() { return applicationClasses; } /** * Returns a chain of the library classes in this scene. These classes can be analysed but not modified. */ public Chain<SootClass> getLibraryClasses() { return libraryClasses; } /** * Returns a chain of the phantom classes in this scene. These classes are referred to by other classes, but cannot be * loaded. */ public Chain<SootClass> getPhantomClasses() { return phantomClasses; } Chain<SootClass> getContainingChain(SootClass c) { if (c.isApplicationClass()) { return getApplicationClasses(); } else if (c.isLibraryClass()) { return getLibraryClasses(); } else if (c.isPhantomClass()) { return getPhantomClasses(); } else { return null; } } /** ************************************************************************* */ /** Retrieves the active side-effect analysis */ public SideEffectAnalysis getSideEffectAnalysis() { SideEffectAnalysis temp = this.activeSideEffectAnalysis; if (temp == null) { temp = new SideEffectAnalysis(getPointsToAnalysis(), getCallGraph()); this.activeSideEffectAnalysis = temp; } return temp; } /** Sets the active side-effect analysis */ public void setSideEffectAnalysis(SideEffectAnalysis sea) { activeSideEffectAnalysis = sea; } public boolean hasSideEffectAnalysis() { return activeSideEffectAnalysis != null; } public void releaseSideEffectAnalysis() { activeSideEffectAnalysis = null; } /** ************************************************************************* */ /** Retrieves the active pointer analysis */ public PointsToAnalysis getPointsToAnalysis() { PointsToAnalysis temp = this.activePointsToAnalysis; if (temp == null) { return DumbPointerAnalysis.v(); } return temp; } /** Sets the active pointer analysis */ public void setPointsToAnalysis(PointsToAnalysis pa) { activePointsToAnalysis = pa; } public boolean hasPointsToAnalysis() { return activePointsToAnalysis != null; } public void releasePointsToAnalysis() { activePointsToAnalysis = null; } /** ************************************************************************* */ /** Retrieves the active client accessibility oracle */ public ClientAccessibilityOracle getClientAccessibilityOracle() { ClientAccessibilityOracle temp = this.accessibilityOracle; if (temp == null) { return PublicAndProtectedAccessibility.v(); } return temp; } public boolean hasClientAccessibilityOracle() { return accessibilityOracle != null; } public void setClientAccessibilityOracle(ClientAccessibilityOracle oracle) { accessibilityOracle = oracle; } public void releaseClientAccessibilityOracle() { accessibilityOracle = null; } /** ************************************************************************* */ /** Makes a new fast hierarchy is none is active, and returns the active fast hierarchy. */ public synchronized FastHierarchy getOrMakeFastHierarchy() { FastHierarchy temp = this.activeFastHierarchy; if (temp == null) { temp = new FastHierarchy(); this.activeFastHierarchy = temp; } return temp; } /** Retrieves the active fast hierarchy */ public synchronized FastHierarchy getFastHierarchy() { FastHierarchy temp = this.activeFastHierarchy; if (temp == null) { throw new RuntimeException("no active FastHierarchy present for scene"); } return temp; } /** Sets the active hierarchy */ public synchronized void setFastHierarchy(FastHierarchy hierarchy) { activeFastHierarchy = hierarchy; } public synchronized boolean hasFastHierarchy() { return activeFastHierarchy != null; } public synchronized void releaseFastHierarchy() { activeFastHierarchy = null; } /** ************************************************************************* */ /** Retrieves the active hierarchy */ public synchronized Hierarchy getActiveHierarchy() { Hierarchy temp = this.activeHierarchy; if (temp == null) { temp = new Hierarchy(); this.activeHierarchy = temp; } return temp; } /** Sets the active hierarchy */ public synchronized void setActiveHierarchy(Hierarchy hierarchy) { activeHierarchy = hierarchy; } public synchronized boolean hasActiveHierarchy() { return activeHierarchy != null; } public synchronized void releaseActiveHierarchy() { activeHierarchy = null; } public boolean hasCustomEntryPoints() { return entryPoints != null; } /** Get the set of entry points that are used to build the call graph. */ public List<SootMethod> getEntryPoints() { List<SootMethod> temp = this.entryPoints; if (temp == null) { temp = EntryPoints.v().all(); this.entryPoints = temp; } return temp; } /** Change the set of entry point methods used to build the call graph. */ public void setEntryPoints(List<SootMethod> entryPoints) { this.entryPoints = entryPoints; } public ContextSensitiveCallGraph getContextSensitiveCallGraph() { ContextSensitiveCallGraph temp = this.cscg; if (temp == null) { throw new RuntimeException("No context-sensitive call graph present in Scene. You can bulid one with Paddle."); } return temp; } public void setContextSensitiveCallGraph(ContextSensitiveCallGraph cscg) { this.cscg = cscg; } public CallGraph getCallGraph() { CallGraph temp = activeCallGraph; if (temp == null) { throw new RuntimeException("No call graph present in Scene. Maybe you want Whole Program mode (-w)."); } return temp; } public void setCallGraph(CallGraph cg) { this.reachableMethods = null; this.activeCallGraph = cg; } public boolean hasCallGraph() { return activeCallGraph != null; } public void releaseCallGraph() { this.activeCallGraph = null; this.reachableMethods = null; } public ReachableMethods getReachableMethods() { ReachableMethods temp = this.reachableMethods; if (temp == null) { temp = new ReachableMethods(getCallGraph(), new ArrayList<MethodOrMethodContext>(getEntryPoints())); this.reachableMethods = temp; } temp.update(); return temp; } public void setReachableMethods(ReachableMethods rm) { reachableMethods = rm; } public boolean hasReachableMethods() { return reachableMethods != null; } public void releaseReachableMethods() { reachableMethods = null; } public boolean getPhantomRefs() { // if( !Options.v().allow_phantom_refs() ) return false; // return allowsPhantomRefs; return Options.v().allow_phantom_refs(); } public void setPhantomRefs(boolean value) { allowsPhantomRefs = value; } public boolean allowsPhantomRefs() { return getPhantomRefs(); } public Numberer<Kind> kindNumberer() { return kindNumberer; } public IterableNumberer<Type> getTypeNumberer() { return typeNumberer; } public IterableNumberer<SootMethod> getMethodNumberer() { return methodNumberer; } public Numberer<Context> getContextNumberer() { return contextNumberer; } public Numberer<Unit> getUnitNumberer() { return unitNumberer; } public Numberer<SparkField> getFieldNumberer() { return fieldNumberer; } public IterableNumberer<SootClass> getClassNumberer() { return classNumberer; } public StringNumberer getSubSigNumberer() { return subSigNumberer; } public IterableNumberer<Local> getLocalNumberer() { return localNumberer; } public void setContextNumberer(Numberer<Context> n) { if (contextNumberer != null) { throw new RuntimeException("Attempt to set context numberer when it is already set."); } contextNumberer = n; } /** * Returns the {@link ThrowAnalysis} to be used by default when constructing CFGs which include exceptional control flow. * * @return the default {@link ThrowAnalysis} */ public ThrowAnalysis getDefaultThrowAnalysis() { if (defaultThrowAnalysis == null) { switch (Options.v().throw_analysis()) { case Options.throw_analysis_pedantic: defaultThrowAnalysis = PedanticThrowAnalysis.v(); break; case Options.throw_analysis_unit: defaultThrowAnalysis = UnitThrowAnalysis.v(); break; case Options.throw_analysis_dalvik: defaultThrowAnalysis = DalvikThrowAnalysis.v(); break; case Options.throw_analysis_auto_select: if (Options.v().src_prec() == Options.src_prec_apk) { defaultThrowAnalysis = DalvikThrowAnalysis.v(); } else { defaultThrowAnalysis = UnitThrowAnalysis.v(); } break; default: throw new IllegalStateException("Options.v().throw_analysis() == " + Options.v().throw_analysis()); } } return defaultThrowAnalysis; } /** * Sets the {@link ThrowAnalysis} to be used by default when constructing CFGs which include exceptional control flow. * * @param ta * the default {@link ThrowAnalysis}. */ public void setDefaultThrowAnalysis(ThrowAnalysis ta) { defaultThrowAnalysis = ta; } private void setReservedNames() { Set<String> rn = this.reservedNames; rn.add("newarray"); rn.add("newmultiarray"); rn.add("nop"); rn.add("ret"); rn.add("specialinvoke"); rn.add("staticinvoke"); rn.add("tableswitch"); rn.add("virtualinvoke"); rn.add("null_type"); rn.add("unknown"); rn.add("cmp"); rn.add("cmpg"); rn.add("cmpl"); rn.add("entermonitor"); rn.add("exitmonitor"); rn.add("interfaceinvoke"); rn.add("lengthof"); rn.add("lookupswitch"); rn.add("neg"); rn.add("if"); rn.add("abstract"); rn.add("annotation"); rn.add("boolean"); rn.add("break"); rn.add("byte"); rn.add("case"); rn.add("catch"); rn.add("char"); rn.add("class"); rn.add("enum"); rn.add("final"); rn.add("native"); rn.add("public"); rn.add("protected"); rn.add("private"); rn.add("static"); rn.add("synchronized"); rn.add("transient"); rn.add("volatile"); rn.add("interface"); rn.add("void"); rn.add("short"); rn.add("int"); rn.add("long"); rn.add("float"); rn.add("double"); rn.add("extends"); rn.add("implements"); rn.add("breakpoint"); rn.add("default"); rn.add("goto"); rn.add("instanceof"); rn.add("new"); rn.add("return"); rn.add("throw"); rn.add("throws"); rn.add("null"); rn.add("from"); rn.add("to"); rn.add("with"); rn.add("cls"); rn.add("dynamicinvoke"); rn.add("strictfp"); } private void addSootBasicClasses() { basicclasses[SootClass.HIERARCHY] = new HashSet<String>(); basicclasses[SootClass.SIGNATURES] = new HashSet<String>(); basicclasses[SootClass.BODIES] = new HashSet<String>(); addBasicClass("java.lang.Object"); addBasicClass("java.lang.Class", SootClass.SIGNATURES); addBasicClass("java.lang.Void", SootClass.SIGNATURES); addBasicClass("java.lang.Boolean", SootClass.SIGNATURES); addBasicClass("java.lang.Byte", SootClass.SIGNATURES); addBasicClass("java.lang.Character", SootClass.SIGNATURES); addBasicClass("java.lang.Short", SootClass.SIGNATURES); addBasicClass("java.lang.Integer", SootClass.SIGNATURES); addBasicClass("java.lang.Long", SootClass.SIGNATURES); addBasicClass("java.lang.Float", SootClass.SIGNATURES); addBasicClass("java.lang.Double", SootClass.SIGNATURES); addBasicClass("java.lang.Number", SootClass.SIGNATURES); addBasicClass("java.lang.String"); addBasicClass("java.lang.StringBuffer", SootClass.SIGNATURES); addBasicClass("java.lang.Enum", SootClass.SIGNATURES); addBasicClass("java.lang.Error"); addBasicClass("java.lang.AssertionError", SootClass.SIGNATURES); addBasicClass("java.lang.Throwable", SootClass.SIGNATURES); addBasicClass("java.lang.Exception", SootClass.SIGNATURES); addBasicClass("java.lang.NoClassDefFoundError", SootClass.SIGNATURES); addBasicClass("java.lang.ReflectiveOperationException", SootClass.SIGNATURES); addBasicClass("java.lang.ExceptionInInitializerError"); addBasicClass("java.lang.RuntimeException"); addBasicClass("java.lang.ClassNotFoundException"); addBasicClass("java.lang.ArithmeticException"); addBasicClass("java.lang.ArrayStoreException"); addBasicClass("java.lang.ClassCastException"); addBasicClass("java.lang.IllegalMonitorStateException"); addBasicClass("java.lang.IndexOutOfBoundsException"); addBasicClass("java.lang.ArrayIndexOutOfBoundsException"); addBasicClass("java.lang.NegativeArraySizeException"); addBasicClass("java.lang.NullPointerException", SootClass.SIGNATURES); addBasicClass("java.lang.InstantiationError"); addBasicClass("java.lang.InternalError"); addBasicClass("java.lang.OutOfMemoryError"); addBasicClass("java.lang.StackOverflowError"); addBasicClass("java.lang.UnknownError"); addBasicClass("java.lang.ThreadDeath"); addBasicClass("java.lang.ClassCircularityError"); addBasicClass("java.lang.ClassFormatError"); addBasicClass("java.lang.IllegalAccessError"); addBasicClass("java.lang.IncompatibleClassChangeError"); addBasicClass("java.lang.LinkageError"); addBasicClass("java.lang.VerifyError"); addBasicClass("java.lang.NoSuchFieldError"); addBasicClass("java.lang.AbstractMethodError"); addBasicClass("java.lang.NoSuchMethodError"); addBasicClass("java.lang.UnsatisfiedLinkError"); addBasicClass("java.lang.Thread"); addBasicClass("java.lang.Runnable"); addBasicClass("java.lang.Cloneable"); addBasicClass("java.io.Serializable"); addBasicClass("java.lang.ref.Finalizer"); addBasicClass("java.lang.invoke.LambdaMetafactory"); } public void addBasicClass(String name) { addBasicClass(name, SootClass.HIERARCHY); } public void addBasicClass(String name, int level) { basicclasses[level].add(name); } /** * Load just the set of basic classes soot needs, ignoring those specified on the command-line. You don't need to use both * this and {@link #loadNecessaryClasses()}, though it will only waste time. */ public void loadBasicClasses() { addReflectionTraceClasses(); int loadedClasses = 0; for (int i = SootClass.BODIES; i >= SootClass.HIERARCHY; i--) { for (String name : basicclasses[i]) { SootClass basicClass = tryLoadClass(name, i); if (basicClass != null && !basicClass.isPhantom()) { loadedClasses++; } } } if (loadedClasses == 0) { // Missing basic classes means no Exceptions could be loaded and no Exception hierarchy can // lead to non-deterministic Jimple code generation: catch blocks may be removed because of // non-existing Exception hierarchy. throw new RuntimeException("None of the basic classes could be loaded! Check your Soot class path!"); } } public Set<String> getBasicClasses() { Set<String> all = new HashSet<String>(); for (int i = SootClass.BODIES; i >= SootClass.HIERARCHY; i--) { all.addAll(basicclasses[i]); } return all; } public boolean isBasicClass(String className) { for (int i = SootClass.BODIES; i >= SootClass.HIERARCHY; i--) { if (basicclasses[i].contains(className)) { return true; } } return false; } protected void addReflectionTraceClasses() { Set<String> classNames = new HashSet<String>(); CGOptions options = new CGOptions(PhaseOptions.v().getPhaseOptions("cg")); String log = options.reflection_log(); if (log != null && !log.isEmpty()) { String line = null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(log)))) { while ((line = reader.readLine()) != null) { if (!line.isEmpty()) { String[] portions = line.split(";", -1); String kind = portions[0]; String target = portions[1]; String source = portions[2]; classNames.add(source.substring(0, source.lastIndexOf('.'))); switch (kind) { case "Class.forName": case "Class.newInstance": classNames.add(target); break; case "Method.invoke": case "Constructor.newInstance": case "Field.set*": case "Field.get*": case "Method.getModifiers": case "Method.getName": classNames.add(signatureToClass(target)); break; default: throw new RuntimeException("Unknown entry kind: " + kind); } } } } catch (Exception e) { throw new RuntimeException("Line: '" + line + "'", e); } } for (String c : classNames) { addBasicClass(c, SootClass.BODIES); } } public Collection<SootClass> dynamicClasses() { List<SootClass> temp = dynamicClasses; if (temp == null) { throw new IllegalStateException("Have to call loadDynamicClasses() first!"); } return temp; } protected void loadNecessaryClass(String name) { loadClassAndSupport(name).setApplicationClass(); } /** * Load the set of classes that soot needs, including those specified on the command-line. This is the standard way of * initialising the list of classes soot should use. */ public void loadNecessaryClasses() { loadBasicClasses(); final Options opts = Options.v(); for (String name : opts.classes()) { loadNecessaryClass(name); } loadDynamicClasses(); if (opts.oaat()) { if (opts.process_dir().isEmpty()) { throw new IllegalArgumentException("If switch -oaat is used, then also -process-dir must be given."); } } else { for (String path : opts.process_dir()) { for (String cl : SourceLocator.v().getClassesUnder(path)) { SootClass theClass = loadClassAndSupport(cl); if (!theClass.isPhantom) { theClass.setApplicationClass(); } } } } prepareClasses(); setDoneResolving(); } public void loadDynamicClasses() { final ArrayList<SootClass> dynamicClasses = new ArrayList<SootClass>(); final Options opts = Options.v(); final HashSet<String> temp = new HashSet<String>(opts.dynamic_class()); final SourceLocator sloc = SourceLocator.v(); for (String path : opts.dynamic_dir()) { temp.addAll(sloc.getClassesUnder(path)); } for (String pkg : opts.dynamic_package()) { temp.addAll(sloc.classesInDynamicPackage(pkg)); } for (String className : temp) { dynamicClasses.add(loadClassAndSupport(className)); } // remove non-concrete classes that may accidentally have been loaded for (Iterator<SootClass> iterator = dynamicClasses.iterator(); iterator.hasNext();) { SootClass c = iterator.next(); if (!c.isConcrete()) { if (opts.verbose()) { logger.warn("dynamic class " + c.getName() + " is abstract or an interface, and it will not be considered."); } iterator.remove(); } } this.dynamicClasses = dynamicClasses; } /** * Generate classes to process, adding or removing package marked by command line options. */ protected void prepareClasses() { final List<String> optionsClasses = Options.v().classes(); // Remove/add all classes from packageInclusionMask as per -i option Chain<SootClass> processedClasses = new HashChain<SootClass>(); while (true) { Chain<SootClass> unprocessedClasses = new HashChain<SootClass>(getClasses()); unprocessedClasses.removeAll(processedClasses); if (unprocessedClasses.isEmpty()) { break; } processedClasses.addAll(unprocessedClasses); for (SootClass s : unprocessedClasses) { if (s.isPhantom()) { continue; } if (Options.v().app()) { s.setApplicationClass(); } if (optionsClasses.contains(s.getName())) { s.setApplicationClass(); continue; } if (s.isApplicationClass() && isExcluded(s)) { s.setLibraryClass(); } if (isIncluded(s)) { s.setApplicationClass(); } if (s.isApplicationClass()) { // make sure we have the support loadClassAndSupport(s.getName()); } } } } public boolean isExcluded(SootClass sc) { return isExcluded(sc.getName()); } public boolean isExcluded(String className) { for (String pkg : excludedPackages) { if (className.equals(pkg) || ((pkg.endsWith(".*") || pkg.endsWith("$*")) && className.startsWith(pkg.substring(0, pkg.length() - 1)))) { return !isIncluded(className); } } return false; } public boolean isIncluded(SootClass sc) { return isIncluded(sc.getName()); } public boolean isIncluded(String className) { for (String pkg : Options.v().include()) { if (className.equals(pkg) || ((pkg.endsWith(".*") || pkg.endsWith("$*")) && className.startsWith(pkg.substring(0, pkg.length() - 1)))) { return true; } } return false; } public void setPkgList(List<String> list) { pkgList = list; } public List<String> getPkgList() { return pkgList; } /** Create an unresolved reference to a method. */ public SootMethodRef makeMethodRef(SootClass declaringClass, String name, List<Type> parameterTypes, Type returnType, boolean isStatic) { if (PolymorphicMethodRef.handlesClass(declaringClass)) { return new PolymorphicMethodRef(declaringClass, name, parameterTypes, returnType, isStatic); } else { return new SootMethodRefImpl(declaringClass, name, parameterTypes, returnType, isStatic); } } /** Create an unresolved reference to a constructor. */ public SootMethodRef makeConstructorRef(SootClass declaringClass, List<Type> parameterTypes) { return makeMethodRef(declaringClass, SootMethod.constructorName, parameterTypes, VoidType.v(), false); } /** Create an unresolved reference to a field. */ public SootFieldRef makeFieldRef(SootClass declaringClass, String name, Type type, boolean isStatic) { return new AbstractSootFieldRef(declaringClass, name, type, isStatic); } /** Returns the list of SootClasses that have been resolved at least to the level specified. */ public List<SootClass> getClasses(int desiredLevel) { List<SootClass> ret = new ArrayList<SootClass>(); for (SootClass cl : getClasses()) { if (cl.resolvingLevel() >= desiredLevel) { ret.add(cl); } } return ret; } public boolean doneResolving() { return doneResolving; } public void setDoneResolving() { doneResolving = true; } void setResolving(boolean value) { doneResolving = value; } public void setMainClassFromOptions() { if (mainClass == null) { String optsMain = Options.v().main_class(); if (optsMain != null && !optsMain.isEmpty()) { setMainClass(getSootClass(optsMain)); } else { final List<Type> mainArgs = Collections.singletonList(ArrayType.v(RefType.v("java.lang.String"), 1)); // try to infer a main class from the command line if none is given for (String next : Options.v().classes()) { SootClass c = getSootClass(next); if (c.declaresMethod("main", mainArgs, VoidType.v())) { logger.debug("No main class given. Inferred '" + c.getName() + "' as main class."); setMainClass(c); return; } } // try to infer a main class from the usual classpath if none is given for (SootClass c : getApplicationClasses()) { if (c.declaresMethod("main", mainArgs, VoidType.v())) { logger.debug("No main class given. Inferred '" + c.getName() + "' as main class."); setMainClass(c); return; } } } } } /** * This method returns true when in incremental build mode. Other classes can query this flag and change the way in which * they use the Scene, depending on the flag's value. */ public boolean isIncrementalBuild() { return incrementalBuild; } public void initiateIncrementalBuild() { this.incrementalBuild = true; } public void incrementalBuildFinished() { this.incrementalBuild = false; } /** * Forces Soot to resolve the class with the given name to the given level, even if resolving has actually already * finished. */ public SootClass forceResolve(String className, int level) { boolean tmp = doneResolving; doneResolving = false; SootClass c; try { c = SootResolver.v().resolveClass(className, level); } finally { doneResolving = tmp; } return c; } public SootClass makeSootClass(String name) { return new SootClass(name); } public SootClass makeSootClass(String name, int modifiers) { return new SootClass(name, modifiers); } public SootMethod makeSootMethod(String name, List<Type> parameterTypes, Type returnType) { return new SootMethod(name, parameterTypes, returnType); } public SootMethod makeSootMethod(String name, List<Type> parameterTypes, Type returnType, int modifiers) { return new SootMethod(name, parameterTypes, returnType, modifiers); } public SootMethod makeSootMethod(String name, List<Type> parameterTypes, Type returnType, int modifiers, List<SootClass> thrownExceptions) { return new SootMethod(name, parameterTypes, returnType, modifiers, thrownExceptions); } public SootField makeSootField(String name, Type type, int modifiers) { return new SootField(name, type, modifiers); } public SootField makeSootField(String name, Type type) { return new SootField(name, type); } public RefType getOrAddRefType(String refTypeName) { return nameToClass.computeIfAbsent(refTypeName, k -> new RefType(k)); } /** * <b>SOOT USERS: DO NOT CALL THIS METHOD!</b> * * <p> * This method is a Soot-internal factory method for generating callgraph objects. It creates non-initialized object that * must then be initialized by a callgraph algorithm * * @return A new callgraph empty object */ public CallGraph internalMakeCallGraph() { return new CallGraph(); } public LocalGenerator createLocalGenerator(Body stmtBody) { return new DefaultLocalGenerator(stmtBody); } public LocalCreation createLocalCreation(Chain<Local> locals) { return new DefaultLocalCreation(locals); } public LocalCreation createLocalCreation(Chain<Local> locals, String prefix) { return new DefaultLocalCreation(locals, prefix); } }
69,729
32.188958
125
java
soot
soot-master/src/main/java/soot/ScenePack.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai and 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% */ /** * A wrapper object for a pack of optimizations. Provides chain-like operations, except that the key is the phase name. */ public class ScenePack extends Pack { public ScenePack(String name) { super(name); } @Override protected void internalApply() { for (Transform t : this) { t.apply(); } } }
1,168
27.512195
119
java
soot
soot-master/src/main/java/soot/SceneTransformer.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 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.HashMap; import java.util.Map; /** An abstract class which acts on the whole Scene. */ public abstract class SceneTransformer extends Transformer { /** Performs the transformation on the Scene, under the given phaseName. */ public final void transform(String phaseName, Map<String, String> options) { if (!PhaseOptions.getBoolean(options, "enabled")) { return; } internalTransform(phaseName, options); } public final void transform(String phaseName) { HashMap<String, String> dummyOptions = new HashMap<String, String>(); dummyOptions.put("enabled", "true"); transform(phaseName, dummyOptions); } public final void transform() { transform(""); } /** Performs the transformation on the Scene, under the given phaseName and with the given Options. */ protected abstract void internalTransform(String phaseName, Map<String, String> options); }
1,734
31.735849
104
java
soot
soot-master/src/main/java/soot/ShortType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java built-in type 'short'. Implemented as a singleton. */ @SuppressWarnings("serial") public class ShortType extends PrimType implements IntegerType { public static final int HASHCODE = 0x8B817DD3; public ShortType(Singletons.Global g) { } public static ShortType v() { return G.v().soot_ShortType(); } @Override public int hashCode() { return HASHCODE; } @Override public boolean equals(Object t) { return this == t; } @Override public String toString() { return "short"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseShortType(this); } @Override public RefType boxedType() { return RefType.v("java.lang.Short"); } @Override public Class<?> getJavaBoxedType() { return Short.class; } @Override public Class<?> getJavaPrimitiveType() { return short.class; } }
1,758
21.551282
85
java
soot
soot-master/src/main/java/soot/SideEffectTester.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 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% */ /** * Provides side effect information. Presumably, different side-effect information can be computed by different * implementations of this interface. */ public interface SideEffectTester { public boolean unitCanReadFrom(Unit u, Value v); public boolean unitCanWriteTo(Unit u, Value v); // Call this whenever starting to analyze a new method public void newMethod(SootMethod m); }
1,206
31.621622
111
java
soot
soot-master/src/main/java/soot/SootClass.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import com.google.common.base.Optional; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.dava.toolkits.base.misc.PackageNamer; import soot.options.Options; import soot.tagkit.AbstractHost; import soot.util.Chain; import soot.util.EmptyChain; import soot.util.HashChain; import soot.util.Numberable; import soot.util.NumberedString; import soot.util.SmallNumberedMap; import soot.validation.ClassFlagsValidator; import soot.validation.ClassValidator; import soot.validation.MethodDeclarationValidator; import soot.validation.OuterClassValidator; import soot.validation.ValidationException; /* * Incomplete and inefficient implementation. * * Implementation notes: * * 1. The getFieldOf() method is slow because it traverses the list of fields, comparing the names, * one by one. If you establish a Dictionary of Name->Field, you will need to add a * notifyOfNameChange() method, and register fields which belong to classes, because the hashtable * will need to be updated. I will do this later. - kor 16-Sep-97 * * 2. Note 1 is kept for historical (i.e. amusement) reasons. In fact, there is no longer a list of fields; * these are kept in a Chain now. But that's ok; there is no longer a getFieldOf() method, * either. There still is no efficient way to get a field by name, although one could establish * a Chain of EquivalentValue-like objects and do an O(1) search on that. - plam 2-24-00 */ /** * Soot representation of a Java class. They are usually created by a Scene, but can also be constructed manually through the * given constructors. */ public class SootClass extends AbstractHost implements Numberable { private static final Logger logger = LoggerFactory.getLogger(SootClass.class); public final static String INVOKEDYNAMIC_DUMMY_CLASS_NAME = "soot.dummy.InvokeDynamic"; public final static int DANGLING = 0; public final static int HIERARCHY = 1; public final static int SIGNATURES = 2; public final static int BODIES = 3; protected String name, shortName, fixedShortName, packageName, fixedPackageName; protected int modifiers; protected Chain<SootField> fields; protected SmallNumberedMap<NumberedString, SootMethod> subSigToMethods; // methodList is just for keeping the methods in a consistent order. It // needs to be kept consistent with subSigToMethods. protected List<SootMethod> methodList; protected Chain<SootClass> interfaces; protected boolean isInScene; protected SootClass superClass; protected SootClass outerClass; protected boolean isPhantom; public final String moduleName; protected SootModuleInfo moduleInformation; private RefType refType; private volatile int resolvingLevel = DANGLING; protected volatile int number = 0; /** * Lazy initialized array containing some validators in order to validate the SootClass. */ private static class LazyValidatorsSingleton { static final ClassValidator[] V = new ClassValidator[] { OuterClassValidator.v(), MethodDeclarationValidator.v(), ClassFlagsValidator.v() }; private LazyValidatorsSingleton() { } } /** * Constructs an empty SootClass with the given name and modifiers. */ public SootClass(String name, int modifiers) { this(name, modifiers, null); } public SootClass(String name, String moduleName) { this(name, 0, moduleName); } public SootClass(String name) { this(name, 0, null); } public SootClass(String name, int modifiers, String moduleName) { if (name.length() > 0 && name.charAt(0) == '[') { throw new RuntimeException("Attempt to make a class whose name starts with ["); } this.moduleName = moduleName; setName(name); this.modifiers = modifiers; initializeRefType(name, moduleName); if (Options.v().debug_resolver()) { logger.debug("created " + name + " with modifiers " + modifiers); } setResolvingLevel(BODIES); } /** * Makes sure that there is a RefType pointing to this SootClass. Client code that provides its own SootClass * implementation can override and modify this behavior. * * @param name * The name of the new class */ protected void initializeRefType(String name, String moduleName) { if (ModuleUtil.module_mode()) { this.refType = ModuleRefType.v(name, Optional.fromNullable(this.moduleName)); } else { this.refType = RefType.v(name); } this.refType.setSootClass(this); } protected static String levelToString(int level) { switch (level) { case DANGLING: return "DANGLING"; case HIERARCHY: return "HIERARCHY"; case SIGNATURES: return "SIGNATURES"; case BODIES: return "BODIES"; default: throw new RuntimeException("unknown resolving level"); } } /** * Checks if the class has at least the resolving level specified. This check does nothing is the class resolution process * is not completed. * * @param level * the resolution level, one of DANGLING, HIERARCHY, SIGNATURES, and BODIES * @throws java.lang.RuntimeException * if the resolution is at an insufficient level */ public void checkLevel(int level) { // Fast check: e.g. FastHierarchy.canStoreClass calls this method quite often if (resolvingLevel() >= level) { return; } if (!Scene.v().doneResolving() || Options.v().ignore_resolving_levels()) { return; } checkLevelIgnoreResolving(level); } /** * Checks if the class has at least the resolving level specified. This check ignores the resolution completeness. * * @param level * the resolution level, one of DANGLING, HIERARCHY, SIGNATURES, and BODIES * @throws java.lang.RuntimeException * if the resolution is at an insufficient level */ public void checkLevelIgnoreResolving(int level) { int currentLevel = resolvingLevel(); if (currentLevel < level) { String hint = "\nIf you are extending Soot, try to add the following call before calling soot.Main.main(..):\n" + "Scene.v().addBasicClass(" + getName() + "," + levelToString(level) + ");\n" + "Otherwise, try whole-program mode (-w)."; throw new RuntimeException("This operation requires resolving level " + levelToString(level) + " but " + name + " is at resolving level " + levelToString(currentLevel) + hint); } } public int resolvingLevel() { return resolvingLevel; } public void setResolvingLevel(int newLevel) { resolvingLevel = newLevel; } public boolean isInScene() { return isInScene; } /** * Tells this class if it is being managed by a Scene. */ public void setInScene(boolean isInScene) { this.isInScene = isInScene; Scene.v().getClassNumberer().add(this); } /** * Returns the number of fields in this class. */ public int getFieldCount() { checkLevel(SIGNATURES); return fields == null ? 0 : fields.size(); } /** * Returns a backed Chain of fields. */ public Chain<SootField> getFields() { checkLevel(SIGNATURES); return fields == null ? EmptyChain.v() : fields; } /* * public void setFields(Field[] fields) { this.fields = new ArraySet(fields); } */ /** * Adds the given field to this class. */ public void addField(SootField f) { checkLevel(SIGNATURES); if (f.isDeclared()) { throw new RuntimeException("already declared: " + f.getName()); } if (declaresField(f.getName(), f.getType())) { throw new RuntimeException("Field already exists : " + f.getName() + " of type " + f.getType()); } if (fields == null) { fields = new HashChain<>(); } fields.add(f); f.setDeclared(true); f.setDeclaringClass(this); } /** * Removes the given field from this class. */ public void removeField(SootField f) { checkLevel(SIGNATURES); if (!f.isDeclared() || f.getDeclaringClass() != this) { throw new RuntimeException("did not declare: " + f.getName()); } if (fields != null) { fields.remove(f); } f.setDeclared(false); f.setDeclaringClass(null); } /** * Returns the field of this class with the given name and type. If the field cannot be found, an exception is thrown. */ public SootField getField(String name, Type type) { SootField sf = getFieldUnsafe(name, type); if (sf == null) { throw new RuntimeException("No field " + name + " in class " + getName()); } return sf; } /** * Returns the field of this class with the given name and type. If the field cannot be found, null is returned. */ public SootField getFieldUnsafe(String name, Type type) { checkLevel(SIGNATURES); if (fields != null) { for (SootField field : fields.getElementsUnsorted()) { if (name.equals(field.getName()) && type.equals(field.getType())) { return field; } } } return null; } /** * Returns the field of this class with the given name. Throws a RuntimeException if there is more than one field with the * given name or if no such field exists at all. */ public SootField getFieldByName(String name) { SootField foundField = getFieldByNameUnsafe(name); if (foundField == null) { throw new RuntimeException("No field " + name + " in class " + getName()); } return foundField; } /** * Returns the field of this class with the given name. Throws a RuntimeException if there is more than one field with the * given name. Returns null if no field with the given name exists. */ public SootField getFieldByNameUnsafe(String name) { assert (name != null); checkLevel(SIGNATURES); SootField foundField = null; if (fields != null) { for (SootField field : fields.getElementsUnsorted()) { if (name.equals(field.getName())) { if (foundField == null) { foundField = field; } else { throw new AmbiguousFieldException(name, this.name); } } } } return foundField; } /** * Returns the field of this class with the given subsignature. If such a field does not exist, an exception is thrown. */ public SootField getField(String subsignature) { // NOTE: getFieldUnsafe(String) calls checkLevel(SIGNATURES) SootField sf = getFieldUnsafe(subsignature); if (sf == null) { throw new RuntimeException("No field " + subsignature + " in class " + getName()); } return sf; } /** * Returns the field of this class with the given subsignature. If such a field does not exist, null is returned. */ public SootField getFieldUnsafe(String subsignature) { checkLevel(SIGNATURES); if (fields != null) { for (SootField field : fields.getElementsUnsorted()) { if (subsignature.equals(field.getSubSignature())) { return field; } } } return null; } /** * Does this class declare a field with the given subsignature? */ public boolean declaresField(String subsignature) { // NOTE: getFieldUnsafe(String) calls checkLevel(SIGNATURES) return getFieldUnsafe(subsignature) != null; } /** * Returns the method of this class with the given subsignature. If no method with the given subsignature can be found, an * exception is thrown. */ public SootMethod getMethod(NumberedString subsignature) { // NOTE: getMethodUnsafe(NumberedString) calls checkLevel(SIGNATURES) SootMethod ret = getMethodUnsafe(subsignature); if (ret == null) { throw new RuntimeException("No method " + subsignature + " in class " + getName()); } else { return ret; } } /** * Returns the method of this class with the given subsignature. If no method with the given subsignature can be found, * null is returned. */ public SootMethod getMethodUnsafe(NumberedString subsignature) { checkLevel(SIGNATURES); return (subSigToMethods != null) ? subSigToMethods.get(subsignature) : null; } /** * Does this class declare a method with the given subsignature? */ public boolean declaresMethod(NumberedString subsignature) { // NOTE: getMethodUnsafe(NumberedString) calls checkLevel(SIGNATURES) return getMethodUnsafe(subsignature) != null; } /* * Returns the method of this class with the given subsignature. If no method with the given subsignature can be found, an * exception is thrown. */ public SootMethod getMethod(String subsignature) { // NOTE: getMethodUnsafe(NumberedString) calls checkLevel(SIGNATURES) NumberedString numberedString = Scene.v().getSubSigNumberer().find(subsignature); if (numberedString == null) { throw new RuntimeException("No method " + subsignature + " in class " + getName()); } return getMethod(numberedString); } /* * Returns the method of this class with the given subsignature. If no method with the given subsignature can be found, * null is returned. */ public SootMethod getMethodUnsafe(String subsignature) { // NOTE: getMethodUnsafe(NumberedString) calls checkLevel(SIGNATURES) NumberedString numberedString = Scene.v().getSubSigNumberer().find(subsignature); return numberedString == null ? null : getMethodUnsafe(numberedString); } /** * Does this class declare a method with the given subsignature? */ public boolean declaresMethod(String subsignature) { // NOTE: getMethodUnsafe(NumberedString) calls checkLevel(SIGNATURES) NumberedString numberedString = Scene.v().getSubSigNumberer().find(subsignature); return numberedString == null ? false : declaresMethod(numberedString); } /** * Does this class declare a field with the given name? */ public boolean declaresFieldByName(String name) { checkLevel(SIGNATURES); if (fields != null) { for (SootField field : fields) { if (name.equals(field.getName())) { return true; } } } return false; } /** * Does this class declare a field with the given name and type. */ public boolean declaresField(String name, Type type) { checkLevel(SIGNATURES); if (fields != null) { for (SootField field : fields) { if (name.equals(field.getName()) && type.equals(field.getType())) { return true; } } } return false; } /** * Returns the number of methods in this class. */ public int getMethodCount() { checkLevel(SIGNATURES); return (subSigToMethods == null) ? 0 : subSigToMethods.nonNullSize(); } /** * Returns an iterator over the methods in this class. */ public Iterator<SootMethod> methodIterator() { checkLevel(SIGNATURES); if (methodList == null) { return Collections.emptyIterator(); } return new Iterator<SootMethod>() { final Iterator<SootMethod> internalIterator = methodList.iterator(); private SootMethod currentMethod; @Override public boolean hasNext() { return internalIterator.hasNext(); } @Override public SootMethod next() { currentMethod = internalIterator.next(); return currentMethod; } @Override public void remove() { internalIterator.remove(); subSigToMethods.put(currentMethod.getNumberedSubSignature(), null); currentMethod.setDeclared(false); } }; } public List<SootMethod> getMethods() { checkLevel(SIGNATURES); return (methodList != null) ? methodList : Collections.emptyList(); } /** * Attempts to retrieve the method with the given name, parameters and return type. If no matching method can be found, an * exception is thrown. */ public SootMethod getMethod(String name, List<Type> parameterTypes, Type returnType) { SootMethod sm = getMethodUnsafe(name, parameterTypes, returnType); if (sm != null) { return sm; } throw new RuntimeException("Class " + getName() + " doesn't have method \"" + SootMethod.getSubSignature(name, parameterTypes, returnType) + "\""); } /** * Attempts to retrieve the method with the given name, parameters and return type. If no matching method can be found, * null is returned. */ public SootMethod getMethodUnsafe(String name, List<Type> parameterTypes, Type returnType) { checkLevel(SIGNATURES); if (methodList != null) { for (SootMethod method : new ArrayList<>(methodList)) { if (name.equals(method.getName()) && returnType.equals(method.getReturnType()) && parameterTypes.equals(method.getParameterTypes())) { return method; } } } return null; } /** * Attempts to retrieve the method with the given name and parameters. This method may throw an AmbiguousMethodException if * there is more than one method with the given name and parameter. */ public SootMethod getMethod(String name, List<Type> parameterTypes) { checkLevel(SIGNATURES); if (methodList != null) { SootMethod foundMethod = null; for (SootMethod method : methodList) { if (name.equals(method.getName()) && parameterTypes.equals(method.getParameterTypes())) { if (foundMethod == null) { foundMethod = method; } else { throw new AmbiguousMethodException(name, this.name); } } } if (foundMethod != null) { return foundMethod; } } throw new RuntimeException("couldn't find method " + name + "(" + parameterTypes + ") in " + this); } /** * Attempts to retrieve the method with the given name. This method may throw an AmbiguousMethodException if there are more * than one method with the given name. If no method with the given is found, null is returned. */ public SootMethod getMethodByNameUnsafe(String name) { checkLevel(SIGNATURES); SootMethod foundMethod = null; if (methodList != null) { for (SootMethod method : methodList) { if (name.equals(method.getName())) { if (foundMethod == null) { foundMethod = method; } else { throw new AmbiguousMethodException(name, this.name); } } } } return foundMethod; } /** * Attempts to retrieve the method with the given name. This method may throw an AmbiguousMethodException if there are more * than one method with the given name. If no method with the given is found, an exception is thrown as well. */ public SootMethod getMethodByName(String name) { SootMethod foundMethod = getMethodByNameUnsafe(name); if (foundMethod == null) { throw new RuntimeException("couldn't find method " + name + "(*) in " + this); } return foundMethod; } /** * Does this class declare a method with the given name and parameter types? */ public boolean declaresMethod(String name, List<Type> parameterTypes) { checkLevel(SIGNATURES); if (methodList != null) { for (SootMethod method : methodList) { if (name.equals(method.getName()) && parameterTypes.equals(method.getParameterTypes())) { return true; } } } return false; } /** * Does this class declare a method with the given name, parameter types, and return type? */ public boolean declaresMethod(String name, List<Type> parameterTypes, Type returnType) { checkLevel(SIGNATURES); if (methodList != null) { for (SootMethod method : methodList) { if (name.equals(method.getName()) && returnType.equals(method.getReturnType()) && parameterTypes.equals(method.getParameterTypes())) { return true; } } } return false; } /** * Does this class declare a method with the given name? */ public boolean declaresMethodByName(String name) { checkLevel(SIGNATURES); if (methodList != null) { for (SootMethod method : methodList) { if (name.equals(method.getName())) { return true; } } } return false; } /* * public void setMethods(Method[] method) { methods = new ArraySet(method); } */ /** * Adds the given method to this class. */ public void addMethod(SootMethod m) { checkLevel(SIGNATURES); if (m.isDeclared()) { throw new RuntimeException("already declared: " + m.getName()); } /* * if(declaresMethod(m.getName(), m.getParameterTypes())) throw new RuntimeException("duplicate signature for: " + * m.getName()); */ if (methodList == null) { this.methodList = Collections.synchronizedList(new ArrayList<>()); this.subSigToMethods = new SmallNumberedMap<>(); } if (this.subSigToMethods.get(m.getNumberedSubSignature()) != null) { throw new RuntimeException("Attempting to add method " + m.getSubSignature() + " to class " + this + ", but the class already has a method with that signature."); } this.subSigToMethods.put(m.getNumberedSubSignature(), m); this.methodList.add(m); m.setDeclared(true); m.setDeclaringClass(this); } public synchronized SootMethod getOrAddMethod(SootMethod m) { checkLevel(SIGNATURES); if (m.isDeclared()) { throw new RuntimeException("already declared: " + m.getName()); } if (methodList == null) { this.methodList = Collections.synchronizedList(new ArrayList<>()); this.subSigToMethods = new SmallNumberedMap<>(); } SootMethod old = this.subSigToMethods.get(m.getNumberedSubSignature()); if (old != null) { return old; } this.subSigToMethods.put(m.getNumberedSubSignature(), m); this.methodList.add(m); m.setDeclared(true); m.setDeclaringClass(this); return m; } public synchronized SootField getOrAddField(SootField f) { checkLevel(SIGNATURES); if (f.isDeclared()) { throw new RuntimeException("already declared: " + f.getName()); } SootField old = getFieldUnsafe(f.getName(), f.getType()); if (old != null) { return old; } if (this.fields == null) { this.fields = new HashChain<>(); } this.fields.add(f); f.setDeclared(true); f.setDeclaringClass(this); return f; } /** * Removes the given method from this class. */ public void removeMethod(SootMethod m) { checkLevel(SIGNATURES); if (!m.isDeclared() || m.getDeclaringClass() != this) { throw new RuntimeException("incorrect declarer for remove: " + m.getName()); } if (subSigToMethods.get(m.getNumberedSubSignature()) == null) { throw new RuntimeException("Attempt to remove method " + m.getSubSignature() + " which is not in class " + this); } subSigToMethods.put(m.getNumberedSubSignature(), null); methodList.remove(m); m.setDeclared(false); m.setDeclaringClass(null); Scene scene = Scene.v(); scene.getMethodNumberer().remove(m); // We have caches for resolving default methods in the FastHierarchy, which are no longer valid scene.modifyHierarchy(); } /** * Returns the modifiers of this class. */ public int getModifiers() { return modifiers; } /** * Sets the modifiers for this class. */ public void setModifiers(int modifiers) { this.modifiers = modifiers; } /** * Returns the number of interfaces being directly implemented by this class. Note that direct implementation corresponds * to an "implements" keyword in the Java class file and that this class may still be implementing additional interfaces in * the usual sense by being a subclass of a class which directly implements some interfaces. */ public int getInterfaceCount() { checkLevel(HIERARCHY); return interfaces == null ? 0 : interfaces.size(); } /** * Returns a backed Chain of the interfaces that are directly implemented by this class. (see getInterfaceCount()) */ public Chain<SootClass> getInterfaces() { checkLevel(HIERARCHY); return interfaces == null ? EmptyChain.v() : interfaces; } /** * Does this class directly implement the given interface? (see getInterfaceCount()) */ public boolean implementsInterface(String name) { checkLevel(HIERARCHY); if (interfaces != null) { for (SootClass sc : interfaces) { if (name.equals(sc.getName())) { return true; } } } return false; } /** * Add the given class to the list of interfaces which are directly implemented by this class. */ public void addInterface(SootClass interfaceClass) { // NOTE: implementsInterface(String) calls checkLevel(HIERARCHY) if (implementsInterface(interfaceClass.getName())) { throw new RuntimeException("duplicate interface on class " + this.getName() + ": " + interfaceClass.getName()); } if (this.interfaces == null) { // Use a small initial size to reduce excess memory usage in the HashChain. // The HashChain uses an underlying ConcurrentHashMap whose default table // size is 16. However, classes tend to implement very few interfaces in // practice (often just 1) which can lead to a significant wasted memory // allocation when the default table size is used. Using an initial table // size of 4 allows up to 2 interfaces to be added before the table is // resized (an initial table size smaller than 4 will be resized up to 4 // when the first element is added due to the load factor in the map). this.interfaces = new HashChain<>(4); } this.interfaces.add(interfaceClass); } /** * Removes the given class from the list of interfaces which are directly implemented by this class. */ public void removeInterface(SootClass interfaceClass) { // NOTE: implementsInterface(String) calls checkLevel(HIERARCHY) if (!implementsInterface(interfaceClass.getName())) { throw new RuntimeException("no such interface on class " + this.getName() + ": " + interfaceClass.getName()); } interfaces.remove(interfaceClass); if (interfaces.isEmpty()) { this.interfaces = null; } } /** * WARNING: interfaces are subclasses of the java.lang.Object class! Does this class have a superclass? False implies that * this is the java.lang.Object class. Note that interfaces are subclasses of the java.lang.Object class. */ public boolean hasSuperclass() { checkLevel(HIERARCHY); return superClass != null; } /** * WARNING: interfaces are subclasses of the java.lang.Object class! Returns the superclass of this class. (see * hasSuperclass()) */ public SootClass getSuperclass() { checkLevel(HIERARCHY); if (superClass == null && !isPhantom() && !Options.v().ignore_resolution_errors()) { throw new RuntimeException("no superclass for " + getName()); } else { return superClass; } } /** * This method returns the superclass, or null if no superclass has been specified for this class. * * WARNING: interfaces are subclasses of the java.lang.Object class! Returns the superclass of this class. (see * hasSuperclass()) */ public SootClass getSuperclassUnsafe() { checkLevel(HIERARCHY); return superClass; } /** * Sets the superclass of this class. Note that passing a null will cause the class to have no superclass. */ public void setSuperclass(SootClass c) { checkLevel(HIERARCHY); superClass = c; } public boolean hasOuterClass() { checkLevel(HIERARCHY); return outerClass != null; } public SootClass getOuterClass() { checkLevel(HIERARCHY); if (outerClass == null) { throw new RuntimeException("no outer class"); } else { return outerClass; } } /** * This method returns the outer class, or null if no outer class has been specified for this class. */ public SootClass getOuterClassUnsafe() { checkLevel(HIERARCHY); return outerClass; } public void setOuterClass(SootClass c) { checkLevel(HIERARCHY); outerClass = c; } public boolean isInnerClass() { return hasOuterClass(); } /** * Returns the name of this class. */ public String getName() { return name; } public String getJavaStyleName() { if (PackageNamer.v().has_FixedNames()) { if (fixedShortName == null) { fixedShortName = PackageNamer.v().get_FixedClassName(name); } if (!PackageNamer.v().use_ShortName(getJavaPackageName(), fixedShortName)) { return getJavaPackageName() + '.' + fixedShortName; } return fixedShortName; } else { return shortName; } } public String getShortJavaStyleName() { if (PackageNamer.v().has_FixedNames()) { if (fixedShortName == null) { fixedShortName = PackageNamer.v().get_FixedClassName(name); } return fixedShortName; } else { return shortName; } } public String getShortName() { return shortName; } /** * Returns the package name of this class. */ public String getPackageName() { return packageName; } public String getJavaPackageName() { if (PackageNamer.v().has_FixedNames()) { if (fixedPackageName == null) { fixedPackageName = PackageNamer.v().get_FixedPackageName(packageName); } return fixedPackageName; } else { return packageName; } } /** * Sets the name of this class. */ public void setName(String name) { this.name = name.intern(); int index = name.lastIndexOf('.'); if (index > 0) { this.shortName = name.substring(index + 1); this.packageName = name.substring(0, index); } else { this.shortName = name; this.packageName = ""; } this.fixedShortName = null; this.fixedPackageName = null; } /** * Convenience method; returns true if this class is an interface. */ public boolean isInterface() { checkLevel(HIERARCHY); return Modifier.isInterface(this.getModifiers()); } /** * Convenience method; returns true if this class is an enumeration. */ public boolean isEnum() { checkLevel(HIERARCHY); return Modifier.isEnum(this.getModifiers()); } /** * Convenience method; returns true if this class is synchronized. */ public boolean isSynchronized() { checkLevel(HIERARCHY); return Modifier.isSynchronized(this.getModifiers()); } /** * Returns true if this class is not an interface and not abstract. */ public boolean isConcrete() { return !isInterface() && !isAbstract(); } /** * Convenience method; returns true if this class is public. */ public boolean isPublic() { return Modifier.isPublic(this.getModifiers()); } /** * Returns true if some method in this class has an active Baf body. */ public boolean containsBafBody() { for (Iterator<SootMethod> methodIt = methodIterator(); methodIt.hasNext();) { SootMethod m = methodIt.next(); if (m.hasActiveBody() && m.getActiveBody() instanceof soot.baf.BafBody) { return true; } } return false; } // made public for obfuscator.. public void setRefType(RefType refType) { this.refType = refType; } public boolean hasRefType() { return refType != null; } /** * Returns the RefType corresponding to this class. */ public RefType getType() { return refType; } /** * Returns the name of this class. */ @Override public String toString() { return getName(); } /** * Renames private fields and methods with numeric names. */ public void renameFieldsAndMethods(boolean privateOnly) { checkLevel(SIGNATURES); // Rename fields. Ignore collisions for now. { int fieldCount = 0; for (SootField f : this.getFields()) { if (!privateOnly || Modifier.isPrivate(f.getModifiers())) { f.setName("__field" + (fieldCount++)); } } } // Rename methods. Again, ignore collisions for now. { int methodCount = 0; for (Iterator<SootMethod> methodIt = methodIterator(); methodIt.hasNext();) { SootMethod m = methodIt.next(); if (!privateOnly || Modifier.isPrivate(m.getModifiers())) { m.setName("__method" + (methodCount++)); } } } } /** * Convenience method returning true if this class is an application class. * * @see Scene#getApplicationClasses() */ public boolean isApplicationClass() { return Scene.v().getApplicationClasses().contains(this); } /** Makes this class an application class. */ public void setApplicationClass() { if (isApplicationClass()) { return; } Chain<SootClass> c = Scene.v().getContainingChain(this); if (c != null) { c.remove(this); } Scene.v().getApplicationClasses().add(this); isPhantom = false; } /** * Convenience method returning true if this class is a library class. * * @see Scene#getLibraryClasses() */ public boolean isLibraryClass() { return Scene.v().getLibraryClasses().contains(this); } /** Makes this class a library class. */ public void setLibraryClass() { if (isLibraryClass()) { return; } Chain<SootClass> c = Scene.v().getContainingChain(this); if (c != null) { c.remove(this); } Scene.v().getLibraryClasses().add(this); isPhantom = false; } /** * Sometimes we need to know which class is a JDK class. There is no simple way to distinguish a user class and a JDK * class, here we use the package prefix as the heuristic. * * @author xiao */ public boolean isJavaLibraryClass() { return name.startsWith("java.") || name.startsWith("sun.") || name.startsWith("javax.") || name.startsWith("com.sun.") || name.startsWith("org.omg.") || name.startsWith("org.xml.") || name.startsWith("org.w3c.dom"); } /** * Convenience method returning true if this class is a phantom class. * * @see Scene#getPhantomClasses() */ public boolean isPhantomClass() { return Scene.v().getPhantomClasses().contains(this); } /** Makes this class a phantom class. */ public void setPhantomClass() { Chain<SootClass> c = Scene.v().getContainingChain(this); if (c != null) { c.remove(this); } Scene.v().getPhantomClasses().add(this); isPhantom = true; } /** * Convenience method returning true if this class is phantom. */ public boolean isPhantom() { return isPhantom; } /** * Convenience method returning true if this class is private. */ public boolean isPrivate() { return Modifier.isPrivate(this.getModifiers()); } /** * Convenience method returning true if this class is protected. */ public boolean isProtected() { return Modifier.isProtected(this.getModifiers()); } /** * Convenience method returning true if this class is abstract. */ public boolean isAbstract() { return Modifier.isAbstract(this.getModifiers()); } /** * Convenience method returning true if this class is final. */ public boolean isFinal() { return Modifier.isFinal(this.getModifiers()); } /** * Convenience method returning true if this class is static. */ public boolean isStatic() { return Modifier.isStatic(this.getModifiers()); } @Override public final int getNumber() { return number; } @Override public void setNumber(int number) { this.number = number; } public void rename(String newName) { this.name = newName; // resolvingLevel = BODIES; if (this.refType != null) { this.refType.setClassName(name); } else if (ModuleUtil.module_mode()) { this.refType = ModuleScene.v().getOrAddRefType(name, Optional.fromNullable(this.moduleName)); } else { this.refType = Scene.v().getOrAddRefType(name); } } /** * Validates this SootClass for logical errors. Note that this does not validate the method bodies, only the class * structure. */ public void validate() { final List<ValidationException> exceptionList = new ArrayList<ValidationException>(); validate(exceptionList); if (!exceptionList.isEmpty()) { throw exceptionList.get(0); } } /** * Validates this SootClass for logical errors. Note that this does not validate the method bodies, only the class * structure. All found errors are saved into the given list. */ public void validate(List<ValidationException> exceptionList) { final boolean runAllValidators = Options.v().debug() || Options.v().validate(); for (ClassValidator validator : LazyValidatorsSingleton.V) { if (runAllValidators || validator.isBasicValidator()) { validator.validate(this, exceptionList); } } } public String getFilePath() { if (ModuleUtil.module_mode()) { return moduleName + ':' + this.getName(); } else { return this.getName(); } } public SootModuleInfo getModuleInformation() { return moduleInformation; } public void setModuleInformation(SootModuleInfo moduleInformation) { this.moduleInformation = moduleInformation; } /** * Checks if this class is exported by it's module * * @return true if the class is public exported */ public boolean isExportedByModule() { if (this.getModuleInformation() == null && ModuleUtil.module_mode()) { // we are in module mode and obviously the class has not been resolved, therefore we have to resolve it Scene.v().forceResolve(this.getName(), SootClass.BODIES); } SootModuleInfo moduleInfo = this.getModuleInformation(); // for dummy classes moduleInfo could be null return (moduleInfo == null) ? true : moduleInfo.exportsPackagePublic(this.getJavaPackageName()); } /** * Checks if this class is exported by it's module * * @return true if the class is public exported */ public boolean isExportedByModule(String toModule) { if (this.getModuleInformation() == null && ModuleUtil.module_mode()) { // we are in module mode and obviously the class has not been resolved, therefore we have to resolve it ModuleScene.v().forceResolve(this.getName(), SootClass.BODIES, Optional.of(this.moduleName)); } return this.getModuleInformation().exportsPackage(this.getJavaPackageName(), toModule); } public boolean isOpenedByModule() { if (this.getModuleInformation() == null && ModuleUtil.module_mode()) { // we are in module mode and obviously the class has not been resolved, therefore we have to resolve it Scene.v().forceResolve(this.getName(), SootClass.BODIES); } SootModuleInfo moduleInfo = this.getModuleInformation(); return (moduleInfo == null) ? true : moduleInfo.openPackagePublic(this.getJavaPackageName()); } }
39,862
29.499617
125
java
soot
soot-master/src/main/java/soot/SootField.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.jimple.paddle.PaddleField; import soot.jimple.spark.pag.SparkField; import soot.options.Options; import soot.tagkit.AbstractHost; import soot.util.Numberable; /** * Soot representation of a Java field. Can be declared to belong to a SootClass. */ public class SootField extends AbstractHost implements ClassMember, SparkField, Numberable, PaddleField { protected String name; protected Type type; protected int modifiers; protected boolean isDeclared = false; protected SootClass declaringClass; protected boolean isPhantom = false; protected volatile String sig; protected volatile String subSig; private int number = 0; /** * Constructs a Soot field with the given name, type and modifiers. */ public SootField(String name, Type type, int modifiers) { if (name == null || type == null) { throw new RuntimeException("A SootField cannot have a null name or type."); } this.name = name; this.type = type; this.modifiers = modifiers; } /** * Constructs a Soot field with the given name, type and no modifiers. */ public SootField(String name, Type type) { this(name, type, 0); } public int equivHashCode() { return type.hashCode() * 101 + modifiers * 17 + name.hashCode(); } public String getSignature() { if (sig == null) { synchronized (this) { if (sig == null) { sig = getSignature(getDeclaringClass(), getSubSignature()); } } } return sig; } public static String getSignature(SootClass cl, String name, Type type) { return getSignature(cl, getSubSignature(name, type)); } public static String getSignature(SootClass cl, String subSignature) { StringBuilder buffer = new StringBuilder(); buffer.append('<').append(Scene.v().quotedNameOf(cl.getName())).append(": "); buffer.append(subSignature).append('>'); return buffer.toString(); } public String getSubSignature() { if (subSig == null) { synchronized (this) { if (subSig == null) { subSig = getSubSignature(getName(), getType()); } } } return subSig; } protected static String getSubSignature(String name, Type type) { StringBuilder buffer = new StringBuilder(); buffer.append(type.toQuotedString()).append(' ').append(Scene.v().quotedNameOf(name)); return buffer.toString(); } @Override public SootClass getDeclaringClass() { if (!isDeclared) { throw new RuntimeException("not declared: " + getName() + " " + getType()); } return declaringClass; } public synchronized void setDeclaringClass(SootClass sc) { if (sc != null && type instanceof RefLikeType) { Scene.v().getFieldNumberer().add(this); } this.declaringClass = sc; this.sig = null; } @Override public boolean isPhantom() { return isPhantom; } @Override public void setPhantom(boolean value) { if (value) { if (!Scene.v().allowsPhantomRefs()) { throw new RuntimeException("Phantom refs not allowed"); } if (!Options.v().allow_phantom_elms() && declaringClass != null && !declaringClass.isPhantom()) { throw new RuntimeException("Declaring class would have to be phantom"); } } isPhantom = value; } @Override public boolean isDeclared() { return isDeclared; } public void setDeclared(boolean isDeclared) { this.isDeclared = isDeclared; } public String getName() { return name; } public synchronized void setName(String name) { if (name != null) { this.name = name; this.sig = null; this.subSig = null; } } @Override public Type getType() { return type; } public synchronized void setType(Type t) { if (t != null) { this.type = t; this.sig = null; this.subSig = null; } } /** * Convenience method returning true if this field is public. */ @Override public boolean isPublic() { return Modifier.isPublic(this.getModifiers()); } /** * Convenience method returning true if this field is protected. */ @Override public boolean isProtected() { return Modifier.isProtected(this.getModifiers()); } /** * Convenience method returning true if this field is private. */ @Override public boolean isPrivate() { return Modifier.isPrivate(this.getModifiers()); } /** * Convenience method returning true if this field is static. */ @Override public boolean isStatic() { return Modifier.isStatic(this.getModifiers()); } /** * Convenience method returning true if this field is final. */ public boolean isFinal() { return Modifier.isFinal(this.getModifiers()); } @Override public void setModifiers(int modifiers) { this.modifiers = modifiers; } @Override public int getModifiers() { return modifiers; } @Override public String toString() { return getSignature(); } private String getOriginalStyleDeclaration() { String qualifiers = (Modifier.toString(modifiers) + ' ' + type.toQuotedString()).trim(); if (qualifiers.isEmpty()) { return Scene.v().quotedNameOf(name); } else { return qualifiers + ' ' + Scene.v().quotedNameOf(name); } } public String getDeclaration() { return getOriginalStyleDeclaration(); } @Override public final int getNumber() { return number; } @Override public final void setNumber(int number) { this.number = number; } public SootFieldRef makeRef() { return Scene.v().makeFieldRef(declaringClass, name, type, isStatic()); } }
6,481
24.027027
105
java
soot
soot-master/src/main/java/soot/SootFieldRef.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Representation of a reference to a field as it appears in a class file. Note that the field directly referred to may not * actually exist; the actual target of the reference is determined according to the resolution procedure in the Java Virtual * Machine Specification, 2nd ed, section 5.4.3.2. */ public interface SootFieldRef { public SootClass declaringClass(); public String name(); public Type type(); public boolean isStatic(); public String getSignature(); public SootField resolve(); }
1,336
29.386364
125
java
soot
soot-master/src/main/java/soot/SootMethod.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.dava.DavaBody; import soot.dava.toolkits.base.renamer.RemoveFullyQualifiedName; import soot.options.Options; import soot.tagkit.AbstractHost; import soot.util.IterableSet; import soot.util.Numberable; import soot.util.NumberedString; /** * Soot representation of a Java method. Can be declared to belong to a {@link SootClass}. Does not contain the actual code, * which belongs to a {@link Body}. The {@link #getActiveBody()} method points to the currently-active body. */ public class SootMethod extends AbstractHost implements ClassMember, Numberable, MethodOrMethodContext, SootMethodInterface { private static final Logger logger = LoggerFactory.getLogger(SootMethod.class); public static final String constructorName = "<init>"; public static final String staticInitializerName = "<clinit>"; /** * Name of the current method. */ protected String name; /** * An array of parameter types taken by this {@link SootMethod} object, in declaration order. */ protected Type[] parameterTypes; /** * The return type of this object. */ protected Type returnType; /** * True when some {@link SootClass} object declares this {@link SootMethod} object. */ protected boolean isDeclared; /** * Holds the class which declares this <code>SootClass</code> method. */ protected SootClass declaringClass; /** * Modifiers associated with this {@link SootMethod} (e.g. private, protected, etc.) */ protected int modifiers; /** * Is this method a phantom method? */ protected boolean isPhantom = false; /** * Declared exceptions thrown by this method. Created upon demand. */ protected List<SootClass> exceptions; /** * Active body associated with this method. */ protected volatile Body activeBody; /** * Tells this method how to find out where its body lives. */ protected volatile MethodSource ms; protected volatile String sig; protected volatile String subSig; protected NumberedString subsignature; protected int number = 0; /** * Constructs a {@link SootMethod} with the given name, parameter types and return type. */ public SootMethod(String name, List<Type> parameterTypes, Type returnType) { this(name, parameterTypes, returnType, 0, Collections.<SootClass>emptyList()); } /** * Constructs a {@link SootMethod} with the given name, parameter types, return type and modifiers. */ public SootMethod(String name, List<Type> parameterTypes, Type returnType, int modifiers) { this(name, parameterTypes, returnType, modifiers, Collections.<SootClass>emptyList()); } /** * Constructs a {@link SootMethod} with the given name, parameter types, return type, and list of thrown exceptions. */ public SootMethod(String name, List<Type> parameterTypes, Type returnType, int modifiers, List<SootClass> thrownExceptions) { this.name = name; if (parameterTypes != null && !parameterTypes.isEmpty()) { this.parameterTypes = parameterTypes.toArray(new Type[parameterTypes.size()]); } this.returnType = returnType; this.modifiers = modifiers; if (thrownExceptions != null && !thrownExceptions.isEmpty()) { this.exceptions = new ArrayList<SootClass>(thrownExceptions); } this.subsignature = Scene.v().getSubSigNumberer().findOrAdd(getSubSignature()); } /** * Returns a hash code for this method consistent with structural equality. */ public int equivHashCode() { return returnType.hashCode() * 101 + modifiers * 17 + name.hashCode(); } /** * Returns the name of this method. */ @Override public String getName() { return name; } /** * Sets the name of this method. */ public synchronized void setName(String name) { boolean wasDeclared = isDeclared; SootClass oldDeclaringClass = declaringClass; if (wasDeclared) { oldDeclaringClass.removeMethod(this); } this.name = name; this.sig = null; this.subSig = null; this.subsignature = Scene.v().getSubSigNumberer().findOrAdd(getSubSignature()); if (wasDeclared) { oldDeclaringClass.addMethod(this); } } /** * Sets the declaring class */ public synchronized void setDeclaringClass(SootClass declClass) { // There is nothing to stop this field from being null except when it actually gets in // other classes such as SootMethodRef (when it tries to resolve the method). However, if // the method is not declared, it should not be trying to resolve it anyways. So I see no // problem with having it able to be null. if (declClass != null) { Scene.v().getMethodNumberer().add(this); } // We could call setDeclared here, however, when SootClass adds a method, it checks isDeclared // and throws an exception if set. So we currently cannot call setDeclared here. this.declaringClass = declClass; this.sig = null; } /** * Returns the class which declares the current {@link SootMethod}. */ @Override public SootClass getDeclaringClass() { if (!isDeclared) { throw new RuntimeException("not declared: " + getName()); } return declaringClass; } public void setDeclared(boolean isDeclared) { this.isDeclared = isDeclared; } /** * Returns true when some {@link SootClass} object declares this {@link SootMethod} object. */ @Override public boolean isDeclared() { return isDeclared; } /** * Returns true when this {@link SootMethod} object is phantom. */ @Override public boolean isPhantom() { return isPhantom; } /** * Returns true if this method is not phantom, abstract or native, i.e. this method can have a body. */ public boolean isConcrete() { return !isPhantom() && !isAbstract() && !isNative(); } /** * Sets the phantom flag on this method. */ @Override public void setPhantom(boolean value) { if (value) { if (!Scene.v().allowsPhantomRefs()) { throw new RuntimeException("Phantom refs not allowed"); } if (!Options.v().allow_phantom_elms() && declaringClass != null && !declaringClass.isPhantom()) { throw new RuntimeException("Declaring class would have to be phantom"); } } this.isPhantom = value; } /** * Gets the modifiers of this method. * * @see soot.Modifier */ @Override public int getModifiers() { return modifiers; } /** * Sets the modifiers of this method. * * @see soot.Modifier */ @Override public void setModifiers(int modifiers) { this.modifiers = modifiers; } /** * Returns the return type of this method. */ @Override public Type getReturnType() { return returnType; } /** * Sets the return type of this method. */ public synchronized void setReturnType(Type t) { boolean wasDeclared = isDeclared; SootClass oldDeclaringClass = declaringClass; if (wasDeclared) { oldDeclaringClass.removeMethod(this); } this.returnType = t; this.sig = null; this.subSig = null; this.subsignature = Scene.v().getSubSigNumberer().findOrAdd(getSubSignature()); if (wasDeclared) { oldDeclaringClass.addMethod(this); } } /** * Returns the number of parameters taken by this method. */ public int getParameterCount() { return parameterTypes == null ? 0 : parameterTypes.length; } /** * Gets the type of the <i>n</i>th parameter of this method. */ @Override public Type getParameterType(int n) { return parameterTypes[n]; } /** * Returns a read-only list of the parameter types of this method. */ @Override public List<Type> getParameterTypes() { return parameterTypes == null ? Collections.<Type>emptyList() : Arrays.asList(parameterTypes); } /** * Changes the set of parameter types of this method. */ public synchronized void setParameterTypes(List<Type> l) { boolean wasDeclared = isDeclared; SootClass oldDeclaringClass = declaringClass; if (wasDeclared) { oldDeclaringClass.removeMethod(this); } this.parameterTypes = l.toArray(new Type[l.size()]); this.sig = null; this.subSig = null; this.subsignature = Scene.v().getSubSigNumberer().findOrAdd(getSubSignature()); if (wasDeclared) { oldDeclaringClass.addMethod(this); } } /** * Returns the {@link MethodSource} of the current {@link SootMethod}. */ public MethodSource getSource() { return ms; } /** * Sets the {@link MethodSource} of the current {@link SootMethod}. */ public synchronized void setSource(MethodSource ms) { this.ms = ms; } /** * Retrieves the active body for this method. */ @SuppressWarnings("deprecation") public Body getActiveBody() { // Retrieve the active body so thread changes do not affect the // synchronization between if the body exists and the returned body. // This is a quick check just in case the activeBody exists. Body activeBody = this.activeBody; if (activeBody != null) { return activeBody; } // Synchronize because we are operating on two fields that may be updated // separately otherwise. synchronized (this) { // Re-check the activeBody because things might have changed activeBody = this.activeBody; if (activeBody != null) { return activeBody; } if (declaringClass != null) { declaringClass.checkLevel(SootClass.BODIES); } if ((declaringClass != null && declaringClass.isPhantomClass()) || isPhantom()) { throw new RuntimeException("cannot get active body for phantom method: " + getSignature()); } // ignore empty body exceptions if we are just computing coffi metrics if (!soot.jbco.Main.metrics) { throw new RuntimeException("no active body present for method " + getSignature()); } return null; } } /** * Sets the active body for this method. */ public synchronized void setActiveBody(Body body) { if ((declaringClass != null) && declaringClass.isPhantomClass()) { throw new RuntimeException("cannot set active body for phantom class! " + this); } // If someone sets a body for a phantom method, this method then is no // longer phantom setPhantom(false); if (!isConcrete()) { throw new RuntimeException("cannot set body for non-concrete method! " + this); } if (body != null) { body.setMethod(this); } this.activeBody = body; } /** * Returns the active body if present, else constructs an active body and returns that. * * If you called Scene.v().loadClassAndSupport() for a class yourself, it will not be an application class, so you cannot * get retrieve its active body. Please call {@link SootClass#setApplicationClass()} on the relevant class. */ public Body retrieveActiveBody() { // Retrieve the active body so thread changes do not affect the // synchronization between if the body exists and the returned body. // This is a quick check just in case the activeBody exists. Body activeBody = this.activeBody; if (activeBody != null) { return activeBody; } // Synchronize because we are operating on multiple fields that may be updated // separately otherwise. synchronized (this) { // Re-check the activeBody because things might have changed activeBody = this.activeBody; if (activeBody != null) { return activeBody; } if (declaringClass != null) { declaringClass.checkLevel(SootClass.BODIES); } if ((declaringClass != null && declaringClass.isPhantomClass()) || isPhantom()) { throw new RuntimeException("cannot get resident body for phantom method : " + this); } if (ms == null) { throw new RuntimeException("No method source set for method " + this); } // Method sources are not expected to be thread safe activeBody = ms.getBody(this, "jb"); setActiveBody(activeBody); // If configured, we drop the method source to save memory if (Options.v().drop_bodies_after_load()) { ms = null; } return activeBody; } } /** * Returns true if this method has an active body. */ public boolean hasActiveBody() { return activeBody != null; } /** * Releases the active body associated with this method. */ public synchronized void releaseActiveBody() { this.activeBody = null; } /** * Adds the given exception to the list of exceptions thrown by this method unless the exception is already in the list. */ public void addExceptionIfAbsent(SootClass e) { if (!throwsException(e)) { addException(e); } } /** * Adds the given exception to the list of exceptions thrown by this method. */ public void addException(SootClass e) { logger.trace("Adding exception {}", e); if (exceptions == null) { exceptions = new ArrayList<SootClass>(); } else if (exceptions.contains(e)) { throw new RuntimeException("already throws exception " + e.getName()); } exceptions.add(e); } /** * Removes the given exception from the list of exceptions thrown by this method. */ public void removeException(SootClass e) { logger.trace("Removing exception {}", e); if (exceptions == null || !exceptions.contains(e)) { throw new RuntimeException("does not throw exception " + e.getName()); } exceptions.remove(e); } /** * Returns true if this method throws exception <code>e</code>. */ public boolean throwsException(SootClass e) { return exceptions != null && exceptions.contains(e); } public void setExceptions(List<SootClass> exceptions) { this.exceptions = (exceptions == null || exceptions.isEmpty()) ? null : new ArrayList<SootClass>(exceptions); } /** * Returns a backed list of the exceptions thrown by this method. */ public List<SootClass> getExceptions() { if (exceptions == null) { exceptions = new ArrayList<SootClass>(); } return exceptions; } public List<SootClass> getExceptionsUnsafe() { return exceptions; } /** * Convenience method returning true if this method is static. */ @Override public boolean isStatic() { return Modifier.isStatic(this.getModifiers()); } /** * Convenience method returning true if this method is private. */ @Override public boolean isPrivate() { return Modifier.isPrivate(this.getModifiers()); } /** * Convenience method returning true if this method is public. */ @Override public boolean isPublic() { return Modifier.isPublic(this.getModifiers()); } /** * Convenience method returning true if this method is protected. */ @Override public boolean isProtected() { return Modifier.isProtected(this.getModifiers()); } /** * Convenience method returning true if this method is abstract. */ public boolean isAbstract() { return Modifier.isAbstract(this.getModifiers()); } /** * Convenience method returning true if this method is final. */ public boolean isFinal() { return Modifier.isFinal(this.getModifiers()); } /** * Convenience method returning true if this method is native. */ public boolean isNative() { return Modifier.isNative(this.getModifiers()); } /** * Convenience method returning true if this method is synchronized. */ public boolean isSynchronized() { return Modifier.isSynchronized(this.getModifiers()); } /** * * @return yes if this is the main method */ public boolean isMain() { return isPublic() && isStatic() && Scene.v().getSubSigNumberer().findOrAdd("void main(java.lang.String[])").equals(subsignature); } /** * * @return yes, if this function is a constructor. Please not that <clinit> methods are not treated as constructors in this * method. */ public boolean isConstructor() { return constructorName.equals(name); } /** * * @return yes, if this function is a static initializer. */ public boolean isStaticInitializer() { return staticInitializerName.equals(name); } /** * @return yes, if this is a class initializer or main function. */ public boolean isEntryMethod() { if (isStatic() && SootMethod.staticInitializerName.equals(subsignature.getString())) { return true; } return isMain(); } /** * We rely on the JDK class recognition to decide if a method is JDK method. */ public boolean isJavaLibraryMethod() { return getDeclaringClass().isJavaLibraryClass(); } /** * Returns the parameters part of the signature in the format in which it appears in bytecode. */ public String getBytecodeParms() { StringBuilder buffer = new StringBuilder(); for (Type type : getParameterTypes()) { buffer.append(AbstractJasminClass.jasminDescriptorOf(type)); } return buffer.toString().intern(); } /** * Returns the signature of this method in the format in which it appears in bytecode (eg. [Ljava/lang/Object instead of * java.lang.Object[]). */ public String getBytecodeSignature() { StringBuilder buffer = new StringBuilder(); buffer.append('<'); buffer.append(Scene.v().quotedNameOf(getDeclaringClass().getName())); buffer.append(": "); buffer.append(getName()); buffer.append(AbstractJasminClass.jasminDescriptorOf(makeRef())); buffer.append('>'); return buffer.toString().intern(); } /** * Returns the Soot signature of this method. Used to refer to methods unambiguously. */ @Override public String getSignature() { String sig = this.sig; if (sig == null) { synchronized (this) { sig = this.sig; if (sig == null) { this.sig = sig = getSignature(getDeclaringClass(), getSubSignature()); } } } return sig; } public static String getSignature(SootClass cl, String name, List<Type> params, Type returnType) { return getSignature(cl, getSubSignatureImpl(name, params, returnType)); } public static String getSignature(SootClass cl, String subSignature) { StringBuilder buffer = new StringBuilder(); buffer.append('<'); buffer.append(Scene.v().quotedNameOf(cl.getName())); buffer.append(": "); buffer.append(subSignature); buffer.append('>'); return buffer.toString(); } /** * Returns the Soot subsignature of this method. Used to refer to methods unambiguously. */ public String getSubSignature() { String subSig = this.subSig; if (subSig == null) { synchronized (this) { subSig = this.subSig; if (subSig == null) { this.subSig = subSig = getSubSignatureImpl(getName(), getParameterTypes(), getReturnType()); } } } return subSig; } public static String getSubSignature(String name, List<Type> params, Type returnType) { return getSubSignatureImpl(name, params, returnType); } private static String getSubSignatureImpl(String name, List<Type> params, Type returnType) { StringBuilder buffer = new StringBuilder(); buffer.append(returnType.toQuotedString()); buffer.append(' '); buffer.append(Scene.v().quotedNameOf(name)); buffer.append('('); if (params != null) { for (int i = 0, e = params.size(); i < e; i++) { if (i > 0) { buffer.append(','); } buffer.append(params.get(i).toQuotedString()); } } buffer.append(')'); return buffer.toString(); } public NumberedString getNumberedSubSignature() { return subsignature; } /** * Returns the signature of this method. */ @Override public String toString() { return getSignature(); } /* * TODO: Nomair A. Naeem .... 8th Feb 2006 This is really messy coding So much for modularization!! Should some day look * into creating the DavaDeclaration from within DavaBody */ public String getDavaDeclaration() { if (staticInitializerName.equals(getName())) { return "static"; } StringBuilder buffer = new StringBuilder(); // modifiers StringTokenizer st = new StringTokenizer(Modifier.toString(this.getModifiers())); if (st.hasMoreTokens()) { buffer.append(st.nextToken()); while (st.hasMoreTokens()) { buffer.append(' ').append(st.nextToken()); } } if (buffer.length() != 0) { buffer.append(' '); } // return type + name if (constructorName.equals(getName())) { buffer.append(getDeclaringClass().getShortJavaStyleName()); } else { Type t = this.getReturnType(); String tempString = t.toString(); /* * Added code to handle RuntimeExcepotion thrown by getActiveBody */ if (hasActiveBody()) { DavaBody body = (DavaBody) getActiveBody(); IterableSet<String> importSet = body.getImportList(); if (!importSet.contains(tempString)) { body.addToImportList(tempString); } tempString = RemoveFullyQualifiedName.getReducedName(importSet, tempString, t); } buffer.append(tempString).append(' '); buffer.append(Scene.v().quotedNameOf(this.getName())); } // parameters int count = 0; buffer.append('('); for (Iterator<Type> typeIt = this.getParameterTypes().iterator(); typeIt.hasNext();) { Type t = typeIt.next(); String tempString = t.toString(); /* * Nomair A. Naeem 7th Feb 2006 It is nice to remove the fully qualified type names of parameters if the package they * belong to have been imported javax.swing.ImageIcon should be just ImageIcon if javax.swing is imported If not * imported WHY NOT..import it!! */ if (hasActiveBody()) { DavaBody body = (DavaBody) getActiveBody(); IterableSet<String> importSet = body.getImportList(); if (!importSet.contains(tempString)) { body.addToImportList(tempString); } tempString = RemoveFullyQualifiedName.getReducedName(importSet, tempString, t); } buffer.append(tempString).append(' '); buffer.append(' '); if (hasActiveBody()) { buffer.append(((DavaBody) getActiveBody()).get_ParamMap().get(count++)); } else { if (t == BooleanType.v()) { buffer.append('z').append(count++); } else if (t == ByteType.v()) { buffer.append('b').append(count++); } else if (t == ShortType.v()) { buffer.append('s').append(count++); } else if (t == CharType.v()) { buffer.append('c').append(count++); } else if (t == IntType.v()) { buffer.append('i').append(count++); } else if (t == LongType.v()) { buffer.append('l').append(count++); } else if (t == DoubleType.v()) { buffer.append('d').append(count++); } else if (t == FloatType.v()) { buffer.append('f').append(count++); } else if (t == StmtAddressType.v()) { buffer.append('a').append(count++); } else if (t == ErroneousType.v()) { buffer.append('e').append(count++); } else if (t == NullType.v()) { buffer.append('n').append(count++); } else { buffer.append('r').append(count++); } } if (typeIt.hasNext()) { buffer.append(", "); } } buffer.append(')'); // Print exceptions if (exceptions != null) { Iterator<SootClass> exceptionIt = this.getExceptions().iterator(); if (exceptionIt.hasNext()) { buffer.append(" throws ").append(exceptionIt.next().getName()); while (exceptionIt.hasNext()) { buffer.append(", ").append(exceptionIt.next().getName()); } } } return buffer.toString().intern(); } /** * Returns the declaration of this method, as used at the top of textual body representations (before the {}'s containing * the code for representation.) */ public String getDeclaration() { StringBuilder buffer = new StringBuilder(); // modifiers StringTokenizer st = new StringTokenizer(Modifier.toString(this.getModifiers())); if (st.hasMoreTokens()) { buffer.append(st.nextToken()); while (st.hasMoreTokens()) { buffer.append(' ').append(st.nextToken()); } } if (buffer.length() != 0) { buffer.append(' '); } // return type + name buffer.append(this.getReturnType().toQuotedString()).append(' '); buffer.append(Scene.v().quotedNameOf(this.getName())); // parameters buffer.append('('); for (Iterator<Type> typeIt = this.getParameterTypes().iterator(); typeIt.hasNext();) { Type t = typeIt.next(); buffer.append(t.toQuotedString()); if (typeIt.hasNext()) { buffer.append(", "); } } buffer.append(')'); // Print exceptions if (exceptions != null) { Iterator<SootClass> exceptionIt = this.getExceptions().iterator(); if (exceptionIt.hasNext()) { buffer.append(" throws ").append(Scene.v().quotedNameOf(exceptionIt.next().getName())); while (exceptionIt.hasNext()) { buffer.append(", ").append(Scene.v().quotedNameOf(exceptionIt.next().getName())); } } } return buffer.toString().intern(); } @Override public final int getNumber() { return number; } @Override public final void setNumber(int number) { this.number = number; } @Override public SootMethod method() { return this; } @Override public Context context() { return null; } public SootMethodRef makeRef() { return Scene.v().makeMethodRef(declaringClass, name, parameterTypes == null ? null : Arrays.asList(parameterTypes), returnType, isStatic()); } public boolean isValidResolve(SootMethodRef ref) { return (this.isStatic() == ref.isStatic()) && Objects.equals(this.getDeclaringClass(), ref.getDeclaringClass()) && Objects.equals(this.getName(), ref.getName()) && Objects.equals(this.getReturnType(), ref.getReturnType()) && Objects.equals(this.getParameterTypes(), ref.getParameterTypes()); } @Override public int getJavaSourceStartLineNumber() { super.getJavaSourceStartLineNumber(); // search statements for first line number if (line == -1 && hasActiveBody()) { for (Unit u : getActiveBody().getUnits()) { int l = u.getJavaSourceStartLineNumber(); if (l > -1) { // store l-1, as method header is usually one line before // 1st statement line = l - 1; break; } } } return line; } }
27,914
27.957469
125
java
soot
soot-master/src/main/java/soot/SootMethodInterface.java
package soot; /*- * #%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.List; /** * The common interface of {@link SootMethod} (resolved method) and {@link SootMethodRef} (unresolved method). Therefore it * allows to access the properties independently whether the method is a resolved one or not. */ public interface SootMethodInterface { /** * @return The class which declares the current {@link SootMethod}/{@link SootMethodRef} */ public SootClass getDeclaringClass(); /** * @return Name of the method */ public String getName(); public List<Type> getParameterTypes(); public Type getParameterType(int i); public Type getReturnType(); public boolean isStatic(); /** * @return The Soot signature of this method. Used to refer to methods unambiguously. */ public String getSignature(); }
1,621
27.45614
123
java
soot
soot-master/src/main/java/soot/SootMethodRef.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.SootMethodRefImpl.ClassResolutionFailedException; import soot.options.Options; import soot.util.NumberedString; /** * Representation of a reference to a method as it appears in a class file. Note that the method directly referred to may not * actually exist; the actual target of the reference is determined according to the resolution procedure in the Java Virtual * Machine Specification, 2nd ed, section 5.4.3.3. */ public interface SootMethodRef extends SootMethodInterface { /** * Use {@link #getDeclaringClass()} instead */ public @Deprecated SootClass declaringClass(); /** * Use {@link #getName()} instead */ public @Deprecated String name(); /** * Use {@link #getParameterTypes()} instead */ public @Deprecated List<Type> parameterTypes(); /** * Use {@link #getReturnType()} instead */ public @Deprecated Type returnType(); /** * Use {@link #getParameterType(int)} instead */ public @Deprecated Type parameterType(int i); /** * Gets whether this method reference points to a constructor * * @return True if this reference points to a constructor, false otherwise */ public default boolean isConstructor() { return getReturnType() == VoidType.v() && "<init>".equals(getName()); } public NumberedString getSubSignature(); /** * Resolves this method call, i.e., finds the method to which this reference points. This method does not handle virtual * dispatch, it just gives the immediate target, which can also be an abstract method. * * @return The immediate target if this method reference * @throws ClassResolutionFailedException * (can be suppressed by {@link Options#set_ignore_resolution_errors(boolean)}) */ public SootMethod resolve(); /** * Tries to resolve this method call, i.e., tries to finds the method to which this reference points. This method does not * handle virtual dispatch, it just gives the immediate target, which can also be an abstract method. This method is * different from {@link #resolve()} in the following ways: * * (1) This method does not fail when the target method does not exist and phantom references are not allowed. In that * case, it returns <code>null</code>. (2) While {@link #resolve()} creates fake methods that throw exceptions when a * target method does not exist and phantom references are allowed, this method returns <code>null</code>. * * @return The immediate target if this method reference if available, <code>null</code> otherwise */ public SootMethod tryResolve(); }
3,438
34.091837
125
java
soot
soot-master/src/main/java/soot/SootMethodRefImpl.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.jimple.AssignStmt; import soot.jimple.InvokeStmt; import soot.jimple.Jimple; import soot.jimple.JimpleBody; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StringConstant; import soot.options.Options; import soot.util.NumberedString; /** * Representation of a reference to a method as it appears in a class file. Note that the method directly referred to may not * actually exist; the actual target of the reference is determined according to the resolution procedure in the Java Virtual * Machine Specification, 2nd ed, section 5.4.3.3. * * @author Manuel Benz 22.10.19 - Delegate method resolution behavior to FastHierarchy to have one common place for extension */ public class SootMethodRefImpl implements SootMethodRef { private static final Logger logger = LoggerFactory.getLogger(SootMethodRefImpl.class); private final SootClass declaringClass; private final String name; private final List<Type> parameterTypes; private final Type returnType; private final boolean isStatic; private SootMethod resolveCache = null; private NumberedString subsig; /** * Constructor. * * @param declaringClass * the declaring class. Must not be {@code null} * @param name * the method name. Must not be {@code null} * @param parameterTypes * the types of parameters. May be {@code null} * @param returnType * the type of return value. Must not be {@code null} * @param isStatic * the static modifier value * @throws IllegalArgumentException * is thrown when {@code declaringClass}, or {@code name}, or {@code returnType} is null */ public SootMethodRefImpl(SootClass declaringClass, String name, List<Type> parameterTypes, Type returnType, boolean isStatic) { if (declaringClass == null) { throw new IllegalArgumentException("Attempt to create SootMethodRef with null class"); } if (name == null) { throw new IllegalArgumentException("Attempt to create SootMethodRef with null name"); } if (returnType == null) { throw new IllegalArgumentException("Attempt to create SootMethodRef with null returnType"); } this.declaringClass = declaringClass; this.name = name; this.parameterTypes = createParameterTypeList(parameterTypes); this.returnType = returnType; this.isStatic = isStatic; } // Not everbody likes creating a copy of the parameter type list. If you're careful, you can // safe precious CPU cycles and a bit of memory. protected List<Type> createParameterTypeList(List<Type> parameterTypes) { // initialize with unmodifiable collection if (parameterTypes == null) { return Collections.emptyList(); } else { return Collections.unmodifiableList(new ArrayList<>(parameterTypes)); } } @Override public SootClass declaringClass() { return getDeclaringClass(); } @Override public SootClass getDeclaringClass() { return declaringClass; } @Override public String name() { return getName(); } @Override public String getName() { return name; } @Override public List<Type> parameterTypes() { return getParameterTypes(); } @Override public List<Type> getParameterTypes() { return parameterTypes; } @Override public Type returnType() { return getReturnType(); } @Override public Type getReturnType() { return returnType; } @Override public boolean isStatic() { return isStatic; } @Override public NumberedString getSubSignature() { if (subsig != null) { return subsig; } if (resolveCache != null) { subsig = resolveCache.getNumberedSubSignature(); return subsig; } // This method is expensive, so it makes sense to cache the result subsig = Scene.v().getSubSigNumberer().findOrAdd(SootMethod.getSubSignature(name, parameterTypes, returnType)); return subsig; } @Override public String getSignature() { return SootMethod.getSignature(declaringClass, name, parameterTypes, returnType); } @Override public Type parameterType(int i) { return getParameterType(i); } @Override public Type getParameterType(int i) { return parameterTypes.get(i); } public class ClassResolutionFailedException extends ResolutionFailedException { /** */ private static final long serialVersionUID = 5430199603403917938L; public ClassResolutionFailedException() { super("Class " + declaringClass + " doesn't have method " + name + "(" + (parameterTypes == null ? "" : parameterTypes) + ")" + " : " + returnType + "; failed to resolve in superclasses and interfaces"); } @Override public String toString() { final StringBuilder ret = new StringBuilder(super.toString()); resolve(ret); return ret.toString(); } } @Override public SootMethod resolve() { SootMethod cached = this.resolveCache; // Use the cached SootMethod if available and still valid if (cached == null || !cached.isValidResolve(this)) { cached = resolve(null); this.resolveCache = cached; } return cached; } @Override public SootMethod tryResolve() { return tryResolve(null); } private void checkStatic(SootMethod method) { final int opt = Options.v().wrong_staticness(); if ((opt == Options.wrong_staticness_fail || opt == Options.wrong_staticness_fixstrict) && method.isStatic() != isStatic() && !method.isPhantom()) { throw new ResolutionFailedException("Resolved " + this + " to " + method + " which has wrong static-ness"); } } protected SootMethod tryResolve(final StringBuilder trace) { // let's do a dispatch and allow abstract method for resolution // we do not have a base object for call so we just take the type of the declaring class SootMethod resolved = Scene.v().getOrMakeFastHierarchy().resolveMethod(declaringClass, declaringClass, name, parameterTypes, returnType, true, this.getSubSignature()); if (resolved != null) { checkStatic(resolved); return resolved; } else if (Scene.v().allowsPhantomRefs()) { // Try to resolve in the current class and the interface, // if not found check for phantom class in the superclass. for (SootClass selectedClass = declaringClass; selectedClass != null;) { if (selectedClass.isPhantom()) { SootMethod phantomMethod = Scene.v().makeSootMethod(name, parameterTypes, returnType, isStatic() ? Modifier.STATIC : 0); phantomMethod.setPhantom(true); phantomMethod = selectedClass.getOrAddMethod(phantomMethod); checkStatic(phantomMethod); return phantomMethod; } selectedClass = selectedClass.getSuperclassUnsafe(); } } // If we don't have a method yet, we try to fix it on the fly if (Scene.v().allowsPhantomRefs() && Options.v().ignore_resolution_errors()) { // if we have a phantom class in the hierarchy, we add the method to it. SootClass classToAddTo = declaringClass; while (classToAddTo != null && !classToAddTo.isPhantom()) { classToAddTo = classToAddTo.getSuperclassUnsafe(); } // We just take the declared class, otherwise. if (classToAddTo == null) { classToAddTo = declaringClass; } SootMethod method = Scene.v().makeSootMethod(name, parameterTypes, returnType, isStatic() ? Modifier.STATIC : 0); method.setPhantom(true); method = classToAddTo.getOrAddMethod(method); checkStatic(method); return method; } return null; } private SootMethod resolve(final StringBuilder trace) { SootMethod resolved = tryResolve(trace); if (resolved != null) { return resolved; } // When allowing phantom refs we also allow for references to non-existing // methods. We simply create the methods on the fly. The method body will // throw an appropriate error just in case the code *is* actually reached // at runtime. Furthermore, the declaring class of dynamic invocations is // not known at compile time, treat as phantom class regardless if phantom // classes are enabled or not. if (Options.v().allow_phantom_refs() || SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME.equals(declaringClass.getName())) { return createUnresolvedErrorMethod(declaringClass); } if (trace == null) { ClassResolutionFailedException e = new ClassResolutionFailedException(); if (Options.v().ignore_resolution_errors()) { logger.debug(e.getMessage()); } else { throw e; } } return null; } /** * Creates a method body that throws an "unresolved compilation error" message * * @param declaringClass * The class that was supposed to contain the method * @return The created SootMethod */ private SootMethod createUnresolvedErrorMethod(SootClass declaringClass) { final Jimple jimp = Jimple.v(); SootMethod m = Scene.v().makeSootMethod(name, parameterTypes, returnType, isStatic() ? Modifier.STATIC : 0); int modifiers = Modifier.PUBLIC; // we don't know who will be calling us if (isStatic()) { modifiers |= Modifier.STATIC; } m.setModifiers(modifiers); JimpleBody body = jimp.newBody(m); m.setActiveBody(body); final LocalGenerator lg = Scene.v().createLocalGenerator(body); // For producing valid Jimple code, we need to access all parameters. // Otherwise, methods like "getThisLocal()" will fail. body.insertIdentityStmts(declaringClass); // exc = new Error RefType runtimeExceptionType = RefType.v("java.lang.Error"); Local exceptionLocal = lg.generateLocal(runtimeExceptionType); AssignStmt assignStmt = jimp.newAssignStmt(exceptionLocal, jimp.newNewExpr(runtimeExceptionType)); body.getUnits().add(assignStmt); // exc.<init>(message) SootMethodRef cref = Scene.v().makeConstructorRef(runtimeExceptionType.getSootClass(), Collections.<Type>singletonList(RefType.v("java.lang.String"))); SpecialInvokeExpr constructorInvokeExpr = jimp.newSpecialInvokeExpr(exceptionLocal, cref, StringConstant.v("Unresolved compilation error: Method " + getSignature() + " does not exist!")); InvokeStmt initStmt = jimp.newInvokeStmt(constructorInvokeExpr); body.getUnits().insertAfter(initStmt, assignStmt); // throw exc body.getUnits().insertAfter(jimp.newThrowStmt(exceptionLocal), initStmt); return declaringClass.getOrAddMethod(m); } @Override public String toString() { return getSignature(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((declaringClass == null) ? 0 : declaringClass.hashCode()); result = prime * result + (isStatic ? 1231 : 1237); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((parameterTypes == null) ? 0 : parameterTypes.hashCode()); result = prime * result + ((returnType == null) ? 0 : returnType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } SootMethodRefImpl other = (SootMethodRefImpl) obj; if (this.isStatic != other.isStatic) { return false; } if (this.declaringClass == null) { if (other.declaringClass != null) { return false; } } else if (!this.declaringClass.equals(other.declaringClass)) { return false; } if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (this.parameterTypes == null) { if (other.parameterTypes != null) { return false; } } else if (!this.parameterTypes.equals(other.parameterTypes)) { return false; } if (this.returnType == null) { if (other.returnType != null) { return false; } } else if (!this.returnType.equals(other.returnType)) { return false; } return true; } }
13,224
31.654321
125
java
soot
soot-master/src/main/java/soot/SootModuleInfo.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-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.base.Optional; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.dava.toolkits.base.misc.PackageNamer; /** * Represents a Module-Info file. * * @author Andreas Dann */ public class SootModuleInfo extends SootClass { public static final String MODULE_INFO_FILE = "module-info.class"; public static final String MODULE_INFO = "module-info"; private static final String ALL_MODULES = "EVERYONE_MODULE"; private final HashSet<String> modulePackages = new HashSet<>(); private final Map<SootModuleInfo, Integer> requiredModules = new HashMap<>(); // TODO: change String to SootClassReference private final Map<String, List<String>> exportedPackages = new HashMap<>(); // TODO: change String to SootClassReference private final Map<String, List<String>> openedPackages = new HashMap<>(); private boolean isAutomaticModule; public SootModuleInfo(String name, int modifiers, String moduleName) { super(name, modifiers, moduleName); } public SootModuleInfo(String name, String moduleName) { this(name, moduleName, false); } public SootModuleInfo(String name, String moduleName, boolean isAutomatic) { super(name, moduleName); this.isAutomaticModule = isAutomatic; } public boolean isAutomaticModule() { return isAutomaticModule; } public void setAutomaticModule(boolean automaticModule) { isAutomaticModule = automaticModule; } private Map<String, List<String>> getExportedPackages() { return exportedPackages; } private Map<String, List<String>> getOpenedPackages() { return openedPackages; } public Set<String> getPublicExportedPackages() { Set<String> publicExportedPackages = new HashSet<>(); for (String packaze : modulePackages) { if (this.exportsPackage(packaze, ALL_MODULES)) { publicExportedPackages.add(packaze); } } return publicExportedPackages; } public Set<String> getPublicOpenedPackages() { Set<String> publicOpenedPackages = new HashSet<>(); for (String packaze : modulePackages) { if (this.opensPackage(packaze, ALL_MODULES)) { publicOpenedPackages.add(packaze); } } return publicOpenedPackages; } public Map<SootModuleInfo, Integer> getRequiredModules() { return requiredModules; } public Map<SootModuleInfo, Integer> retrieveRequiredModules() { Map<SootModuleInfo, Integer> moduleInfos = requiredModules; // move into subclass if (this.isAutomaticModule) { // we can read all modules for (SootClass sootClass : Scene.v().getClasses()) { if (sootClass instanceof SootModuleInfo && sootClass.moduleName != this.moduleName) { moduleInfos.put((SootModuleInfo) sootClass, Modifier.REQUIRES_STATIC); } } } for (SootModuleInfo moduleInfo : moduleInfos.keySet()) { SootModuleResolver.v().resolveClass(SootModuleInfo.MODULE_INFO, SootClass.BODIES, Optional.fromNullable(moduleInfo.moduleName)); } return moduleInfos; } public void addExportedPackage(String packaze, String... exportedToModules) { List<String> qualifiedExports; if (exportedToModules != null && exportedToModules.length > 0) { qualifiedExports = Arrays.asList(exportedToModules); } else { qualifiedExports = Collections.singletonList(SootModuleInfo.ALL_MODULES); } exportedPackages.put(PackageNamer.v().get_FixedPackageName(packaze).replace('/', '.'), qualifiedExports); } public void addOpenedPackage(String packaze, String... openedToModules) { List<String> qualifiedOpens; if (openedToModules != null && openedToModules.length > 0) { qualifiedOpens = Arrays.asList(openedToModules); } else { qualifiedOpens = Collections.singletonList(SootModuleInfo.ALL_MODULES); } openedPackages.put(PackageNamer.v().get_FixedPackageName(packaze).replace('/', '.'), qualifiedOpens); } public String getModuleName() { return this.moduleName; } @Override public boolean isConcrete() { return false; } @Override public boolean isExportedByModule() { return true; } @Override public boolean isExportedByModule(String toModule) { return true; } @Override public boolean isOpenedByModule() { return true; } public boolean exportsPackagePublic(String packaze) { return exportsPackage(packaze, ALL_MODULES); } public boolean openPackagePublic(String packaze) { return opensPackage(packaze, ALL_MODULES); } public boolean opensPackage(String packaze, String toModule) { if (SootModuleInfo.MODULE_INFO.equalsIgnoreCase(packaze)) { return true; } // all packages are exported/open to self if (this.getModuleName().equals(toModule)) { return this.modulePackages.contains(packaze); } // all packages in open and automatic modules are open if (this.isAutomaticModule()) { return this.modulePackages.contains(packaze); } List<String> qualifiedOpens = this.openedPackages.get(packaze); if (qualifiedOpens == null) { return false; // if qualifiedExport is null, the package is not exported } if (qualifiedOpens.contains(ALL_MODULES)) { return true; } return (toModule != ALL_MODULES) && qualifiedOpens.contains(toModule); } public boolean exportsPackage(String packaze, String toModule) { if (SootModuleInfo.MODULE_INFO.equalsIgnoreCase(packaze)) { return true; } /// all packages are exported/open to self if (this.getModuleName().equals(toModule)) { return this.modulePackages.contains(packaze); } // a automatic module exports all its packages if (this.isAutomaticModule()) { return this.modulePackages.contains(packaze); } List<String> qualifiedExport = this.exportedPackages.get(packaze); if (qualifiedExport == null) { return false; } if (qualifiedExport.contains(ALL_MODULES)) { return true; } return (toModule != ALL_MODULES) && qualifiedExport.contains(toModule); } public Set<SootModuleInfo> getRequiredPublicModules() { Set<SootModuleInfo> requiredPublic = new HashSet<>(); // check if exported packages is "requires public" for (Map.Entry<SootModuleInfo, Integer> entry : this.requiredModules.entrySet()) { // check if module is reexported via "requires public" if ((entry.getValue() & Modifier.REQUIRES_TRANSITIVE) != 0) { requiredPublic.add(entry.getKey()); } } return requiredPublic; } public void addModulePackage(String packageName) { this.modulePackages.add(packageName); } public boolean moduleContainsPackage(String packageName) { return this.modulePackages.contains(packageName); } }
7,728
28.957364
109
java
soot
soot-master/src/main/java/soot/SootModuleResolver.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-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.base.Optional; /** * Loads symbols for SootClasses from either class files or jimple files. * * @author Andreas Dann */ public class SootModuleResolver extends SootResolver { public SootModuleResolver(Singletons.Global g) { super(g); } public static SootModuleResolver v() { return G.v().soot_SootModuleResolver(); } public SootClass makeClassRef(String className, Optional<String> moduleName) { // If this class name is escaped, we need to un-escape it className = Scene.unescapeName(className); String module = null; if (moduleName.isPresent()) { module = ModuleUtil.v().declaringModule(className, moduleName.get()); } // if no module return first one found final ModuleScene modScene = ModuleScene.v(); if (modScene.containsClass(className, Optional.fromNullable(module))) { return modScene.getSootClass(className, Optional.fromNullable(module)); } SootClass newClass; if (className.endsWith(SootModuleInfo.MODULE_INFO)) { newClass = new SootModuleInfo(className, module); } else { newClass = modScene.makeSootClass(className, module); } newClass.setResolvingLevel(SootClass.DANGLING); modScene.addClass(newClass); return newClass; } @Override public SootClass makeClassRef(String className) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return makeClassRef(wrapper.getClassName(), wrapper.getModuleNameOptional()); } /** * Resolves the given class. Depending on the resolver settings, may decide to resolve other classes as well. If the class * has already been resolved, just returns the class that was already resolved. */ public SootClass resolveClass(String className, int desiredLevel, Optional<String> moduleName) { SootClass resolvedClass = null; try { resolvedClass = makeClassRef(className, moduleName); addToResolveWorklist(resolvedClass, desiredLevel); processResolveWorklist(); return resolvedClass; } catch (SootClassNotFoundException e) { // remove unresolved class and rethrow if (resolvedClass != null) { assert (resolvedClass.resolvingLevel() == SootClass.DANGLING); ModuleScene.v().removeClass(resolvedClass); } throw e; } } @Override public SootClass resolveClass(String className, int desiredLevel) { ModuleUtil.ModuleClassNameWrapper wrapper = ModuleUtil.v().makeWrapper(className); return resolveClass(wrapper.getClassName(), desiredLevel, wrapper.getModuleNameOptional()); } }
3,446
32.794118
124
java
soot
soot-master/src/main/java/soot/SootResolver.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville * Copyright (C) 2004 Ondrej Lhotak, Ganesh Sittampalam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.IOException; import java.io.InputStream; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.JastAddJ.BytecodeParser; import soot.JastAddJ.CompilationUnit; import soot.JastAddJ.JastAddJavaParser; import soot.JastAddJ.JavaParser; import soot.JastAddJ.Program; import soot.javaToJimple.IInitialResolver.Dependencies; import soot.options.Options; import soot.util.ConcurrentHashMultiMap; import soot.util.MultiMap; /** Loads symbols for SootClasses from either class files or jimple files. */ public class SootResolver { private static final Logger logger = LoggerFactory.getLogger(SootResolver.class); /** Maps each resolved class to a list of all references in it. */ protected MultiMap<SootClass, Type> classToTypesSignature = new ConcurrentHashMultiMap<SootClass, Type>(); /** Maps each resolved class to a list of all references in it. */ protected MultiMap<SootClass, Type> classToTypesHierarchy = new ConcurrentHashMultiMap<SootClass, Type>(); /** SootClasses waiting to be resolved. */ @SuppressWarnings("unchecked") private final Deque<SootClass>[] worklist = new Deque[4]; private Program program = null; public SootResolver(Singletons.Global g) { worklist[SootClass.HIERARCHY] = new ArrayDeque<SootClass>(); worklist[SootClass.SIGNATURES] = new ArrayDeque<SootClass>(); worklist[SootClass.BODIES] = new ArrayDeque<SootClass>(); } protected void initializeProgram() { if (Options.v().src_prec() != Options.src_prec_apk_c_j) { program = new Program(); program.state().reset(); program.initBytecodeReader(new BytecodeParser()); program.initJavaParser(new JavaParser() { @Override public CompilationUnit parse(InputStream is, String fileName) throws IOException, beaver.Parser.Exception { return new JastAddJavaParser().parse(is, fileName); } }); final soot.JastAddJ.Options options = program.options(); options.initOptions(); options.addKeyValueOption("-classpath"); options.setValueForOption(Scene.v().getSootClassPath(), "-classpath"); switch (Options.v().src_prec()) { case Options.src_prec_java: program.setSrcPrec(Program.SRC_PREC_JAVA); break; case Options.src_prec_class: program.setSrcPrec(Program.SRC_PREC_CLASS); break; case Options.src_prec_only_class: program.setSrcPrec(Program.SRC_PREC_CLASS); break; default: break; } program.initPaths(); } } public static SootResolver v() { if (ModuleUtil.module_mode()) { return G.v().soot_SootModuleResolver(); } else { return G.v().soot_SootResolver(); } } /** Returns true if we are resolving all class refs recursively. */ protected boolean resolveEverything() { final Options opts = Options.v(); if (opts.on_the_fly()) { return false; } else { return (opts.whole_program() || opts.whole_shimple() || opts.full_resolver() || opts.output_format() == Options.output_format_dava); } } /** * Returns a (possibly not yet resolved) SootClass to be used in references to a class. If/when the class is resolved, it * will be resolved into this SootClass. */ public SootClass makeClassRef(String className) { final Scene scene = Scene.v(); if (scene.containsClass(className)) { return scene.getSootClass(className); } else { SootClass newClass; if (className.endsWith(SootModuleInfo.MODULE_INFO)) { newClass = new SootModuleInfo(className, null); } else { newClass = new SootClass(className); } newClass.setResolvingLevel(SootClass.DANGLING); scene.addClass(newClass); return newClass; } } /** * Resolves the given class. Depending on the resolver settings, may decide to resolve other classes as well. If the class * has already been resolved, just returns the class that was already resolved. */ public SootClass resolveClass(String className, int desiredLevel) { SootClass resolvedClass = null; try { resolvedClass = makeClassRef(className); addToResolveWorklist(resolvedClass, desiredLevel); processResolveWorklist(); return resolvedClass; } catch (SootClassNotFoundException e) { // remove unresolved class and rethrow if (resolvedClass != null) { assert (resolvedClass.resolvingLevel() == SootClass.DANGLING); Scene.v().removeClass(resolvedClass); } throw e; } } /** Resolve all classes on toResolveWorklist. */ protected void processResolveWorklist() { final Scene scene = Scene.v(); final boolean resolveEverything = resolveEverything(); final boolean no_bodies_for_excluded = Options.v().no_bodies_for_excluded(); for (int i = SootClass.BODIES; i >= SootClass.HIERARCHY; i--) { Deque<SootClass> currWorklist = worklist[i]; while (!currWorklist.isEmpty()) { SootClass sc = currWorklist.pop(); if (resolveEverything) { // Whole program mode boolean onlySignatures = sc.isPhantom() || (no_bodies_for_excluded && scene.isExcluded(sc) && !scene.isBasicClass(sc.getName())); if (onlySignatures) { bringToSignatures(sc); sc.setPhantomClass(); for (SootMethod m : sc.getMethods()) { m.setPhantom(true); } for (SootField f : sc.getFields()) { f.setPhantom(true); } } else { bringToBodies(sc); } } else { // No transitive switch (i) { case SootClass.BODIES: bringToBodies(sc); break; case SootClass.SIGNATURES: bringToSignatures(sc); break; case SootClass.HIERARCHY: bringToHierarchy(sc); break; } } } // The ArrayDeque can grow particularly large but the implementation will // never shrink the backing array, leaving a possibly large memory leak. worklist[i] = new ArrayDeque<SootClass>(0); } } protected void addToResolveWorklist(Type type, int level) { // We go from Type -> SootClass directly, since RefType.getSootClass // calls makeClassRef anyway if (type instanceof RefType) { addToResolveWorklist(((RefType) type).getSootClass(), level); } else if (type instanceof ArrayType) { addToResolveWorklist(((ArrayType) type).baseType, level); } // Other types ignored } protected void addToResolveWorklist(SootClass sc, int desiredLevel) { if (sc.resolvingLevel() >= desiredLevel) { return; } worklist[desiredLevel].add(sc); } /** * Hierarchy - we know the hierarchy of the class and that's it requires at least Hierarchy for all supertypes and * enclosing types. */ protected void bringToHierarchy(SootClass sc) { if (sc.resolvingLevel() >= SootClass.HIERARCHY) { return; } if (Options.v().debug_resolver()) { logger.debug("bringing to HIERARCHY: " + sc); } sc.setResolvingLevel(SootClass.HIERARCHY); bringToHierarchyUnchecked(sc); } protected void bringToHierarchyUnchecked(SootClass sc) { String className = sc.getName(); ClassSource is; if (ModuleUtil.module_mode()) { is = ModulePathSourceLocator.v().getClassSource(className, com.google.common.base.Optional.fromNullable(sc.moduleName)); } else { is = SourceLocator.v().getClassSource(className); } try { boolean modelAsPhantomRef = (is == null); if (modelAsPhantomRef) { if (!Scene.v().allowsPhantomRefs()) { String suffix = ""; if ("java.lang.Object".equals(className)) { suffix = " Try adding rt.jar to Soot's classpath, e.g.:\n" + "java -cp sootclasses.jar soot.Main -cp " + ".:/path/to/jdk/jre/lib/rt.jar <other options>"; } else if ("javax.crypto.Cipher".equals(className)) { suffix = " Try adding jce.jar to Soot's classpath, e.g.:\n" + "java -cp sootclasses.jar soot.Main -cp " + ".:/path/to/jdk/jre/lib/rt.jar:/path/to/jdk/jre/lib/jce.jar <other options>"; } throw new SootClassNotFoundException( "couldn't find class: " + className + " (is your soot-class-path set properly?)" + suffix); } else { // logger.warn(className + " is a phantom class!"); sc.setPhantomClass(); } } else { Dependencies dependencies = is.resolve(sc); if (!dependencies.typesToSignature.isEmpty()) { classToTypesSignature.putAll(sc, dependencies.typesToSignature); } if (!dependencies.typesToHierarchy.isEmpty()) { classToTypesHierarchy.putAll(sc, dependencies.typesToHierarchy); } } } finally { if (is != null) { is.close(); } } reResolveHierarchy(sc, SootClass.HIERARCHY); } public void reResolveHierarchy(SootClass sc, int level) { // Bring superclasses to hierarchy SootClass superClass = sc.getSuperclassUnsafe(); if (superClass != null) { addToResolveWorklist(superClass, level); } SootClass outerClass = sc.getOuterClassUnsafe(); if (outerClass != null) { addToResolveWorklist(outerClass, level); } for (SootClass iface : sc.getInterfaces()) { addToResolveWorklist(iface, level); } } /** * Signatures - we know the signatures of all methods and fields requires at least Hierarchy for all referred to types in * these signatures. */ protected void bringToSignatures(SootClass sc) { if (sc.resolvingLevel() >= SootClass.SIGNATURES) { return; } bringToHierarchy(sc); if (Options.v().debug_resolver()) { logger.debug("bringing to SIGNATURES: " + sc); } sc.setResolvingLevel(SootClass.SIGNATURES); bringToSignaturesUnchecked(sc); } protected void bringToSignaturesUnchecked(SootClass sc) { for (SootField f : sc.getFields()) { addToResolveWorklist(f.getType(), SootClass.HIERARCHY); } for (SootMethod m : sc.getMethods()) { addToResolveWorklist(m.getReturnType(), SootClass.HIERARCHY); for (Type ptype : m.getParameterTypes()) { addToResolveWorklist(ptype, SootClass.HIERARCHY); } List<SootClass> exceptions = m.getExceptionsUnsafe(); if (exceptions != null) { for (SootClass exception : exceptions) { addToResolveWorklist(exception, SootClass.HIERARCHY); } } } // Bring superclasses to signatures reResolveHierarchy(sc, SootClass.SIGNATURES); } /** * Bodies - we can now start loading the bodies of methods for all referred to methods and fields in the bodies, requires * signatures for the method receiver and field container, and hierarchy for all other classes referenced in method * references. Current implementation does not distinguish between the receiver and other references. Therefore, it is * conservative and brings all of them to signatures. But this could/should be improved. */ protected void bringToBodies(SootClass sc) { if (sc.resolvingLevel() >= SootClass.BODIES) { return; } bringToSignatures(sc); if (Options.v().debug_resolver()) { logger.debug("bringing to BODIES: " + sc); } sc.setResolvingLevel(SootClass.BODIES); bringToBodiesUnchecked(sc); } protected void bringToBodiesUnchecked(SootClass sc) { { Collection<Type> references = classToTypesHierarchy.get(sc); if (references != null) { // This must be an iterator, not a for-all since the underlying // collection may change as we go for (Type t : references) { addToResolveWorklist(t, SootClass.HIERARCHY); } } } { Collection<Type> references = classToTypesSignature.get(sc); if (references != null) { // This must be an iterator, not a for-all since the underlying // collection may change as we go for (Type t : references) { addToResolveWorklist(t, SootClass.SIGNATURES); } } } } public void reResolve(SootClass cl, int newResolvingLevel) { int resolvingLevel = cl.resolvingLevel(); if (resolvingLevel >= newResolvingLevel) { return; } reResolveHierarchy(cl, SootClass.HIERARCHY); cl.setResolvingLevel(newResolvingLevel); addToResolveWorklist(cl, resolvingLevel); processResolveWorklist(); } public void reResolve(SootClass cl) { reResolve(cl, SootClass.HIERARCHY); } public Program getProgram() { if (program == null) { initializeProgram(); } return program; } public class SootClassNotFoundException extends RuntimeException { /** * */ private static final long serialVersionUID = 1563461446590293827L; public SootClassNotFoundException(String s) { super(s); } } }
14,081
32.93253
124
java
soot
soot-master/src/main/java/soot/SourceLocator.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.jf.dexlib2.iface.DexFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.JavaClassProvider.JarException; import soot.asm.AsmClassProvider; import soot.asm.AsmJava9ClassProvider; import soot.dexpler.DexFileProvider; import soot.options.Options; /** * Provides utility methods to retrieve an input stream for a class name, given a classfile, or jimple or baf output files. */ public class SourceLocator { private static final Logger logger = LoggerFactory.getLogger(SourceLocator.class); protected Set<ClassLoader> additionalClassLoaders = new HashSet<ClassLoader>(); protected List<ClassProvider> classProviders; protected List<String> classPath; private List<String> sourcePath; protected boolean java9Mode = false; protected final LoadingCache<String, ClassSourceType> pathToSourceType = CacheBuilder.newBuilder().initialCapacity(60).maximumSize(500).softValues() .concurrencyLevel(Runtime.getRuntime().availableProcessors()).build(new CacheLoader<String, ClassSourceType>() { @Override public ClassSourceType load(String path) throws Exception { File f = new File(path); if (!f.exists() && !Options.v().ignore_classpath_errors()) { throw new Exception("Error: The path '" + path + "' does not exist."); } if (!f.canRead() && !Options.v().ignore_classpath_errors()) { throw new Exception("Error: The path '" + path + "' exists but is not readable."); } if (f.isFile()) { if (path.endsWith(".zip")) { return ClassSourceType.zip; } else if (path.endsWith(".jar")) { return ClassSourceType.jar; } else if (Scene.isApk(new File(path))) { return ClassSourceType.apk; } else if (path.endsWith(".dex")) { return ClassSourceType.dex; } else { return ClassSourceType.unknown; } } return ClassSourceType.directory; } }); protected final LoadingCache<String, Set<String>> archivePathsToEntriesCache = CacheBuilder.newBuilder().initialCapacity(60).maximumSize(500).softValues() .concurrencyLevel(Runtime.getRuntime().availableProcessors()).build(new CacheLoader<String, Set<String>>() { @Override public Set<String> load(String archivePath) throws Exception { ZipFile archive = null; try { archive = new ZipFile(archivePath); Set<String> ret = new HashSet<String>(); Enumeration<? extends ZipEntry> it = archive.entries(); while (it.hasMoreElements()) { ret.add(it.nextElement().getName()); } return ret; } finally { if (archive != null) { archive.close(); } } } }); /** * Set containing all dex files that were appended to the classpath later on. The classes from these files are not yet * loaded and are still missing from dexClassIndex. */ private Set<String> dexClassPathExtensions; /** * The index that maps classes to the files they are defined in. This is necessary because a dex file can hold multiple * classes. */ private Map<String, File> dexClassIndex; public SourceLocator(Singletons.Global g) { } public static SourceLocator v() { if (ModuleUtil.module_mode()) { return G.v().soot_ModulePathSourceLocator(); } return G.v().soot_SourceLocator(); } /** * Create the given directory and all parent directories if {@code dir} is non-null. * * @param dir */ public static void ensureDirectoryExists(File dir) { if (dir != null && !dir.exists()) { try { dir.mkdirs(); } catch (SecurityException se) { logger.debug("Unable to create " + dir); throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED); } } } /** * Explodes a class path into a list of individual class path entries. */ public static List<String> explodeClassPath(String classPath) { List<String> ret = new ArrayList<String>(); // the classpath is split at every path separator which is not escaped String regex = "(?<!\\\\)" + Pattern.quote(File.pathSeparator); for (String originalDir : classPath.split(regex)) { try { String canonicalDir = new File(originalDir).getCanonicalPath(); if (originalDir.equals(ModulePathSourceLocator.DUMMY_CLASSPATH_JDK9_FS)) { SourceLocator.v().java9Mode = true; continue; } ret.add(canonicalDir); } catch (IOException e) { throw new CompilationDeathException("Couldn't resolve classpath entry " + originalDir + ": " + e); } } return ret; } /** * Given a class name, uses the soot-class-path to return a ClassSource for the given class. */ public ClassSource getClassSource(String className) { if (classPath == null) { classPath = explodeClassPath(Scene.v().getSootClassPath()); } if (classProviders == null) { setupClassProviders(); } JarException ex = null; for (ClassProvider cp : classProviders) { try { ClassSource ret = cp.find(className); if (ret != null) { return ret; } } catch (JarException e) { ex = e; } } if (ex != null) { throw ex; } for (final ClassLoader cl : additionalClassLoaders) { try { ClassSource ret = new ClassProvider() { @Override public ClassSource find(String className) { String fileName = className.replace('.', '/') + ".class"; InputStream stream = cl.getResourceAsStream(fileName); if (stream == null) { return null; } return new CoffiClassSource(className, stream, fileName); } }.find(className); if (ret != null) { return ret; } } catch (JarException e) { ex = e; } } if (ex != null) { throw ex; } if (className.startsWith("soot.rtlib.tamiflex.")) { String fileName = className.replace('.', '/') + ".class"; ClassLoader cl = getClass().getClassLoader(); if (cl == null) { return null; } InputStream stream = cl.getResourceAsStream(fileName); if (stream != null) { return new CoffiClassSource(className, stream, fileName); } } return null; } public void additionalClassLoader(ClassLoader c) { additionalClassLoaders.add(c); } protected void setupClassProviders() { classProviders = new LinkedList<ClassProvider>(); ClassProvider classFileClassProvider = Options.v().coffi() ? new CoffiClassProvider() : new AsmClassProvider(); if (this.java9Mode) { classProviders.add(new AsmJava9ClassProvider()); } switch (Options.v().src_prec()) { case Options.src_prec_class: classProviders.add(classFileClassProvider); classProviders.add(new JimpleClassProvider()); classProviders.add(new JavaClassProvider()); break; case Options.src_prec_only_class: classProviders.add(classFileClassProvider); break; case Options.src_prec_java: classProviders.add(new JavaClassProvider()); classProviders.add(classFileClassProvider); classProviders.add(new JimpleClassProvider()); break; case Options.src_prec_jimple: classProviders.add(new JimpleClassProvider()); classProviders.add(classFileClassProvider); classProviders.add(new JavaClassProvider()); break; case Options.src_prec_apk: classProviders.add(new DexClassProvider()); classProviders.add(classFileClassProvider); classProviders.add(new JavaClassProvider()); classProviders.add(new JimpleClassProvider()); break; case Options.src_prec_apk_c_j: classProviders.add(new DexClassProvider()); classProviders.add(classFileClassProvider); classProviders.add(new JimpleClassProvider()); break; default: throw new RuntimeException("Other source precedences are not currently supported."); } } public void setClassProviders(List<ClassProvider> classProviders) { this.classProviders = classProviders; } public List<String> classPath() { return classPath; } public void invalidateClassPath() { classPath = null; dexClassIndex = null; } public List<String> sourcePath() { if (sourcePath == null) { sourcePath = new ArrayList<String>(); for (String dir : classPath) { ClassSourceType cst = getClassSourceType(dir); if (cst != ClassSourceType.apk && cst != ClassSourceType.jar && cst != ClassSourceType.zip) { sourcePath.add(dir); } } } return sourcePath; } protected ClassSourceType getClassSourceType(String path) { try { return pathToSourceType.get(path); } catch (Exception e) { throw new RuntimeException(e); } } public List<String> getClassesUnder(String aPath) { return getClassesUnder(aPath, ""); } public List<String> getClassesUnder(String aPath, String prefix) { List<String> classes = new ArrayList<String>(); // FIXME: AD the dummy_classpath_variable should be replaced with a more stable concept if (aPath.equals(ModulePathSourceLocator.DUMMY_CLASSPATH_JDK9_FS)) { Collection<List<String>> values = ModulePathSourceLocator.v().getClassUnderModulePath("jrt:/").values(); ArrayList<String> foundClasses = new ArrayList<>(); for (List<String> classesInModule : values) { foundClasses.addAll(classesInModule); } return foundClasses; } ClassSourceType cst = getClassSourceType(aPath); // Get the dex file from an apk if (cst == ClassSourceType.apk || cst == ClassSourceType.dex) { try { for (DexFileProvider.DexContainer<? extends DexFile> dex : DexFileProvider.v().getDexFromSource(new File(aPath))) { classes.addAll(DexClassProvider.classesOfDex(dex.getBase().getDexFile())); } } catch (IOException e) { throw new CompilationDeathException("Error reading dex source", e); } } // load Java class files from ZIP and JAR else if (cst == ClassSourceType.jar || cst == ClassSourceType.zip) { ZipFile archive = null; try { archive = new ZipFile(aPath); for (Enumeration<? extends ZipEntry> entries = archive.entries(); entries.hasMoreElements();) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName.endsWith(".class") || entryName.endsWith(".jimple")) { int extensionIndex = entryName.lastIndexOf('.'); entryName = entryName.substring(0, extensionIndex); entryName = entryName.replace('/', '.'); classes.add(prefix + entryName); } } } catch (Throwable e) { throw new CompilationDeathException("Error reading archive '" + aPath + "'", e); } finally { try { if (archive != null) { archive.close(); } } catch (Throwable t) { logger.debug("" + t.getMessage()); } } // we might have dex files inside the archive try { for (DexFileProvider.DexContainer<? extends DexFile> container : DexFileProvider.v() .getDexFromSource(new File(aPath))) { classes.addAll(DexClassProvider.classesOfDex(container.getBase().getDexFile())); } } catch (CompilationDeathException e) { // There might be cases where there is no dex file within a JAR or ZIP file... } catch (IOException e) { /* Ignore unreadable files */ logger.debug("" + e.getMessage()); } } else if (cst == ClassSourceType.directory) { File file = new File(aPath); File[] files = file.listFiles(); if (files == null) { files = new File[1]; files[0] = file; } for (File element : files) { if (element.isDirectory()) { classes.addAll(getClassesUnder(aPath + File.separatorChar + element.getName(), prefix + element.getName() + ".")); } else { String fileName = element.getName(); if (fileName.endsWith(".class")) { int index = fileName.lastIndexOf(".class"); classes.add(prefix + fileName.substring(0, index)); } else if (fileName.endsWith(".jimple")) { int index = fileName.lastIndexOf(".jimple"); classes.add(prefix + fileName.substring(0, index)); } else if (fileName.endsWith(".java")) { int index = fileName.lastIndexOf(".java"); classes.add(prefix + fileName.substring(0, index)); } else if (fileName.endsWith(".dex")) { try { for (DexFileProvider.DexContainer<? extends DexFile> container : DexFileProvider.v() .getDexFromSource(element)) { classes.addAll(DexClassProvider.classesOfDex(container.getBase().getDexFile())); } } catch (IOException e) { /* Ignore unreadable files */ logger.debug("" + e.getMessage()); } } } } } else { throw new RuntimeException("Invalid class source type"); } return classes; } public String getFileNameFor(SootClass c, int rep) { if (rep == Options.output_format_none) { return null; } StringBuffer b = new StringBuffer(); if (!Options.v().output_jar()) { b.append(getOutputDir()); } if ((b.length() > 0) && (b.charAt(b.length() - 1) != File.separatorChar)) { b.append(File.separatorChar); } if (rep != Options.output_format_dava) { if (rep == Options.output_format_class) { b.append(c.getName().replace('.', File.separatorChar)); } else if (rep == Options.output_format_template) { b.append(c.getName().replace('.', '_')); b.append("_Maker"); } else { // Generate tree structure for Jimple output or generation // fails for deep hierarchies ("file name too long"). if (Options.v().hierarchy_dirs() && (rep == Options.output_format_jimple || rep == Options.output_format_shimple)) { b.append(c.getName().replace('.', File.separatorChar)); } else { b.append(c.getName()); } } b.append(getExtensionFor(rep)); return b.toString(); } return getDavaFilenameFor(c, b); } private String getDavaFilenameFor(SootClass c, StringBuffer b) { b.append("dava"); b.append(File.separatorChar); ensureDirectoryExists(new File(b.toString() + "classes")); b.append("src"); b.append(File.separatorChar); String fixedPackageName = c.getJavaPackageName(); if (!fixedPackageName.equals("")) { b.append(fixedPackageName.replace('.', File.separatorChar)); b.append(File.separatorChar); } ensureDirectoryExists(new File(b.toString())); b.append(c.getShortJavaStyleName()); b.append(".java"); return b.toString(); } /* This is called after sootClassPath has been defined. */ public Set<String> classesInDynamicPackage(String str) { HashSet<String> set = new HashSet<String>(0); StringTokenizer strtok = new StringTokenizer(Scene.v().getSootClassPath(), String.valueOf(File.pathSeparatorChar)); while (strtok.hasMoreTokens()) { String path = strtok.nextToken(); if (getClassSourceType(path) != ClassSourceType.directory) { continue; } // For jimple files List<String> l = getClassesUnder(path); for (String filename : l) { if (filename.startsWith(str)) { set.add(filename); } } // For class files; path = path + File.separatorChar; StringTokenizer tokenizer = new StringTokenizer(str, "."); while (tokenizer.hasMoreTokens()) { path = path + tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) { path = path + File.separatorChar; } } l = getClassesUnder(path); for (String string : l) { set.add(str + "." + string); } } return set; } public String getExtensionFor(int rep) { switch (rep) { case Options.output_format_baf: return ".baf"; case Options.output_format_b: return ".b"; case Options.output_format_jimple: return ".jimple"; case Options.output_format_jimp: return ".jimp"; case Options.output_format_shimple: return ".shimple"; case Options.output_format_shimp: return ".shimp"; case Options.output_format_grimp: return ".grimp"; case Options.output_format_grimple: return ".grimple"; case Options.output_format_class: return ".class"; case Options.output_format_dava: return ".java"; case Options.output_format_jasmin: return ".jasmin"; case Options.output_format_xml: return ".xml"; case Options.output_format_template: return ".java"; case Options.output_format_asm: return ".asm"; default: throw new RuntimeException(); } } /** * Returns the output directory given by {@link Options} or a default if not set. Also ensures that all directories in the * path exist. * * @return the output directory from {@link Options} or a default if not set */ public String getOutputDir() { File dir; if (Options.v().output_dir().length() == 0) { // Default if -output-dir was not set dir = new File("sootOutput"); } else { dir = new File(Options.v().output_dir()); // If a Jar name was given as the output dir // get its parent path (possibly empty) if (dir.getPath().endsWith(".jar")) { dir = dir.getParentFile(); if (dir == null) { dir = new File(""); } } } ensureDirectoryExists(dir); return dir.getPath(); } /** * If {@link Options#v()#output_jar()} is set, returns the name of the jar file to which the output will be written. The * name of the jar file can be given with the -output-dir option or a default will be used. Also ensures that all * directories in the path exist. * * @return the name of the Jar file to which outputs are written */ public String getOutputJarName() { if (!Options.v().output_jar()) { return ""; } File dir; if (Options.v().output_dir().length() == 0) { // Default if -output-dir was not set dir = new File("sootOutput/out.jar"); } else { dir = new File(Options.v().output_dir()); // If a Jar name was not given, then supply default if (!dir.getPath().endsWith(".jar")) { dir = new File(dir.getPath(), "out.jar"); } } ensureDirectoryExists(dir.getParentFile()); return dir.getPath(); } /** * Searches for a file with the given name in the exploded classPath. */ public FoundFile lookupInClassPath(String fileName) { for (String dir : classPath) { FoundFile ret = null; ClassSourceType cst = getClassSourceType(dir); if (cst == ClassSourceType.zip || cst == ClassSourceType.jar) { ret = lookupInArchive(dir, fileName); } else if (cst == ClassSourceType.directory) { ret = lookupInDir(dir, fileName); } if (ret != null) { return ret; } } return null; } protected FoundFile lookupInDir(String dir, String fileName) { File f = new File(dir, fileName); if (f.exists() && f.canRead()) { return new FoundFile(f); } return null; } protected FoundFile lookupInArchive(String archivePath, String fileName) { Set<String> entryNames = null; try { entryNames = archivePathsToEntriesCache.get(archivePath); } catch (Exception e) { throw new RuntimeException( "Error: Failed to retrieve the archive entries list for the archive at path '" + archivePath + "'.", e); } if (entryNames.contains(fileName)) { return new FoundFile(archivePath, fileName); } return null; } /** * Returns the name of the class in which the (possibly inner) class className appears. */ public String getSourceForClass(String className) { String javaClassName = className; int i = className.indexOf("$"); if (i > -1) { // class is an inner class and will be in // Outer of Outer$Inner javaClassName = className.substring(0, i); } return javaClassName; } /** * Return the dex class index that maps class names to files * * @return the index */ public Map<String, File> dexClassIndex() { return dexClassIndex; } /** * Set the dex class index * * @param index * the index */ public void setDexClassIndex(Map<String, File> index) { dexClassIndex = index; } public void extendClassPath(String newPathElement) { classPath = null; if (newPathElement.endsWith(".dex") || newPathElement.endsWith(".apk")) { if (dexClassPathExtensions == null) { dexClassPathExtensions = new HashSet<String>(); } dexClassPathExtensions.add(newPathElement); } } /** * Gets all files that were added to the classpath later on and that have not yet been processed for the dexClassIndex * mapping * * @return The set of dex or apk files that still need to be indexed */ public Set<String> getDexClassPathExtensions() { return this.dexClassPathExtensions; } /** * Clears the set of dex or apk files that still need to be indexed */ public void clearDexClassPathExtensions() { this.dexClassPathExtensions = null; } protected enum ClassSourceType { jar, zip, apk, dex, directory, jrt, unknown } }
23,660
32.138655
124
java
soot
soot-master/src/main/java/soot/StmtAddressType.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Soot representation of the Java type for a statement address. Implemented as a singleton. */ @SuppressWarnings("serial") public class StmtAddressType extends Type { public StmtAddressType(Singletons.Global g) { } public static StmtAddressType v() { return G.v().soot_StmtAddressType(); } @Override public boolean equals(Object t) { return this == t; } @Override public int hashCode() { return 0x74F368D1; } @Override public String toString() { return "address"; } @Override public void apply(Switch sw) { ((TypeSwitch) sw).caseStmtAddressType(this); } }
1,468
23.483333
92
java
soot
soot-master/src/main/java/soot/Timer.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static java.lang.System.gc; import static java.lang.System.nanoTime; import soot.options.Options; /** * Utility class providing a timer. Used for profiling various phases of Sootification. */ public class Timer { private long duration; private long startTime; private boolean hasStarted; private String name; /** Creates a new timer with the given name. */ public Timer(String name) { this.name = name; duration = 0; } /** Creates a new timer. */ public Timer() { this("unnamed"); } static void doGarbageCollecting() { final G g = G.v(); // Subtract garbage collection time if (g.Timer_isGarbageCollecting) { return; } if (!Options.v().subtract_gc()) { return; } // garbage collects only every 4 calls to avoid round off errors if ((g.Timer_count++ % 4) != 0) { return; } g.Timer_isGarbageCollecting = true; g.Timer_forcedGarbageCollectionTimer.start(); // Stop all outstanding timers for (Timer t : g.Timer_outstandingTimers) { t.end(); } gc(); // Start all outstanding timers for (Timer t : g.Timer_outstandingTimers) { t.start(); } g.Timer_forcedGarbageCollectionTimer.end(); g.Timer_isGarbageCollecting = false; } /** Starts the given timer. */ public void start() { doGarbageCollecting(); startTime = nanoTime(); if (hasStarted) { throw new RuntimeException("timer " + name + " has already been started!"); } hasStarted = true; if (!G.v().Timer_isGarbageCollecting) { synchronized (G.v().Timer_outstandingTimers) { G.v().Timer_outstandingTimers.add(this); } } } /** Returns the name of the current timer. */ public String toString() { return name; } /** Stops the current timer. */ public void end() { if (!hasStarted) { throw new RuntimeException("timer " + name + " has not been started!"); } hasStarted = false; duration += nanoTime() - startTime; if (!G.v().Timer_isGarbageCollecting) { synchronized (G.v().Timer_outstandingTimers) { G.v().Timer_outstandingTimers.remove(this); } } } /** Returns the sum of the intervals start()-end() of the current timer. */ public long getTime() { return duration / 1000000L; } }
3,163
22.789474
87
java
soot
soot-master/src/main/java/soot/Timers.java
package soot; /*- * #%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.text.DecimalFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.options.Options; public class Timers { private static final Logger logger = LoggerFactory.getLogger(Timers.class); public Timers(Singletons.Global g) { } public static Timers v() { return G.v().soot_Timers(); } public int totalFlowNodes; public int totalFlowComputations; public Timer copiesTimer = new Timer("copies"); public Timer defsTimer = new Timer("defs"); public Timer usesTimer = new Timer("uses"); public Timer liveTimer = new Timer("live"); public Timer splitTimer = new Timer("split"); public Timer packTimer = new Timer("pack"); public Timer cleanup1Timer = new Timer("cleanup1"); public Timer cleanup2Timer = new Timer("cleanup2"); public Timer conversionTimer = new Timer("conversion"); public Timer cleanupAlgorithmTimer = new Timer("cleanupAlgorithm"); public Timer graphTimer = new Timer("graphTimer"); public Timer assignTimer = new Timer("assignTimer"); public Timer resolveTimer = new Timer("resolveTimer"); public Timer totalTimer = new Timer("totalTimer"); public Timer splitPhase1Timer = new Timer("splitPhase1"); public Timer splitPhase2Timer = new Timer("splitPhase2"); public Timer usePhase1Timer = new Timer("usePhase1"); public Timer usePhase2Timer = new Timer("usePhase2"); public Timer usePhase3Timer = new Timer("usePhase3"); public Timer defsSetupTimer = new Timer("defsSetup"); public Timer defsAnalysisTimer = new Timer("defsAnalysis"); public Timer defsPostTimer = new Timer("defsPost"); public Timer liveSetupTimer = new Timer("liveSetup"); public Timer liveAnalysisTimer = new Timer("liveAnalysis"); public Timer livePostTimer = new Timer("livePost"); public Timer aggregationTimer = new Timer("aggregation"); public Timer grimpAggregationTimer = new Timer("grimpAggregation"); public Timer deadCodeTimer = new Timer("deadCode"); public Timer propagatorTimer = new Timer("propagator"); public Timer buildJasminTimer = new Timer("buildjasmin"); public Timer assembleJasminTimer = new Timer("assembling jasmin"); public Timer resolverTimer = new Timer("resolver"); public int conversionLocalCount; public int cleanup1LocalCount; public int splitLocalCount; public int assignLocalCount; public int packLocalCount; public int cleanup2LocalCount; public int conversionStmtCount; public int cleanup1StmtCount; public int splitStmtCount; public int assignStmtCount; public int packStmtCount; public int cleanup2StmtCount; public long stmtCount; public Timer fieldTimer = new soot.Timer(); public Timer methodTimer = new soot.Timer(); public Timer attributeTimer = new soot.Timer(); public Timer locatorTimer = new soot.Timer(); public Timer readTimer = new soot.Timer(); public Timer orderComputation = new soot.Timer("orderComputation"); public void printProfilingInformation() { long totalTime = totalTimer.getTime(); logger.debug("Time measurements"); logger.debug(" Building graphs: " + toTimeString(graphTimer, totalTime)); logger.debug(" Computing LocalDefs: " + toTimeString(defsTimer, totalTime)); // logger.debug(" setup: " + toTimeString(defsSetupTimer, totalTime)); // logger.debug(" analysis: " + toTimeString(defsAnalysisTimer, totalTime)); // logger.debug(" post: " + toTimeString(defsPostTimer, totalTime)); logger.debug(" Computing LocalUses: " + toTimeString(usesTimer, totalTime)); // logger.debug(" Use phase1: " + toTimeString(usePhase1Timer, totalTime)); // logger.debug(" Use phase2: " + toTimeString(usePhase2Timer, totalTime)); // logger.debug(" Use phase3: " + toTimeString(usePhase3Timer, totalTime)); logger.debug(" Cleaning up code: " + toTimeString(cleanupAlgorithmTimer, totalTime)); logger.debug("Computing LocalCopies: " + toTimeString(copiesTimer, totalTime)); logger.debug(" Computing LiveLocals: " + toTimeString(liveTimer, totalTime)); // logger.debug(" setup: " + toTimeString(liveSetupTimer, totalTime)); // logger.debug(" analysis: " + toTimeString(liveAnalysisTimer, totalTime)); // logger.debug(" post: " + toTimeString(livePostTimer, totalTime)); logger.debug("Coading coffi structs: " + toTimeString(resolveTimer, totalTime)); // Print out time stats. { float timeInSecs; logger.debug(" Resolving classfiles: " + toTimeString(resolverTimer, totalTime)); logger.debug(" Bytecode -> jimple (naive): " + toTimeString(conversionTimer, totalTime)); logger.debug(" Splitting variables: " + toTimeString(splitTimer, totalTime)); logger.debug(" Assigning types: " + toTimeString(assignTimer, totalTime)); logger.debug(" Propagating copies & csts: " + toTimeString(propagatorTimer, totalTime)); logger.debug(" Eliminating dead code: " + toTimeString(deadCodeTimer, totalTime)); logger.debug(" Aggregation: " + toTimeString(aggregationTimer, totalTime)); logger.debug(" Coloring locals: " + toTimeString(packTimer, totalTime)); logger.debug(" Generating jasmin code: " + toTimeString(buildJasminTimer, totalTime)); logger.debug(" .jasmin -> .class: " + toTimeString(assembleJasminTimer, totalTime)); // logger.debug(" Cleaning up code: " + toTimeString(cleanup1Timer, totalTime) + // "\t" + cleanup1LocalCount + " locals " + cleanup1StmtCount + " stmts"); // logger.debug(" Split phase1: " + toTimeString(splitPhase1Timer, totalTime)); // logger.debug(" Split phase2: " + toTimeString(splitPhase2Timer, totalTime)); /* * logger.debug("cleanup2Timer: " + cleanup2Time + "(" + (cleanup2Time * 100 / totalTime) + "%) " + * cleanup2LocalCount + " locals " + cleanup2StmtCount + " stmts"); */ timeInSecs = totalTime / 1000.0f; // float memoryUsed = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000.0f; logger.debug("totalTime:" + toTimeString(totalTimer, totalTime)); if (Options.v().subtract_gc()) { logger.debug("Garbage collection was subtracted from these numbers."); logger.debug(" forcedGC:" + toTimeString(G.v().Timer_forcedGarbageCollectionTimer, totalTime)); } logger.debug("stmtCount: " + stmtCount + "(" + toFormattedString(stmtCount / timeInSecs) + " stmt/s)"); logger.debug("totalFlowNodes: " + totalFlowNodes + " totalFlowComputations: " + totalFlowComputations + " avg: " + truncatedOf((double) totalFlowComputations / totalFlowNodes, 2)); } } private String toTimeString(Timer timer, long totalTime) { DecimalFormat format = new DecimalFormat("00.0"); DecimalFormat percFormat = new DecimalFormat("00.0"); long time = timer.getTime(); String timeString = format.format(time / 1000.0); // paddedLeftOf(new Double(truncatedOf(time / 1000.0, 1)).toString(), // 5); return (timeString + "s" + " (" + percFormat.format(time * 100.0 / totalTime) + "%" + ")"); } private String toFormattedString(double value) { return paddedLeftOf(new Double(truncatedOf(value, 2)).toString(), 5); } public double truncatedOf(double d, int numDigits) { double multiplier = 1; for (int i = 0; i < numDigits; i++) { multiplier *= 10; } return ((long) (d * multiplier)) / multiplier; } public String paddedLeftOf(String s, int length) { if (s.length() >= length) { return s; } else { int diff = length - s.length(); char[] padding = new char[diff]; for (int i = 0; i < diff; i++) { padding[i] = ' '; } return new String(padding) + s; } } }
8,677
32.766537
123
java
soot
soot-master/src/main/java/soot/Transform.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai and 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.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.options.Options; import soot.util.PhaseDumper; /** * Maintains the pair (phaseName, singleton) needed for a transformation. */ public class Transform implements HasPhaseOptions { private static final Logger logger = LoggerFactory.getLogger(Transform.class); private final boolean DEBUG; private String declaredOpts; private String defaultOpts; final String phaseName; final Transformer t; public Transform(String phaseName, Transformer t) { this.DEBUG = Options.v().dump_body().contains(phaseName); this.phaseName = phaseName; this.t = t; } @Override public String getPhaseName() { return phaseName; } public Transformer getTransformer() { return t; } @Override public String getDeclaredOptions() { if (declaredOpts != null) { return declaredOpts; } return Options.getDeclaredOptionsForPhase(phaseName); } @Override public String getDefaultOptions() { if (defaultOpts != null) { return defaultOpts; } return Options.getDefaultOptionsForPhase(phaseName); } /** * Allows user-defined phases to have options other than just enabled without having to mess with the XML. Call this method * with a space-separated list of options declared for this Transform. Only declared options may be passed to this * transform as a phase option. */ public void setDeclaredOptions(String options) { declaredOpts = options; } /** * Allows user-defined phases to have options other than just enabled without having to mess with the XML. Call this method * with a space-separated list of option:value pairs that this Transform is to use as default parameters (eg * `enabled:off'). */ public void setDefaultOptions(String options) { defaultOpts = options; } public void apply() { Map<String, String> options = PhaseOptions.v().getPhaseOptions(phaseName); if (PhaseOptions.getBoolean(options, "enabled")) { if (Options.v().verbose()) { logger.debug("" + "Applying phase " + phaseName + " to the scene."); } } if (DEBUG) { PhaseDumper.v().dumpBefore(getPhaseName()); } ((SceneTransformer) t).transform(phaseName, options); if (DEBUG) { PhaseDumper.v().dumpAfter(getPhaseName()); } } public void apply(Body b) { if (b == null) { return; } Map<String, String> options = PhaseOptions.v().getPhaseOptions(phaseName); if (PhaseOptions.getBoolean(options, "enabled")) { if (Options.v().verbose()) { logger.debug("" + "Applying phase " + phaseName + " to " + b.getMethod() + "."); } } if (DEBUG) { PhaseDumper.v().dumpBefore(b, getPhaseName()); } ((BodyTransformer) t).transform(b, phaseName, options); if (DEBUG) { PhaseDumper.v().dumpAfter(b, getPhaseName()); } } @Override public String toString() { return phaseName; } }
3,840
26.833333
125
java
soot
soot-master/src/main/java/soot/Transformer.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 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% */ /** * An abstract class which acts on some Soot object. Transformers are generally expected to supply some sort of transform() * method. */ public abstract class Transformer { }
999
31.258065
123
java
soot
soot-master/src/main/java/soot/Trap.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; /** * A trap (exception catcher), used within Body classes. Intermediate representations must use an implementation of Trap to * describe caught exceptions. */ public interface Trap extends UnitBoxOwner { /** * <p> * Returns the first trapped unit, unless this <code>Trap</code> does not trap any units at all. * </p> * * <p> * If this is a degenerate <code>Trap</code> which traps no units (which can occur if all the units originally trapped by * the exception handler have been optimized away), returns an untrapped unit. The returned unit will likely be the first * unit remaining after the point where the trapped units were once located, but the only guarantee provided is that for * such an empty trap, <code>getBeginUnit()</code> will return the same value as {@link #getEndUnit()}. * </p> */ public Unit getBeginUnit(); /** * <p> * Returns the unit following the last trapped unit (that is, the first succeeding untrapped unit in the underlying * <Code>Chain</code>), unless this <code>Trap</code> does not trap any units at all. * </p> * * <p> * In the case of a degenerate <code>Trap</code> which traps no units, returns the same untrapped unit as * <code>getBeginUnit()</code> * </p> * * <p> * Note that a weakness of marking the end of the trapped region with the first untrapped unit is that Soot has no good * mechanism for describing a <code>Trap</code> which traps the last unit in a method. * </p> */ public Unit getEndUnit(); /** * Returns the unit handling the exception being trapped. */ public Unit getHandlerUnit(); /** * Returns the box holding the unit returned by {@link #getBeginUnit()}. */ public UnitBox getBeginUnitBox(); /** * Returns the box holding the unit returned by {@link #getEndUnit()}. */ public UnitBox getEndUnitBox(); /** * Returns the box holding the exception handler unit. */ public UnitBox getHandlerUnitBox(); /** * Returns the boxes for first, last, and handler units. */ @Override public List<UnitBox> getUnitBoxes(); /** * Returns the exception being caught. */ public SootClass getException(); /** * Sets the value to be returned by {@link #getBeginUnit()} to <code>beginUnit</code>. */ public void setBeginUnit(Unit beginUnit); /** * Sets the value to be returned by {@link #getEndUnit()} to <code>endUnit</code>. */ public void setEndUnit(Unit endUnit); /** * Sets the unit handling the exception to <code>handlerUnit</code>. */ public void setHandlerUnit(Unit handlerUnit); /** * Sets the exception being caught to <code>exception</code>. */ public void setException(SootClass exception); /** * Performs a shallow clone of this trap. */ public Object clone(); }
3,677
29.396694
123
java
soot
soot-master/src/main/java/soot/TrapManager.java
package soot; /*- * #%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 com.google.common.base.Optional; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import soot.util.Chain; /** Utility methods for dealing with traps. */ public class TrapManager { /** * If exception e is caught at unit u in body b, return true; otherwise, return false. */ public static boolean isExceptionCaughtAt(SootClass e, Unit u, Body b) { // Look through the traps t of b, checking to see if (1) caught exception is // e and, (2) unit lies between t.beginUnit and t.endUnit. final Hierarchy h = Scene.v().getActiveHierarchy(); final Chain<Unit> units = b.getUnits(); for (Trap t : b.getTraps()) { /* Ah ha, we might win. */ if (h.isClassSubclassOfIncluding(e, t.getException())) { for (Iterator<Unit> it = units.iterator(t.getBeginUnit(), units.getPredOf(t.getEndUnit())); it.hasNext();) { if (u.equals(it.next())) { return true; } } } } return false; } /** Returns the list of traps caught at Unit u in Body b. */ public static List<Trap> getTrapsAt(Unit unit, Body b) { final Chain<Unit> units = b.getUnits(); List<Trap> trapsList = new ArrayList<Trap>(); for (Trap t : b.getTraps()) { for (Iterator<Unit> it = units.iterator(t.getBeginUnit(), units.getPredOf(t.getEndUnit())); it.hasNext();) { if (unit.equals(it.next())) { trapsList.add(t); } } } return trapsList; } /** Returns a set of units which lie inside the range of any trap. */ public static Set<Unit> getTrappedUnitsOf(Body b) { final Chain<Unit> units = b.getUnits(); Set<Unit> trapsSet = new HashSet<Unit>(); for (Trap t : b.getTraps()) { for (Iterator<Unit> it = units.iterator(t.getBeginUnit(), units.getPredOf(t.getEndUnit())); it.hasNext();) { trapsSet.add(it.next()); } } return trapsSet; } /** * Splits all traps so that they do not cross the range rangeStart - rangeEnd. Note that rangeStart is inclusive, rangeEnd * is exclusive. */ public static void splitTrapsAgainst(Body b, Unit rangeStart, Unit rangeEnd) { final Chain<Trap> traps = b.getTraps(); final Chain<Unit> units = b.getUnits(); for (Iterator<Trap> trapsIt = traps.snapshotIterator(); trapsIt.hasNext();) { Trap t = trapsIt.next(); boolean insideRange = false; for (Iterator<Unit> unitIt = units.iterator(t.getBeginUnit(), t.getEndUnit()); unitIt.hasNext();) { Unit u = unitIt.next(); if (rangeStart.equals(u)) { insideRange = true; } if (!unitIt.hasNext()) { // i.e. u.equals(t.getEndUnit()) if (insideRange) { Trap newTrap = (Trap) t.clone(); t.setBeginUnit(rangeStart); newTrap.setEndUnit(rangeStart); traps.insertAfter(newTrap, t); } else { break; } } if (rangeEnd.equals(u)) { // insideRange had better be true now. if (!insideRange) { throw new RuntimeException("inversed range?"); } Trap firstTrap = (Trap) t.clone(); Trap secondTrap = (Trap) t.clone(); firstTrap.setEndUnit(rangeStart); secondTrap.setBeginUnit(rangeStart); secondTrap.setEndUnit(rangeEnd); t.setBeginUnit(rangeEnd); traps.insertAfter(firstTrap, t); traps.insertAfter(secondTrap, t); } } } } /** * Given a body and a unit handling an exception, returns the list of exception types possibly caught by the handler. */ public static List<RefType> getExceptionTypesOf(Unit u, Body body) { final boolean module_mode = ModuleUtil.module_mode(); List<RefType> possibleTypes = new ArrayList<RefType>(); for (Trap trap : body.getTraps()) { if (trap.getHandlerUnit() == u) { RefType type; if (module_mode) { type = ModuleRefType.v(trap.getException().getName(), Optional.fromNullable(trap.getException().moduleName)); } else { type = RefType.v(trap.getException().getName()); } possibleTypes.add(type); } } return possibleTypes; } }
5,103
32.142857
124
java
soot
soot-master/src/main/java/soot/Type.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.Serializable; import soot.util.Numberable; import soot.util.Switch; import soot.util.Switchable; /** * Represents types within Soot, eg <code>int</code>, <code>java.lang.String</code>. */ @SuppressWarnings("serial") public abstract class Type implements Switchable, Serializable, Numberable { protected ArrayType arrayType; private int number = 0; public Type() { Scene.v().getTypeNumberer().add(this); } /** * Returns a textual representation of this type. */ @Override public abstract String toString(); /** * Returns a textual (and quoted as needed) representation of this type for serialization, e.g. to .jimple format */ public String toQuotedString() { return toString(); } /** * Returns a textual (and quoted as needed) representation of this type for serialization, e.g. to .jimple format Replaced * by toQuotedString; only here for backwards compatibility. */ @Deprecated public String getEscapedName() { return toQuotedString(); } /** * Converts the int-like types (short, byte, boolean and char) to IntType. */ public static Type toMachineType(Type t) { if (t.equals(ShortType.v()) || t.equals(ByteType.v()) || t.equals(BooleanType.v()) || t.equals(CharType.v())) { return IntType.v(); } else { return t; } } /** * Returns the least common superclass of this type and other. */ public Type merge(Type other, Scene cm) { // method overriden in subclasses UnknownType and RefType throw new RuntimeException("illegal type merge: " + this + " and " + other); } /** * Method required for use of Switchable. */ @Override public void apply(Switch sw) { } public void setArrayType(ArrayType at) { arrayType = at; } public ArrayType getArrayType() { return arrayType; } public ArrayType makeArrayType() { return ArrayType.v(this, 1); } /** * Returns <code>true</code> if this type is allowed to appear in final (clean) Jimple code. * * @return */ public boolean isAllowedInFinalCode() { return false; } @Override public final int getNumber() { return number; } @Override public final void setNumber(int number) { this.number = number; } /** * If this type is not allowed in final code, this method provides a replacement type that is allowed in final code * * @return The replacement type */ public Type getDefaultFinalType() { return this; } }
3,323
24.181818
124
java
soot
soot-master/src/main/java/soot/TypeSwitch.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** Implements Switchable on base Java types. */ public class TypeSwitch<T> implements ITypeSwitch { T result; @Override public void caseArrayType(ArrayType t) { defaultCase(t); } @Override public void caseBooleanType(BooleanType t) { defaultCase(t); } @Override public void caseByteType(ByteType t) { defaultCase(t); } @Override public void caseCharType(CharType t) { defaultCase(t); } @Override public void caseDoubleType(DoubleType t) { defaultCase(t); } @Override public void caseFloatType(FloatType t) { defaultCase(t); } @Override public void caseIntType(IntType t) { defaultCase(t); } @Override public void caseLongType(LongType t) { defaultCase(t); } @Override public void caseRefType(RefType t) { defaultCase(t); } @Override public void caseShortType(ShortType t) { defaultCase(t); } @Override public void caseStmtAddressType(StmtAddressType t) { defaultCase(t); } @Override public void caseUnknownType(UnknownType t) { defaultCase(t); } @Override public void caseVoidType(VoidType t) { defaultCase(t); } @Override public void caseAnySubType(AnySubType t) { defaultCase(t); } @Override public void caseNullType(NullType t) { defaultCase(t); } @Override public void caseErroneousType(ErroneousType t) { defaultCase(t); } @Override public void defaultCase(Type t) { } /** * @deprecated Replaced by defaultCase(Type) * @see #defaultCase(Type) */ @Deprecated @Override public void caseDefault(Type t) { } public void setResult(T result) { this.result = result; } public T getResult() { return this.result; } }
2,561
18.557252
71
java