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/shimple/internal/PiNodeManager.java
package soot.shimple.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Stack; import soot.Local; import soot.PatchingChain; import soot.Unit; import soot.UnitBox; import soot.Value; import soot.ValueBox; import soot.jimple.AssignStmt; import soot.jimple.IfStmt; import soot.jimple.Jimple; import soot.jimple.LookupSwitchStmt; import soot.jimple.TableSwitchStmt; import soot.jimple.toolkits.scalar.CopyPropagator; import soot.jimple.toolkits.scalar.DeadAssignmentEliminator; import soot.shimple.PiExpr; import soot.shimple.Shimple; import soot.shimple.ShimpleBody; import soot.shimple.ShimpleFactory; import soot.toolkits.graph.Block; import soot.toolkits.graph.DominanceFrontier; import soot.toolkits.graph.DominatorNode; import soot.toolkits.graph.DominatorTree; import soot.toolkits.graph.ReversibleGraph; import soot.util.HashMultiMap; import soot.util.MultiMap; /** * This class does the real high-level work. It takes a Jimple body or Jimple/Shimple hybrid body and produces pure Shimple. * * <p> * The work is done in two main steps: * * <ol> * <li>Trivial Phi nodes are added. * <li>A renaming algorithm is executed. * </ol> * * <p> * This class can also translate out of Shimple by producing an equivalent Jimple body with all Phi nodes removed. * * <p> * Note that this is an internal class, understanding it should not be necessary from a user point-of-view and relying on it * directly is not recommended. * * @author Navindra Umanee * @see soot.shimple.ShimpleBody * @see <a href="http://citeseer.nj.nec.com/cytron91efficiently.html">Efficiently Computing Static Single Assignment Form and * the Control Dependence Graph</a> */ public class PiNodeManager { protected final ShimpleBody body; protected final ShimpleFactory sf; protected final boolean trimmed; protected ReversibleGraph<Block> cfg; protected MultiMap<Local, Block> varToBlocks; /** * Transforms the provided body to pure SSA form. */ public PiNodeManager(ShimpleBody body, boolean trimmed, ShimpleFactory sf) { this.body = body; this.trimmed = trimmed; this.sf = sf; } public void update() { ReversibleGraph<Block> oldCfg = this.cfg; this.cfg = sf.getReverseBlockGraph(); if (oldCfg != this.cfg) { // If the CFG was rebuilt, clear the map because Blocks are stale this.varToBlocks = null; } } public boolean insertTrivialPiNodes() { update(); this.varToBlocks = new HashMultiMap<Local, Block>(); final MultiMap<Local, Block> localsToUsePoints = new SHashMultiMap<Local, Block>(); // compute localsToUsePoints and varToBlocks for (Block block : cfg) { for (Unit unit : block) { for (ValueBox next : unit.getUseBoxes()) { Value use = next.getValue(); if (use instanceof Local) { localsToUsePoints.put((Local) use, block); } } if (Shimple.isPiNode(unit)) { varToBlocks.put(Shimple.getLhsLocal(unit), block); } } } boolean change = false; { final DominatorTree<Block> dt = sf.getReverseDominatorTree(); final DominanceFrontier<Block> df = sf.getReverseDominanceFrontier(); /* Routine initialisations. */ int iterCount = 0; int[] workFlags = new int[cfg.size()]; int[] hasAlreadyFlags = new int[cfg.size()]; Stack<Block> workList = new Stack<Block>(); /* Main Cytron algorithm. */ for (Local local : localsToUsePoints.keySet()) { iterCount++; // initialise worklist for (Block block : localsToUsePoints.get(local)) { workFlags[block.getIndexInMethod()] = iterCount; workList.push(block); } while (!workList.empty()) { Block block = workList.pop(); for (DominatorNode<Block> frontierNode : df.getDominanceFrontierOf(dt.getDode(block))) { Block frontierBlock = frontierNode.getGode(); int fBIndex = frontierBlock.getIndexInMethod(); if (hasAlreadyFlags[fBIndex] < iterCount) { hasAlreadyFlags[fBIndex] = iterCount; insertPiNodes(local, frontierBlock); change = true; if (workFlags[fBIndex] < iterCount) { workFlags[fBIndex] = iterCount; workList.push(frontierBlock); } } } } } } if (change) { sf.clearCache(); } return change; } public void insertPiNodes(Local local, Block frontierBlock) { if (varToBlocks.get(local).contains(frontierBlock.getSuccs().get(0))) { return; } Unit u = frontierBlock.getTail(); TRIMMED: { if (trimmed) { for (ValueBox vb : u.getUseBoxes()) { if (vb.getValue().equals(local)) { break TRIMMED; } } return; } } if (u instanceof IfStmt) { piHandleIfStmt(local, (IfStmt) u); } else if ((u instanceof LookupSwitchStmt) || (u instanceof TableSwitchStmt)) { piHandleSwitchStmt(local, u); } else { throw new RuntimeException("Assertion failed: Unhandled stmt: " + u); } } public void piHandleIfStmt(Local local, IfStmt u) { final PatchingChain<Unit> units = body.getUnits(); Unit target = u.getTarget(); Unit addt = Jimple.v().newAssignStmt(local, Shimple.v().newPiExpr(local, u, Boolean.TRUE)); Unit addf = Jimple.v().newAssignStmt(local, Shimple.v().newPiExpr(local, u, Boolean.FALSE)); // insert after should be safe; a new block should result if // the Unit originally after the IfStmt had another predecessor. // what about SPatchingChain? seems sane. units.insertAfter(addf, u); /* * we need to be careful with insertBefore, if target already had some other predecessors. */ // handle immediate predecessor if it falls through // *** FIXME: Does SPatchingChain do the right thing? { Unit predOfTarget; try { predOfTarget = units.getPredOf(target); } catch (NoSuchElementException e) { predOfTarget = null; } if (predOfTarget != null && predOfTarget.fallsThrough()) { units.insertAfter(Jimple.v().newGotoStmt(target), predOfTarget); } } // we do not want to move the pointers for other branching statements units.getNonPatchingChain().insertBefore(addt, target); u.setTarget(addt); } public void piHandleSwitchStmt(Local local, Unit u) { List<UnitBox> targetBoxes = new ArrayList<UnitBox>(); List<Object> targetKeys = new ArrayList<Object>(); if (u instanceof LookupSwitchStmt) { LookupSwitchStmt lss = (LookupSwitchStmt) u; targetBoxes.add(lss.getDefaultTargetBox()); targetKeys.add("default"); for (int i = 0, e = lss.getTargetCount(); i < e; i++) { targetBoxes.add(lss.getTargetBox(i)); } targetKeys.addAll(lss.getLookupValues()); } else if (u instanceof TableSwitchStmt) { TableSwitchStmt tss = (TableSwitchStmt) u; int low = tss.getLowIndex(); int hi = tss.getHighIndex(); targetBoxes.add(tss.getDefaultTargetBox()); targetKeys.add("default"); for (int i = 0, e = (hi - low); i <= e; i++) { targetBoxes.add(tss.getTargetBox(i)); } for (int i = low; i <= hi; i++) { targetKeys.add(i); } } else { throw new RuntimeException("Assertion failed."); } for (int count = 0, e = targetBoxes.size(); count < e; count++) { UnitBox targetBox = targetBoxes.get(count); Unit target = targetBox.getUnit(); PatchingChain<Unit> units = body.getUnits(); /* * we need to be careful with insertBefore, if target already had some other predecessors. */ // handle immediate predecessor if it falls through // *** FIXME: Does SPatchingChain do the right thing? { Unit predOfTarget; try { predOfTarget = units.getPredOf(target); } catch (NoSuchElementException ex) { predOfTarget = null; } if (predOfTarget != null && predOfTarget.fallsThrough()) { units.insertAfter(Jimple.v().newGotoStmt(target), predOfTarget); } } // we do not want to move the pointers for other branching statements Unit add1 = Jimple.v().newAssignStmt(local, Shimple.v().newPiExpr(local, u, targetKeys.get(count))); units.getNonPatchingChain().insertBefore(add1, target); targetBox.setUnit(add1); } } public void eliminatePiNodes(boolean smart) { if (smart) { Map<Value, Value> newToOld = new HashMap<Value, Value>(); List<ValueBox> boxes = new ArrayList<ValueBox>(); for (Iterator<Unit> unitsIt = body.getUnits().iterator(); unitsIt.hasNext();) { Unit u = unitsIt.next(); PiExpr pe = Shimple.getPiExpr(u); if (pe != null) { newToOld.put(Shimple.getLhsLocal(u), pe.getValue()); unitsIt.remove(); } else { boxes.addAll(u.getUseBoxes()); } } for (ValueBox box : boxes) { Value value = box.getValue(); Value old = newToOld.get(value); if (old != null) { box.setValue(old); } } DeadAssignmentEliminator.v().transform(body); CopyPropagator.v().transform(body); DeadAssignmentEliminator.v().transform(body); } else { for (Unit u : body.getUnits()) { PiExpr pe = Shimple.getPiExpr(u); if (pe != null) { ((AssignStmt) u).setRightOp(pe.getValue()); } } } } public static List<ValueBox> getUseBoxesFromBlock(Block block) { List<ValueBox> useBoxesList = new ArrayList<ValueBox>(); for (Unit next : block) { useBoxesList.addAll(next.getUseBoxes()); } return useBoxesList; } }
10,822
30.371014
125
java
soot
soot-master/src/main/java/soot/shimple/internal/SHashMultiMap.java
package soot.shimple.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Navindra Umanee * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.LinkedHashSet; import java.util.Set; import soot.util.HashMultiMap; import soot.util.MultiMap; /** * A map with ordered sets as values, HashMap implementation. * * @author Navindra Umanee */ public class SHashMultiMap<K, V> extends HashMultiMap<K, V> { private static final long serialVersionUID = -860669798578291979L; public SHashMultiMap() { super(); } public SHashMultiMap(MultiMap<K, V> m) { super(m); } @Override protected Set<V> newSet() { return new LinkedHashSet<V>(4); } }
1,370
24.867925
71
java
soot
soot-master/src/main/java/soot/shimple/internal/SPatchingChain.java
package soot.shimple.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.TrapManager; import soot.Unit; import soot.UnitBox; import soot.UnitPatchingChain; import soot.options.Options; import soot.shimple.PhiExpr; import soot.shimple.Shimple; import soot.shimple.ShimpleBody; import soot.util.Chain; import soot.util.HashMultiMap; import soot.util.MultiMap; /** * Internal Shimple extension of PatchingChain. * * @author Navindra Umanee * @see soot.PatchingChain */ public class SPatchingChain extends UnitPatchingChain { private static final Logger logger = LoggerFactory.getLogger(SPatchingChain.class); /** * Needed to find non-trapped Units of the body. */ protected final Body body; protected final boolean debug; /** * Map from UnitBox to the Phi node owning it. */ protected Map<UnitBox, Unit> boxToPhiNode = new HashMap<UnitBox, Unit>(); /** * Set of the values of boxToPhiNode. Used to allow O(1) contains() on the values. */ protected Set<Unit> phiNodeSet = new HashSet<Unit>(); /** * Flag that indicates whether control flow falls through from the unit referenced in the SUnitBox to the Phi node that * owns the SUnitBox. */ protected Map<SUnitBox, Boolean> boxToNeedsPatching = new HashMap<SUnitBox, Boolean>(); public SPatchingChain(Body aBody, Chain<Unit> aChain) { super(aChain); this.body = aBody; boolean debug = Options.v().debug(); if (aBody instanceof ShimpleBody) { debug |= ((ShimpleBody) aBody).getOptions().debug(); } this.debug = debug; } @Override public boolean add(Unit o) { processPhiNode(o); return super.add(o); } @Override public void swapWith(Unit out, Unit in) { // Ensure that branching statements are swapped correctly. // The normal swapWith implementation would still work // correctly but redirectToPreds performed during the remove // would be more expensive and might print warnings if no // actual CFG predecessors for out was found due to the // insertion of branching statement in. processPhiNode(in); Shimple.redirectPointers(out, in); super.insertBefore(in, out);// use super to avoid repeating processPhiNode(in) this.remove(out); } @Override public void insertAfter(Unit toInsert, Unit point) { // important to do these before the patching, so that // computeNeedsPatching works properly processPhiNode(toInsert); super.insertAfter(toInsert, point); // update any pointers from Phi nodes only if the unit // being inserted is in the same basic block as point. // // no need to move the pointers if (!point.fallsThrough()) { return; } // move pointers unconditionally, needed as a special case if (!point.branches()) { if (body == null || !TrapManager.getTrappedUnitsOf(body).contains(point)) { Shimple.redirectPointers(point, toInsert); return; } } /* handle each UnitBox individually */ for (UnitBox ub : new ArrayList<>(point.getBoxesPointingToThis())) { if (ub.getUnit() != point) { throw new RuntimeException("Assertion failed."); } if (ub.isBranchTarget()) { continue; } SUnitBox box = getSBox(ub); Boolean needsPatching = boxToNeedsPatching.get(box); if (needsPatching == null || box.isUnitChanged()) { // if boxes were added or removed to the known Phi if (!boxToPhiNode.containsKey(box)) { reprocessPhiNodes(); // *** FIXME: Disabling this allows us to have // PiExpr that have UnitBox pointers. // I think this means that any changes // to the relevant Unit will be ignored by // SPatchingChain. // // Hopefully this also means that any // transformation that moves/removes/modifies // a Unit pointed at by a PiExpr knows what // it's doing. if (!boxToPhiNode.containsKey(box) && debug) { throw new RuntimeException("SPatchingChain has pointers from a Phi node that has never been seen."); } } computeNeedsPatching(); needsPatching = boxToNeedsPatching.get(box); if (needsPatching == null) { // maybe the user forgot to clearUnitBoxes() // when removing a Phi node, or the user removed // a Phi node and hasn't put it back yet if (debug) { logger.warn("Orphaned UnitBox to " + point + "? SPatchingChain will not move the pointer."); } continue; } } if (needsPatching) { box.setUnit(toInsert); box.setUnitChanged(false); } } } @Override public void insertAfter(List<Unit> toInsert, Unit point) { for (Unit unit : toInsert) { processPhiNode(unit); } super.insertAfter(toInsert, point); } @Override public void insertAfter(Chain<Unit> toInsert, Unit point) { for (Unit unit : toInsert) { processPhiNode(unit); } super.insertAfter(toInsert, point); } @Override public void insertAfter(Collection<? extends Unit> toInsert, Unit point) { for (Unit unit : toInsert) { processPhiNode(unit); } super.insertAfter(toInsert, point); } @Override public void insertBefore(Unit toInsert, Unit point) { processPhiNode(toInsert); super.insertBefore(toInsert, point); } @Override public void insertBefore(List<Unit> toInsert, Unit point) { for (Unit unit : toInsert) { processPhiNode(unit); } super.insertBefore(toInsert, point); } @Override public void insertBefore(Chain<Unit> toInsert, Unit point) { for (Unit unit : toInsert) { processPhiNode(unit); } super.insertBefore(toInsert, point); } @Override public void insertBefore(Collection<? extends Unit> toInsert, Unit point) { for (Unit unit : toInsert) { processPhiNode(unit); } super.insertBefore(toInsert, point); } @Override public void addFirst(Unit u) { processPhiNode(u); super.addFirst(u); } @Override public void addLast(Unit u) { processPhiNode(u); super.addLast(u); } public boolean remove(Unit u) { if (contains(u)) { Shimple.redirectToPreds(body, u); boolean ret = super.remove(u); patchAfterRemoval(u); return ret; } else { return false; } } @Override public boolean remove(Object obj) { return (obj instanceof Unit) ? remove((Unit) obj) : false; } // After all patching is done, clear references to this Unit // from any Unit that one of its UnitBoxes referenced. protected static void patchAfterRemoval(Unit removing) { if (removing != null) { for (UnitBox ub : removing.getUnitBoxes()) { Unit u = ub.getUnit(); if (u != null) { u.removeBoxPointingToThis(ub); } } } } protected void processPhiNode(Unit phiNode) { PhiExpr phi = Shimple.getPhiExpr(phiNode); // not a Phi node if (phi == null) { return; } // already processed previously, unit chain manipulations? if (phiNodeSet.contains(phiNode)) { return; } for (UnitBox box : phi.getUnitBoxes()) { boxToPhiNode.put(box, phiNode); phiNodeSet.add(phiNode); } } protected void reprocessPhiNodes() { Set<Unit> phiNodes = new HashSet<Unit>(boxToPhiNode.values()); this.boxToPhiNode = new HashMap<UnitBox, Unit>(); this.phiNodeSet = new HashSet<Unit>(); this.boxToNeedsPatching = new HashMap<SUnitBox, Boolean>(); for (Unit next : phiNodes) { processPhiNode(next); } } /** * Computes {@link #boxToNeedsPatching} which maps each UnitBox from a PhiExpr to true if the referenced Unit falls-through * to the statement containing the PhiExpr, false otherwise. * * NOTE: This will *miss* all the Phi nodes outside a chain. So make sure you know what you are doing if you remove a Phi * node from a chain and don't put it back or call clearUnitBoxes() on it. */ protected void computeNeedsPatching() { if (boxToPhiNode.isEmpty()) { return; } // we track the fallthrough control flow from boxes to the // corresponding Phi statements. trackedPhi provides a // mapping from the Phi being tracked to its relevant boxes. final MultiMap<Unit, UnitBox> trackedPhiToBoxes = new HashMultiMap<Unit, UnitBox>(); // consider: // // if blah goto label1 // label1: // // Here control flow both fallsthrough and branches to label1. // If such an if statement is encountered, we do not want to // move any UnitBox pointers beyond the if statement. final Set<Unit> trackedBranchTargets = new HashSet<Unit>(); for (Unit u : this) { // update trackedPhiToBoxes List<UnitBox> boxesToTrack = u.getBoxesPointingToThis(); if (boxesToTrack != null) { for (UnitBox boxToTrack : boxesToTrack) { if (!boxToTrack.isBranchTarget()) { trackedPhiToBoxes.put(boxToPhiNode.get(boxToTrack), boxToTrack); } } } // update trackedBranchTargets if (u.fallsThrough() && u.branches()) { for (UnitBox ub : u.getUnitBoxes()) { trackedBranchTargets.add(ub.getUnit()); } } // the tracked Phi nodes may be reached through branching. // (note: if u is a Phi node and not a trackedBranchTarget, this // is not triggered since u would fall through in that case.) if (!u.fallsThrough() || trackedBranchTargets.contains(u)) { for (UnitBox next : trackedPhiToBoxes.values()) { SUnitBox box = getSBox(next); boxToNeedsPatching.put(box, Boolean.FALSE); box.setUnitChanged(false); } trackedPhiToBoxes.clear(); continue; } // we found one of the Phi nodes pointing to a Unit Set<UnitBox> boxes = trackedPhiToBoxes.get(u); if (boxes != null) { for (UnitBox ub : boxes) { SUnitBox box = getSBox(ub); // falls through boxToNeedsPatching.put(box, Boolean.TRUE); box.setUnitChanged(false); } trackedPhiToBoxes.remove(u); } } // after the iteration, the rest do not fall through for (UnitBox next : trackedPhiToBoxes.values()) { SUnitBox box = getSBox(next); boxToNeedsPatching.put(box, Boolean.FALSE); box.setUnitChanged(false); } } protected SUnitBox getSBox(UnitBox box) { if (box instanceof SUnitBox) { return (SUnitBox) box; } else { throw new RuntimeException("Shimple box not an SUnitBox?"); } } protected class SPatchingIterator extends PatchingIterator { SPatchingIterator(Chain<Unit> innerChain) { super(innerChain); } SPatchingIterator(Chain<Unit> innerChain, Unit u) { super(innerChain, u); } SPatchingIterator(Chain<Unit> innerChain, Unit head, Unit tail) { super(innerChain, head, tail); } @Override public void remove() { if (!state) { throw new IllegalStateException("remove called before first next() call"); } state = false; Unit victim = lastObject; Shimple.redirectToPreds(SPatchingChain.this.body, victim); patchBeforeRemoval(innerChain, victim); innerIterator.remove(); patchAfterRemoval(victim); } } @Override public Iterator<Unit> iterator() { return new SPatchingIterator(innerChain); } @Override public Iterator<Unit> iterator(Unit u) { return new SPatchingIterator(innerChain, u); } @Override public Iterator<Unit> iterator(Unit head, Unit tail) { return new SPatchingIterator(innerChain, head, tail); } }
12,860
28.163265
125
java
soot
soot-master/src/main/java/soot/shimple/internal/SPhiExpr.java
package soot.shimple.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Local; import soot.Type; import soot.Unit; import soot.UnitBox; import soot.UnitPrinter; import soot.Value; import soot.ValueBox; import soot.shimple.PhiExpr; import soot.shimple.Shimple; import soot.shimple.ShimpleExprSwitch; import soot.toolkits.graph.Block; import soot.toolkits.scalar.ValueUnitPair; import soot.util.Switch; /** * Internal implementation of Phi nodes. * * @author Navindra Umanee * @see soot.shimple.PhiExpr */ public class SPhiExpr implements PhiExpr { private static final Logger logger = LoggerFactory.getLogger(SPhiExpr.class); protected List<ValueUnitPair> argPairs = new ArrayList<ValueUnitPair>(); protected Map<Unit, ValueUnitPair> predToPair = new HashMap<Unit, ValueUnitPair>(); // cache protected Type type; protected int blockId = -1; /** * Create a trivial Phi expression for leftLocal. preds is an ordered list of the control flow predecessor Blocks of the * PhiExpr. */ public SPhiExpr(Local leftLocal, List<Block> preds) { this.type = leftLocal.getType(); for (Block pred : preds) { addArg(leftLocal, pred); } } /** * Create a Phi expression from the given list of Values and Blocks. */ public SPhiExpr(List<Value> args, List<Unit> preds) { if (args.isEmpty()) { throw new RuntimeException("Arg list may not be empty"); } if (args.size() != preds.size()) { throw new RuntimeException("Arg list does not match Pred list"); } this.type = args.get(0).getType(); Iterator<Unit> predsIt = preds.iterator(); for (Value arg : args) { Unit pred = predsIt.next(); if (pred instanceof Block) { addArg(arg, (Block) pred); } else { addArg(arg, pred); } } } /* get-accessor implementations */ @Override public List<ValueUnitPair> getArgs() { return Collections.unmodifiableList(argPairs); } @Override public List<Value> getValues() { List<Value> args = new ArrayList<Value>(); for (ValueUnitPair vup : argPairs) { Value arg = vup.getValue(); args.add(arg); } return args; } @Override public List<Unit> getPreds() { List<Unit> preds = new ArrayList<Unit>(); for (ValueUnitPair up : argPairs) { Unit arg = up.getUnit(); preds.add(arg); } return preds; } @Override public int getArgCount() { return argPairs.size(); } @Override public ValueUnitPair getArgBox(int index) { if (index < 0 || index >= argPairs.size()) { return null; } return argPairs.get(index); } @Override public Value getValue(int index) { ValueUnitPair arg = getArgBox(index); if (arg == null) { return null; } return arg.getValue(); } @Override public Unit getPred(int index) { ValueUnitPair arg = getArgBox(index); if (arg == null) { return null; } return arg.getUnit(); } @Override public int getArgIndex(Unit predTailUnit) { ValueUnitPair pair = getArgBox(predTailUnit); return argPairs.indexOf(pair); // (-1 on null) } @Override public ValueUnitPair getArgBox(Unit predTailUnit) { ValueUnitPair vup = predToPair.get(predTailUnit); // we pay a penalty for misses but hopefully the common case // is faster than an iteration over argPairs every time if (vup == null || vup.getUnit() != predTailUnit) { updateCache(); vup = predToPair.get(predTailUnit); if ((vup != null) && (vup.getUnit() != predTailUnit)) { throw new RuntimeException("Assertion failed."); } } // (null if not found) return vup; } @Override public Value getValue(Unit predTailUnit) { ValueBox vb = getArgBox(predTailUnit); if (vb == null) { return null; } return vb.getValue(); } @Override public int getArgIndex(Block pred) { ValueUnitPair box = getArgBox(pred); return argPairs.indexOf(box); // (-1 on null) } @Override public ValueUnitPair getArgBox(Block pred) { Unit predTailUnit = pred.getTail(); ValueUnitPair box = getArgBox(predTailUnit); // workaround added for internal cases where the predTailUnit // may not be at the end of the predecessor block // (eg, fall-through pointer not moved) while (box == null) { predTailUnit = pred.getPredOf(predTailUnit); if (predTailUnit == null) { break; } box = getArgBox(predTailUnit); } return box; } @Override public Value getValue(Block pred) { ValueBox vb = getArgBox(pred); if (vb == null) { return null; } return vb.getValue(); } /* set-accessor implementations */ @Override public boolean setArg(int index, Value arg, Unit predTailUnit) { boolean ret1 = setValue(index, arg); boolean ret2 = setPred(index, predTailUnit); if (ret1 != ret2) { throw new RuntimeException("Assertion failed."); } return ret1; } @Override public boolean setArg(int index, Value arg, Block pred) { return setArg(index, arg, pred.getTail()); } @Override public boolean setValue(int index, Value arg) { ValueUnitPair argPair = getArgBox(index); if (argPair == null) { return false; } argPair.setValue(arg); return true; } @Override public boolean setValue(Unit predTailUnit, Value arg) { int index = getArgIndex(predTailUnit); return setValue(index, arg); } @Override public boolean setValue(Block pred, Value arg) { int index = getArgIndex(pred); return setValue(index, arg); } @Override public boolean setPred(int index, Unit predTailUnit) { ValueUnitPair argPair = getArgBox(index); if (argPair == null) { return false; } int other = getArgIndex(predTailUnit); if (other != -1) { logger.warn("An argument with control flow predecessor " + predTailUnit + " already exists in " + this + "!"); logger.warn("setPred resulted in deletion of " + argPair + " from " + this + "."); removeArg(argPair); return false; } argPair.setUnit(predTailUnit); return true; } @Override public boolean setPred(int index, Block pred) { return setPred(index, pred.getTail()); } /* add/remove implementations */ @Override public boolean removeArg(int index) { ValueUnitPair arg = getArgBox(index); return removeArg(arg); } @Override public boolean removeArg(Unit predTailUnit) { ValueUnitPair arg = getArgBox(predTailUnit); return removeArg(arg); } @Override public boolean removeArg(Block pred) { ValueUnitPair arg = getArgBox(pred); return removeArg(arg); } @Override public boolean removeArg(ValueUnitPair arg) { if (argPairs.remove(arg)) { // update cache predToPair.remove(arg.getUnit()); // remove back-pointer arg.getUnit().removeBoxPointingToThis(arg); return true; } else { return false; } } @Override public boolean addArg(Value arg, Block pred) { return addArg(arg, pred.getTail()); } @Override public boolean addArg(Value arg, Unit predTailUnit) { // Do not allow phi nodes for dummy blocks if (predTailUnit == null) { return false; } // we disallow duplicate arguments if (predToPair.containsKey(predTailUnit)) { return false; } ValueUnitPair vup = new SValueUnitPair(arg, predTailUnit); // add and update cache argPairs.add(vup); predToPair.put(predTailUnit, vup); return true; } @Override public void setBlockId(int blockId) { this.blockId = blockId; } @Override public int getBlockId() { if (blockId == -1) { throw new RuntimeException("Assertion failed: Block Id unknown."); } return blockId; } /* misc */ /** * Update predToPair cache map which could be out-of-sync due to external setUnit or clone operations on the UnitBoxes. */ protected void updateCache() { // Always attempt to allocate the next power of 2 sized map int needed = argPairs.size(); predToPair = new HashMap<Unit, ValueUnitPair>(needed << 1, 1.0F); for (ValueUnitPair vup : argPairs) { predToPair.put(vup.getUnit(), vup); } } @Override public boolean equivTo(Object o) { if (o instanceof SPhiExpr) { SPhiExpr pe = (SPhiExpr) o; int argCount = this.getArgCount(); if (argCount == pe.getArgCount()) { for (int i = 0; i < argCount; i++) { if (!this.argPairs.get(i).equivTo(pe.argPairs.get(i))) { return false; } } return true; } } return false; } @Override public int equivHashCode() { int hashcode = 1; for (ValueUnitPair p : argPairs) { hashcode = hashcode * 17 + p.equivHashCode(); } return hashcode; } @Override public List<UnitBox> getUnitBoxes() { return Collections.unmodifiableList(new ArrayList<UnitBox>(new HashSet<UnitBox>(argPairs))); } @Override public void clearUnitBoxes() { for (UnitBox box : argPairs) { box.setUnit(null); } } @Override public List<ValueBox> getUseBoxes() { Set<ValueBox> set = new HashSet<ValueBox>(); for (ValueUnitPair argPair : argPairs) { set.addAll(argPair.getValue().getUseBoxes()); set.add(argPair); } return new ArrayList<ValueBox>(set); } @Override public Type getType() { return type; } @Override public String toString() { StringBuilder expr = new StringBuilder(Shimple.PHI + "("); boolean isFirst = true; for (ValueUnitPair vuPair : argPairs) { if (!isFirst) { expr.append(", "); } else { isFirst = false; } expr.append(vuPair.getValue().toString()); } expr.append(')'); return expr.toString(); } @Override public void toString(UnitPrinter up) { up.literal(Shimple.PHI); up.literal("("); boolean isFirst = true; for (ValueUnitPair vuPair : argPairs) { if (!isFirst) { up.literal(", "); } else { isFirst = false; } vuPair.toString(up); } up.literal(")"); } @Override public void apply(Switch sw) { ((ShimpleExprSwitch) sw).casePhiExpr(this); } @Override public Object clone() { // Note to self: Do not try to "fix" this *again*. Yes, it // should be a shallow copy in order to conform with the rest // of Soot. When a body is cloned, the Values are cloned // explicitly and replaced, and UnitBoxes are explicitly // patched. See Body.importBodyContentsFrom for details. return new SPhiExpr(getValues(), getPreds()); } }
11,754
23.643606
122
java
soot
soot-master/src/main/java/soot/shimple/internal/SPiExpr.java
package soot.shimple.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Collections; import java.util.List; import soot.Type; import soot.Unit; import soot.UnitBox; import soot.UnitPrinter; import soot.Value; import soot.ValueBox; import soot.shimple.PiExpr; import soot.shimple.Shimple; import soot.toolkits.scalar.ValueUnitPair; import soot.util.Switch; /** * @author Navindra Umanee */ public class SPiExpr implements PiExpr { protected ValueUnitPair argBox; protected Object targetKey; public SPiExpr(Value v, Unit u, Object o) { this.argBox = new SValueUnitPair(v, u); this.targetKey = o; } @Override public ValueUnitPair getArgBox() { return argBox; } @Override public Value getValue() { return argBox.getValue(); } @Override public Unit getCondStmt() { return argBox.getUnit(); } @Override public Object getTargetKey() { return targetKey; } @Override public void setValue(Value value) { argBox.setValue(value); } @Override public void setCondStmt(Unit pred) { argBox.setUnit(pred); } @Override public void setTargetKey(Object targetKey) { this.targetKey = targetKey; } @Override public List<UnitBox> getUnitBoxes() { return Collections.<UnitBox>singletonList(argBox); } @Override public void clearUnitBoxes() { argBox.setUnit(null); } @Override public boolean equivTo(Object o) { if (o instanceof SPiExpr) { return getArgBox().equivTo(((SPiExpr) o).getArgBox()); } else { return false; } } @Override public int equivHashCode() { return getArgBox().equivHashCode() * 17; } @Override public void apply(Switch sw) { // *** FIXME: throw new RuntimeException("Not Yet Implemented."); } @Override public Object clone() { return new SPiExpr(getValue(), getCondStmt(), getTargetKey()); } @Override public String toString() { return Shimple.PI + "(" + getValue() + ")"; } @Override public void toString(UnitPrinter up) { up.literal(Shimple.PI); up.literal("("); argBox.toString(up); up.literal(" ["); up.literal(targetKey.toString()); up.literal("])"); } @Override public Type getType() { return getValue().getType(); } @Override public List<ValueBox> getUseBoxes() { return Collections.<ValueBox>singletonList(argBox); } }
3,176
20.612245
71
java
soot
soot-master/src/main/java/soot/shimple/internal/SUnitBox.java
package soot.shimple.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.UnitBox; /** * Extension of UnitBox to provide some extra information needed by SPatchingChain. * * @author Navindra Umanee */ public interface SUnitBox extends UnitBox { /** * Indicates whether the contents of the UnitBox may have been changed. Returns true if setUnit(Unit) has been called * recently and was not followed by setUnitChanged(false). * * <p> * Needed for Shimple internal Unit chain patching. */ public boolean isUnitChanged(); /** * Updates the value of the flag used to indicate whether the contents of the UnitBox may have changed. * * <p> * Needed for Shimple internal Unit chain patching. * * @see #isUnitChanged() */ public void setUnitChanged(boolean unitChanged); }
1,611
30
119
java
soot
soot-master/src/main/java/soot/shimple/internal/SValueUnitPair.java
package soot.shimple.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.Unit; import soot.Value; import soot.toolkits.scalar.ValueUnitPair; /** * Extension of ValueUnitPair that implements SUnitBox. Needed by SPatchingChain. Equality is no longer dependent on the * value. * * @author Navindra Umanee */ public class SValueUnitPair extends ValueUnitPair implements SUnitBox { protected boolean unitChanged; public SValueUnitPair(Value value, Unit unit) { super(value, unit); setUnitChanged(true); } @Override public boolean isBranchTarget() { return false; } @Override public void setUnit(Unit u) { super.setUnit(u); setUnitChanged(true); } /** * @see SUnitBox#isUnitChanged() */ @Override public boolean isUnitChanged() { return unitChanged; } /** * @see SUnitBox#setUnitChanged(boolean) */ @Override public void setUnitChanged(boolean unitChanged) { this.unitChanged = unitChanged; } }
1,770
23.943662
120
java
soot
soot-master/src/main/java/soot/shimple/internal/ShimpleBodyBuilder.java
package soot.shimple.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.DefinitionStmt; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.base.Aggregator; import soot.jimple.toolkits.scalar.DeadAssignmentEliminator; 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.options.ShimpleOptions; import soot.shimple.DefaultShimpleFactory; import soot.shimple.PhiExpr; import soot.shimple.Shimple; import soot.shimple.ShimpleBody; import soot.shimple.ShimpleFactory; import soot.toolkits.graph.Block; import soot.toolkits.graph.DominatorNode; import soot.toolkits.graph.DominatorTree; import soot.toolkits.scalar.UnusedLocalEliminator; /** * This class does the real high-level work. It takes a Jimple body or Jimple/Shimple hybrid body and produces pure Shimple. * * <p> * The work is done in two main steps: * * <ol> * <li>Trivial Phi nodes are added. * <li>A renaming algorithm is executed. * </ol> * * <p> * This class can also translate out of Shimple by producing an equivalent Jimple body with all Phi nodes removed. * * <p> * Note that this is an internal class, understanding it should not be necessary from a user point-of-view and relying on it * directly is not recommended. * * @author Navindra Umanee * @see soot.shimple.ShimpleBody * @see <a href="http://citeseer.nj.nec.com/cytron91efficiently.html">Efficiently Computing Static Single Assignment Form and * the Control Dependence Graph</a> */ public class ShimpleBodyBuilder { private static String freshSeparator = "_"; protected final ShimpleBody body; protected final ShimpleOptions options; protected final ShimpleFactory sf; // A fixed list of all original Locals. protected List<Local> origLocals; // Maps new name Strings to Locals. protected Map<String, Local> newLocals; // Maps renamed Locals to original Locals. protected Map<Local, Local> newLocalsToOldLocal; protected int[] assignmentCounters; protected Stack<Integer>[] namingStacks; public final PhiNodeManager phi; public final PiNodeManager pi; /** * Transforms the provided body to pure SSA form. */ public ShimpleBodyBuilder(ShimpleBody body) { // Must remove nops prior to building the CFG because NopStmt appearing // before the IdentityStmt in a trap handler that is itself protected // by a trap cause Phi nodes to be inserted before the NopStmt and // therefore before the IdentityStmt. This introduces a validation // problem if the Phi nodes leave residual assignment statements after // their removal. NopEliminator.v().transform(body); this.body = body; this.options = body.getOptions(); this.sf = new DefaultShimpleFactory(body); sf.clearCache(); this.phi = new PhiNodeManager(body, sf); this.pi = new PiNodeManager(body, false, sf); makeUniqueLocalNames(); } public void update() { this.origLocals = Collections.unmodifiableList(new ArrayList<Local>(body.getLocals())); } public void transform() { // Must clear cached graph, etc. in case of rebuilding Shimple // after Body modifications that may introduce new blocks. sf.clearCache(); update(); phi.insertTrivialPhiNodes(); if (options.extended()) { for (boolean change = pi.insertTrivialPiNodes(); change;) { if (phi.insertTrivialPhiNodes()) { change = pi.insertTrivialPiNodes(); } else { break; } } } renameLocals(); phi.trimExceptionalPhiNodes(); makeUniqueLocalNames(); } public void preElimOpt() { // boolean optElim = options.node_elim_opt(); // *** FIXME: 89e9a0470601091906j26489960j65290849dbe0481f@mail.gmail.com // if(optElim) // DeadAssignmentEliminator.v().transform(body); } public void postElimOpt() { if (options.node_elim_opt()) { DeadAssignmentEliminator.v().transform(body); UnreachableCodeEliminator.v().transform(body); UnconditionalBranchFolder.v().transform(body); Aggregator.v().transform(body); UnusedLocalEliminator.v().transform(body); } } /** * Remove Phi nodes from current body, high probability this destroys SSA form. * * <p> * Dead code elimination + register aggregation are performed as recommended by Cytron. The Aggregator looks like it could * use some improvements. * * @see soot.options.ShimpleOptions */ public void eliminatePhiNodes() { if (phi.doEliminatePhiNodes()) { makeUniqueLocalNames(); } } public void eliminatePiNodes() { pi.eliminatePiNodes(options.node_elim_opt()); } /** * Variable Renaming Algorithm from Cytron et al 91, P26-8, implemented in various bits and pieces by the next functions. * Must be called after trivial nodes have been added. */ public void renameLocals() { update(); this.newLocals = new HashMap<String, Local>(); this.newLocalsToOldLocal = new HashMap<Local, Local>(); final int size = origLocals.size(); this.assignmentCounters = new int[size]; @SuppressWarnings("unchecked") Stack<Integer>[] temp = new Stack[size]; for (int i = 0; i < size; i++) { temp[i] = new Stack<Integer>(); } this.namingStacks = temp; List<Block> heads = sf.getBlockGraph().getHeads(); switch (heads.size()) { case 0: return; case 1: renameLocalsSearch(heads.get(0)); return; default: throw new RuntimeException("Assertion failed: Only one head expected."); } } /** * Driven by renameLocals(). */ public void renameLocalsSearch(Block block) { // accumulated in Step 1 to be re-processed in Step 4 List<Local> lhsLocals = new ArrayList<Local>(); // Step 1 of 4 -- Rename block's uses (ordinary) and defs // accumulated and re-processed in a later loop for (Unit unit : block) { // Step 1A if (!Shimple.isPhiNode(unit)) { for (ValueBox useBox : unit.getUseBoxes()) { Value use = useBox.getValue(); int localIndex = indexOfLocal(use); // not one of our locals if (localIndex == -1) { continue; } Stack<Integer> namingStack = namingStacks[localIndex]; if (namingStack.empty()) { continue; } Integer subscript = namingStack.peek(); Local renamedLocal = fetchNewLocal((Local) use, subscript); useBox.setValue(renamedLocal); } } // Step 1B if (unit instanceof DefinitionStmt) { DefinitionStmt defStmt = (DefinitionStmt) unit; ValueBox lhsLocalBox = defStmt.getLeftOpBox(); Value lhsValue = lhsLocalBox.getValue(); // not something we're interested in if (!origLocals.contains(lhsValue)) { continue; } Local lhsLocal = (Local) lhsValue; // re-processed in Step 4 lhsLocals.add(lhsLocal); int localIndex = indexOfLocal(lhsLocal); if (localIndex == -1) { throw new RuntimeException("Assertion failed."); } Integer subscript = assignmentCounters[localIndex]; Local newLhsLocal = fetchNewLocal(lhsLocal, subscript); lhsLocalBox.setValue(newLhsLocal); namingStacks[localIndex].push(subscript); assignmentCounters[localIndex]++; } } // Step 2 of 4 -- Rename Phi node uses in Successors for (Block succ : sf.getBlockGraph().getSuccsOf(block)) { // Ignore dummy blocks if (block.getHead() == null && block.getTail() == null) { continue; } for (Unit unit : succ) { PhiExpr phiExpr = Shimple.getPhiExpr(unit); if (phiExpr != null) { // simulate whichPred ValueBox phiArgBox = phiExpr.getArgBox(block); if (phiArgBox == null) { throw new RuntimeException("Assertion failed. Cannot find " + block + " in " + phiExpr); } Local phiArg = (Local) phiArgBox.getValue(); int localIndex = indexOfLocal(phiArg); if (localIndex == -1) { throw new RuntimeException("Assertion failed."); } Stack<Integer> namingStack = namingStacks[localIndex]; if (!namingStack.empty()) { Integer subscript = namingStack.peek(); Local newPhiArg = fetchNewLocal(phiArg, subscript); phiArgBox.setValue(newPhiArg); } } } } // Step 3 of 4 -- Recurse over children. { DominatorTree<Block> dt = sf.getDominatorTree(); for (DominatorNode<Block> childNode : dt.getChildrenOf(dt.getDode(block))) { renameLocalsSearch(childNode.getGode()); } } // Step 4 of 4 -- Tricky name stack updates. for (Local lhsLocal : lhsLocals) { int lhsLocalIndex = indexOfLocal(lhsLocal); if (lhsLocalIndex == -1) { throw new RuntimeException("Assertion failed."); } namingStacks[lhsLocalIndex].pop(); } // And we're done. The renaming process is complete. } /** * Clever convenience function to fetch or create new Local's given a Local and the desired subscript. */ protected Local fetchNewLocal(Local local, Integer subscript) { Local oldLocal = origLocals.contains(local) ? local : newLocalsToOldLocal.get(local); if (subscript == 0) { return oldLocal; } // If the name already exists, makeUniqueLocalNames() will take care of it. String name = oldLocal.getName() + freshSeparator + subscript; Local newLocal = newLocals.get(name); if (newLocal == null) { newLocal = new JimpleLocal(name, oldLocal.getType()); newLocals.put(name, newLocal); newLocalsToOldLocal.put(newLocal, oldLocal); // add proper Local declation body.getLocals().add(newLocal); } return newLocal; } /** * Convenient function that maps new Locals to the originating Local, and finds the appropriate array index into the naming * structures. */ protected int indexOfLocal(Value local) { int localIndex = origLocals.indexOf(local); if (localIndex == -1) { // might be null Local oldLocal = newLocalsToOldLocal.get(local); localIndex = origLocals.indexOf(oldLocal); } return localIndex; } /** * Make sure the locals in the given body all have unique String names. Renaming is done if necessary. */ public void makeUniqueLocalNames() { if (options.standard_local_names()) { LocalNameStandardizer.v().transform(body); return; } Set<String> localNames = new HashSet<String>(); for (Local local : body.getLocals()) { String localName = local.getName(); if (localNames.contains(localName)) { String uniqueName = makeUniqueLocalName(localName, localNames); local.setName(uniqueName); localNames.add(uniqueName); } else { localNames.add(localName); } } } /** * Given a set of Strings, return a new name for dupName that is not currently in the set. */ public static String makeUniqueLocalName(String dupName, Set<String> localNames) { int counter = 1; String newName = dupName; while (localNames.contains(newName)) { newName = dupName + freshSeparator + counter++; } return newName; } public static void setSeparator(String sep) { freshSeparator = sep; } }
12,685
30.40099
125
java
soot
soot-master/src/main/java/soot/shimple/toolkits/graph/GlobalValueNumberer.java
package soot.shimple.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Local; public interface GlobalValueNumberer { public int getGlobalValueNumber(Local local); public boolean areEqual(Local local1, Local local2); }
1,027
31.125
71
java
soot
soot-master/src/main/java/soot/shimple/toolkits/graph/SimpleGlobalValueNumberer.java
package soot.shimple.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import soot.Body; import soot.Local; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.shimple.Shimple; import soot.shimple.ShimpleBody; import soot.shimple.toolkits.graph.ValueGraph.Node; import soot.toolkits.graph.BlockGraph; import soot.toolkits.graph.CompleteBlockGraph; public class SimpleGlobalValueNumberer implements GlobalValueNumberer { protected BlockGraph cfg; protected ValueGraph vg; protected Set<Partition> partitions; protected Map<Node, Partition> nodeToPartition; protected int currentPartitionNumber; public SimpleGlobalValueNumberer(BlockGraph cfg) { this.cfg = cfg; vg = new ValueGraph(cfg); partitions = new HashSet<Partition>(); // not deterministic nodeToPartition = new HashMap<Node, Partition>(); currentPartitionNumber = 0; initPartition(); iterPartition(); } // testing public static void main(String[] args) { // assumes 2 args: Class + Method Scene.v().loadClassAndSupport(args[0]); SootClass sc = Scene.v().getSootClass(args[0]); SootMethod sm = sc.getMethod(args[1]); Body b = sm.retrieveActiveBody(); ShimpleBody sb = Shimple.v().newBody(b); CompleteBlockGraph cfg = new CompleteBlockGraph(sb); SimpleGlobalValueNumberer sgvn = new SimpleGlobalValueNumberer(cfg); System.out.println(sgvn); } public int getGlobalValueNumber(Local local) { Node node = vg.getNode(local); return nodeToPartition.get(node).getPartitionNumber(); } public boolean areEqual(Local local1, Local local2) { Node node1 = vg.getNode(local1); Node node2 = vg.getNode(local2); return (nodeToPartition.get(node1) == nodeToPartition.get(node2)); } protected void initPartition() { Map<String, Partition> labelToPartition = new HashMap<String, Partition>(); Iterator<Node> topNodesIt = vg.getTopNodes().iterator(); while (topNodesIt.hasNext()) { Node node = topNodesIt.next(); String label = node.getLabel(); Partition partition = labelToPartition.get(label); if (partition == null) { partition = new Partition(); partitions.add(partition); labelToPartition.put(label, partition); } partition.add(node); nodeToPartition.put(node, partition); } } protected List<Partition> newPartitions; protected void iterPartition() { newPartitions = new ArrayList<Partition>(); Iterator<Partition> partitionsIt = partitions.iterator(); while (partitionsIt.hasNext()) { Partition partition = partitionsIt.next(); processPartition(partition); } partitions.addAll(newPartitions); } protected void processPartition(Partition partition) { int size = partition.size(); if (size == 0) { return; } Node firstNode = (Node) partition.get(0); Partition newPartition = new Partition(); boolean processNewPartition = false; for (int i = 1; i < size; i++) { Node node = (Node) partition.get(i); if (!childrenAreInSamePartition(firstNode, node)) { partition.remove(i); size--; newPartition.add(node); newPartitions.add(newPartition); nodeToPartition.put(node, newPartition); processNewPartition = true; } } if (processNewPartition) { processPartition(newPartition); } } protected boolean childrenAreInSamePartition(Node node1, Node node2) { boolean ordered = node1.isOrdered(); if (ordered != node2.isOrdered()) { throw new RuntimeException("Assertion failed."); } List<Node> children1 = node1.getChildren(); List<Node> children2 = node2.getChildren(); int numberOfChildren = children1.size(); if (children2.size() != numberOfChildren) { return false; } if (ordered) { for (int i = 0; i < numberOfChildren; i++) { Node child1 = children1.get(i); Node child2 = children2.get(i); if (nodeToPartition.get(child1) != nodeToPartition.get(child2)) { return false; } } } else { for (int i = 0; i < numberOfChildren; i++) { Node child1 = children1.get(i); for (int j = i; j < numberOfChildren; j++) { Node child2 = children2.get(j); if (nodeToPartition.get(child1) == nodeToPartition.get(child2)) { if (j != i) { children2.remove(j); children2.add(i, child2); } break; } // last iteration, no match if ((j + 1) == numberOfChildren) { return false; } } } } return true; } public String toString() { StringBuffer tmp = new StringBuffer(); Body b = cfg.getBody(); Iterator localsIt = b.getLocals().iterator(); while (localsIt.hasNext()) { Local local = (Local) localsIt.next(); tmp.append(local + "\t" + getGlobalValueNumber(local) + "\n"); } /* * Iterator partitionsIt = partitions.iterator(); while(partitionsIt.hasNext()){ Partition partition = (Partition) * partitionsIt.next(); int partitionNumber = partition.getPartitionNumber(); * * Iterator partitionIt = partition.iterator(); while(partitionIt.hasNext()){ Local local = * vg.getLocal((Node)partitionIt.next()); if(local == null) continue; tmp.append(local + "\t" + partitionNumber + "\n"); * } } */ return tmp.toString(); } protected class Partition extends ArrayList { protected int partitionNumber; protected Partition() { super(); partitionNumber = currentPartitionNumber++; } protected int getPartitionNumber() { return partitionNumber; } } }
6,740
27.685106
124
java
soot
soot-master/src/main/java/soot/shimple/toolkits/graph/ValueGraph.java
package soot.shimple.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.Body; import soot.Local; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.UnitPrinter; import soot.Value; import soot.ValueBox; import soot.jimple.AddExpr; import soot.jimple.AndExpr; import soot.jimple.ArrayRef; import soot.jimple.BinopExpr; import soot.jimple.CastExpr; import soot.jimple.CaughtExceptionRef; import soot.jimple.CmpExpr; import soot.jimple.CmpgExpr; import soot.jimple.CmplExpr; import soot.jimple.Constant; import soot.jimple.DefinitionStmt; import soot.jimple.DivExpr; import soot.jimple.EqExpr; import soot.jimple.Expr; import soot.jimple.FloatConstant; import soot.jimple.GeExpr; import soot.jimple.GtExpr; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceOfExpr; import soot.jimple.IntConstant; import soot.jimple.InterfaceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.LeExpr; import soot.jimple.LengthExpr; import soot.jimple.LongConstant; import soot.jimple.LtExpr; import soot.jimple.MulExpr; import soot.jimple.NeExpr; import soot.jimple.NegExpr; import soot.jimple.NewArrayExpr; import soot.jimple.NewExpr; import soot.jimple.NewMultiArrayExpr; import soot.jimple.NullConstant; import soot.jimple.OrExpr; import soot.jimple.ParameterRef; import soot.jimple.Ref; import soot.jimple.RemExpr; import soot.jimple.ShlExpr; import soot.jimple.ShrExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticFieldRef; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.jimple.SubExpr; import soot.jimple.ThisRef; import soot.jimple.UnopExpr; import soot.jimple.UshrExpr; import soot.jimple.VirtualInvokeExpr; import soot.jimple.XorExpr; import soot.shimple.AbstractShimpleValueSwitch; import soot.shimple.PhiExpr; import soot.shimple.Shimple; import soot.shimple.ShimpleBody; import soot.toolkits.graph.Block; import soot.toolkits.graph.BlockGraph; import soot.toolkits.graph.CompleteBlockGraph; import soot.toolkits.graph.Orderer; import soot.toolkits.graph.PseudoTopologicalOrderer; import soot.util.Switch; // consider implementing DirectedGraph public class ValueGraph { // can we handle field writes/reads? // Issues: - does the field write DOMINATE field uses? // - do intervening method calls have SIDE-EFFECTs? // Affects fields whether of simple type or ref type // - CONCURRENT writes? protected Map<Value, Node> localToNode; protected Map<Node, Value> nodeToLocal; protected List<Node> nodeList; protected int currentNodeNumber; public ValueGraph(BlockGraph cfg) { if (!(cfg.getBody() instanceof ShimpleBody)) { throw new RuntimeException("ValueGraph requires SSA form"); } localToNode = new HashMap<Value, Node>(); nodeToLocal = new HashMap<Node, Value>(); nodeList = new ArrayList<Node>(); currentNodeNumber = 0; Orderer<Block> pto = new PseudoTopologicalOrderer<Block>(); List<Block> blocks = pto.newList(cfg, false); for (Iterator<Block> blocksIt = blocks.iterator(); blocksIt.hasNext();) { Block block = (Block) blocksIt.next(); for (Iterator<Unit> blockIt = block.iterator(); blockIt.hasNext();) { handleStmt((Stmt) blockIt.next()); } } for (Node node : nodeList) { node.patchStubs(); } } protected void handleStmt(Stmt stmt) { if (!(stmt instanceof DefinitionStmt)) { return; } DefinitionStmt dStmt = (DefinitionStmt) stmt; Value leftOp = dStmt.getLeftOp(); if (!(leftOp instanceof Local)) { return; } Value rightOp = dStmt.getRightOp(); Node node = fetchGraph(rightOp); localToNode.put(leftOp, node); // only update for non-trivial assignments and non-stubs if (!(rightOp instanceof Local) && !node.isStub()) { nodeToLocal.put(node, leftOp); } } protected Node fetchNode(Value value) { Node ret = null; if (value instanceof Local) { // assumption: the local definition has already been processed ret = getNode(value); // or maybe not... a PhiExpr may refer to a local that // has not been seen yet in the pseudo topological order. // use a stub node in that case and fill in the details later. if (ret == null) { ret = new Node(value, true); } } else { ret = new Node(value); } return ret; } protected Node fetchGraph(Value value) { AbstractShimpleValueSwitch vs; value.apply(vs = new AbstractShimpleValueSwitch() { /** * No default case, we implement explicit handling for each situation. **/ public void defaultCase(Object object) { throw new RuntimeException("Internal error: " + object + " unhandled case."); } /** * Handle a trivial assignment. **/ public void caseLocal(Local l) { setResult(fetchNode(l)); } /** * Handle other simple assignments. **/ public void handleConstant(Constant constant) { setResult(fetchNode(constant)); } /** * Assume nothing about Refs. **/ public void handleRef(Ref ref) { setResult(fetchNode(ref)); } public void handleBinop(BinopExpr binop, boolean ordered) { Node nop1 = fetchNode(binop.getOp1()); Node nop2 = fetchNode(binop.getOp2()); List<Node> children = new ArrayList<Node>(); children.add(nop1); children.add(nop2); setResult(new Node(binop, ordered, children)); } // *** FIXME // *** assume non-equality by default // *** what about New expressions? public void handleUnknown(Expr expr) { setResult(fetchNode(expr)); } public void handleUnop(UnopExpr unop) { Node nop = fetchNode(unop.getOp()); List<Node> child = Collections.<Node>singletonList(nop); setResult(new Node(unop, true, child)); } public void caseFloatConstant(FloatConstant v) { handleConstant(v); } public void caseIntConstant(IntConstant v) { handleConstant(v); } public void caseLongConstant(LongConstant v) { handleConstant(v); } public void caseNullConstant(NullConstant v) { handleConstant(v); } public void caseStringConstant(StringConstant v) { handleConstant(v); } public void caseArrayRef(ArrayRef v) { handleRef(v); } public void caseStaticFieldRef(StaticFieldRef v) { handleRef(v); } public void caseInstanceFieldRef(InstanceFieldRef v) { handleRef(v); } public void caseParameterRef(ParameterRef v) { handleRef(v); } public void caseCaughtExceptionRef(CaughtExceptionRef v) { handleRef(v); } public void caseThisRef(ThisRef v) { handleRef(v); } public void caseAddExpr(AddExpr v) { handleBinop(v, false); } public void caseAndExpr(AndExpr v) { handleBinop(v, false); } public void caseCmpExpr(CmpExpr v) { handleBinop(v, true); } public void caseCmpgExpr(CmpgExpr v) { handleBinop(v, true); } public void caseCmplExpr(CmplExpr v) { handleBinop(v, true); } public void caseDivExpr(DivExpr v) { handleBinop(v, true); } public void caseEqExpr(EqExpr v) { handleBinop(v, false); } public void caseNeExpr(NeExpr v) { handleBinop(v, false); } public void caseGeExpr(GeExpr v) { handleBinop(v, true); } public void caseGtExpr(GtExpr v) { handleBinop(v, true); } public void caseLeExpr(LeExpr v) { handleBinop(v, true); } public void caseLtExpr(LtExpr v) { handleBinop(v, true); } public void caseMulExpr(MulExpr v) { handleBinop(v, false); } // *** check public void caseOrExpr(OrExpr v) { handleBinop(v, false); } public void caseRemExpr(RemExpr v) { handleBinop(v, true); } public void caseShlExpr(ShlExpr v) { handleBinop(v, true); } public void caseShrExpr(ShrExpr v) { handleBinop(v, true); } public void caseUshrExpr(UshrExpr v) { handleBinop(v, true); } public void caseSubExpr(SubExpr v) { handleBinop(v, true); } // *** check public void caseXorExpr(XorExpr v) { handleBinop(v, false); } public void caseInterfaceInvokeExpr(InterfaceInvokeExpr v) { handleUnknown(v); } public void caseSpecialInvokeExpr(SpecialInvokeExpr v) { handleUnknown(v); } public void caseStaticInvokeExpr(StaticInvokeExpr v) { handleUnknown(v); } public void caseVirtualInvokeExpr(VirtualInvokeExpr v) { handleUnknown(v); } /** * Handle like a trivial assignment. **/ public void caseCastExpr(CastExpr v) { setResult(fetchNode(v.getOp())); } /** * Handle like an ordered binop. **/ public void caseInstanceOfExpr(InstanceOfExpr v) { Node nop1 = fetchNode(v.getOp()); Value op2 = new TypeValueWrapper(v.getCheckType()); Node nop2 = fetchNode(op2); List<Node> children = new ArrayList<Node>(); children.add(nop1); children.add(nop2); setResult(new Node(v, true, children)); } // *** perhaps New expressions require special handling? public void caseNewArrayExpr(NewArrayExpr v) { handleUnknown(v); } public void caseNewMultiArrayExpr(NewMultiArrayExpr v) { handleUnknown(v); } public void caseNewExpr(NewExpr v) { handleUnknown(v); } public void caseLengthExpr(LengthExpr v) { handleUnop(v); } public void caseNegExpr(NegExpr v) { handleUnop(v); } public void casePhiExpr(PhiExpr v) { List<Node> children = new ArrayList<Node>(); Iterator<Value> argsIt = v.getValues().iterator(); while (argsIt.hasNext()) { Value arg = argsIt.next(); children.add(fetchNode(arg)); } // relies on Phi nodes in same block having a // consistent sort order... setResult(new Node(v, true, children)); } }); return ((Node) vs.getResult()); } public Node getNode(Value local) { return localToNode.get(local); } // *** Check for non-determinism public Collection<Node> getTopNodes() { return localToNode.values(); } public Local getLocal(Node node) { return (Local) nodeToLocal.get(node); } public String toString() { StringBuffer tmp = new StringBuffer(); for (int i = 0; i < nodeList.size(); i++) { tmp.append(nodeList.get(i)); tmp.append("\n"); } return tmp.toString(); } // testing public static void main(String[] args) { // assumes 2 args: Class + Method Scene.v().loadClassAndSupport(args[0]); SootClass sc = Scene.v().getSootClass(args[0]); SootMethod sm = sc.getMethod(args[1]); Body b = sm.retrieveActiveBody(); ShimpleBody sb = Shimple.v().newBody(b); CompleteBlockGraph cfg = new CompleteBlockGraph(sb); ValueGraph vg = new ValueGraph(cfg); System.out.println(vg); } public class Node { protected int nodeNumber; protected Value node; protected String nodeLabel; protected boolean ordered; protected List<Node> children; protected boolean stub = false; // stub node protected Node(Value local, boolean ignored) { this.stub = true; setNode(local); } protected void patchStubs() { // can't patch self if (isStub()) { throw new RuntimeException("Assertion failed."); } // if any immediate children are stubs, patch them for (int i = 0; i < children.size(); i++) { Node child = children.get(i); if (child.isStub()) { Node newChild = localToNode.get(child.node); if (newChild == null || newChild.isStub()) { throw new RuntimeException("Assertion failed."); } children.set(i, newChild); } } } protected void checkIfStub() { if (isStub()) { throw new RuntimeException("Assertion failed: Attempted operation on invalid node (stub)"); } } protected Node(Value node) { this(node, true, Collections.<Node>emptyList()); } protected Node(Value node, boolean ordered, List<Node> children) { setNode(node); setOrdered(ordered); setChildren(children); // updateLabel() relies on nodeNumber being set nodeNumber = currentNodeNumber++; updateLabel(); nodeList.add(nodeNumber, this); } protected void setNode(Value node) { this.node = node; } protected void setOrdered(boolean ordered) { this.ordered = ordered; } protected void setChildren(List<Node> children) { this.children = children; } protected void updateLabel() { if (!children.isEmpty()) { nodeLabel = node.getClass().getName(); if (node instanceof PhiExpr) { nodeLabel = nodeLabel + ((PhiExpr) node).getBlockId(); } } else { // *** FIXME // NewExpr // NewArrayExpr // NewMultiArrayExpr // Ref // FieldRef? // InstanceFieldRef? // IdentityRef? // ArrayRef? // CaughtExceptionRef // InvokeExpr? // InstanceInvokeExpr? // InterfaceInvokeExpr? // SpecialInvokeExpr // StaticInvokeExpr // VirtualInvokeExpr nodeLabel = node.toString(); if ((node instanceof NewExpr) || (node instanceof NewArrayExpr) || (node instanceof NewMultiArrayExpr) || (node instanceof Ref) || (node instanceof InvokeExpr)) { nodeLabel = nodeLabel + " " + getNodeNumber(); } } } public boolean isStub() { return stub; } public String getLabel() { checkIfStub(); return nodeLabel; } public boolean isOrdered() { checkIfStub(); return ordered; } public List<Node> getChildren() { checkIfStub(); return children; // return Collections.unmodifiableList(children); } public int getNodeNumber() { checkIfStub(); return nodeNumber; } public String toString() { checkIfStub(); StringBuffer tmp = new StringBuffer(); Local local = getLocal(this); if (local != null) { tmp.append(local.toString()); } tmp.append("\tNode " + getNodeNumber() + ": " + getLabel()); List<Node> children = getChildren(); if (!children.isEmpty()) { tmp.append(" [" + (isOrdered() ? "ordered" : "unordered") + ": "); for (int i = 0; i < children.size(); i++) { if (i != 0) { tmp.append(", "); } tmp.append(children.get(i).getNodeNumber()); } tmp.append("]"); } return tmp.toString(); } } protected static class TypeValueWrapper implements Value { protected Type type; protected TypeValueWrapper(Type type) { this.type = type; } public List<ValueBox> getUseBoxes() { return Collections.<ValueBox>emptyList(); } public Type getType() { return type; } public Object clone() { return new TypeValueWrapper(type); } public void toString(UnitPrinter up) { up.literal("[Wrapped] " + type); } public void apply(Switch sw) { throw new RuntimeException("Not Implemented."); } public boolean equals(Object o) { if (!(o instanceof TypeValueWrapper)) { return false; } return getType().equals(((TypeValueWrapper) o).getType()); } public int hashCode() { return getType().hashCode(); } public boolean equivTo(Object o) { return equals(o); } public int equivHashCode() { return hashCode(); } } }
17,299
24.292398
110
java
soot
soot-master/src/main/java/soot/shimple/toolkits/scalar/SConstantPropagatorAndFolder.java
package soot.shimple.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.Local; import soot.PhaseOptions; import soot.Singletons; import soot.Unit; import soot.UnitBox; import soot.UnitBoxOwner; import soot.Value; import soot.ValueBox; import soot.jimple.Constant; import soot.jimple.DefinitionStmt; import soot.jimple.GotoStmt; import soot.jimple.IfStmt; import soot.jimple.IntConstant; import soot.jimple.Jimple; import soot.jimple.LookupSwitchStmt; import soot.jimple.Stmt; import soot.jimple.TableSwitchStmt; import soot.options.Options; import soot.shimple.ShimpleBody; import soot.shimple.toolkits.scalar.SEvaluator.BottomConstant; import soot.shimple.toolkits.scalar.SEvaluator.MetaConstant; import soot.shimple.toolkits.scalar.SEvaluator.TopConstant; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.ArraySparseSet; import soot.toolkits.scalar.FlowSet; import soot.toolkits.scalar.ForwardBranchedFlowAnalysis; import soot.toolkits.scalar.Pair; import soot.toolkits.scalar.UnitValueBoxPair; import soot.util.Chain; /** * A powerful constant propagator and folder based on an algorithm sketched by Cytron et al that takes conditional control * flow into account. This optimization demonstrates some of the benefits of SSA -- particularly the fact that Phi nodes * represent natural merge points in the control flow. * * @author Navindra Umanee * @see <a href="http://citeseer.nj.nec.com/cytron91efficiently.html">Efficiently Computing Static Single Assignment Form and * the Control Dependence Graph</a> **/ public class SConstantPropagatorAndFolder extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(SConstantPropagatorAndFolder.class); public SConstantPropagatorAndFolder(Singletons.Global g) { } public static SConstantPropagatorAndFolder v() { return G.v().soot_shimple_toolkits_scalar_SConstantPropagatorAndFolder(); } protected ShimpleBody sb; protected boolean debug; @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { if (!(b instanceof ShimpleBody)) { throw new RuntimeException("SConstantPropagatorAndFolder requires a ShimpleBody."); } ShimpleBody castBody = (ShimpleBody) b; if (!castBody.isSSA()) { throw new RuntimeException("ShimpleBody is not in proper SSA form as required by SConstantPropagatorAndFolder. " + "You may need to rebuild it or use ConstantPropagatorAndFolder instead."); } this.sb = castBody; this.debug = Options.v().debug() || castBody.getOptions().debug(); if (Options.v().verbose()) { logger.debug("[" + castBody.getMethod().getName() + "] Propagating and folding constants (SSA)..."); } // *** FIXME: What happens when Shimple is built with another UnitGraph? SCPFAnalysis scpf = new SCPFAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(castBody)); propagateResults(scpf.getResults()); if (PhaseOptions.getBoolean(options, "prune-cfg")) { removeStmts(scpf.getDeadStmts()); replaceStmts(scpf.getStmtsToReplace()); } } /** * Propagates constants to the definition and uses of the relevant locals given a mapping. Notice that we use the Shimple * implementation of LocalDefs and LocalUses. **/ protected void propagateResults(Map<Local, Constant> localToConstant) { ShimpleLocalDefs localDefs = new ShimpleLocalDefs(sb); ShimpleLocalUses localUses = new ShimpleLocalUses(sb); for (Local local : sb.getLocals()) { Constant constant = localToConstant.get(local); if (constant instanceof MetaConstant) { continue; } // update definition { DefinitionStmt stmt = (DefinitionStmt) localDefs.getDefsOf(local).get(0); ValueBox defSrcBox = stmt.getRightOpBox(); Value defSrcOld = defSrcBox.getValue(); if (defSrcBox.canContainValue(constant)) { defSrcBox.setValue(constant); // remove dangling pointers if (defSrcOld instanceof UnitBoxOwner) { ((UnitBoxOwner) defSrcOld).clearUnitBoxes(); } } else if (debug) { logger.warn("Couldn't propagate constant " + constant + " to box " + defSrcBox.getValue() + " in unit " + stmt); } } // update uses for (UnitValueBoxPair pair : localUses.getUsesOf(local)) { ValueBox useBox = pair.getValueBox(); if (useBox.canContainValue(constant)) { useBox.setValue(constant); } else if (debug) { logger.warn( "Couldn't propagate constant " + constant + " to box " + useBox.getValue() + " in unit " + pair.getUnit()); } } } } /** * Removes the given list of fall through IfStmts from the body. **/ protected void removeStmts(List<IfStmt> deadStmts) { Chain<Unit> units = sb.getUnits(); for (IfStmt dead : deadStmts) { units.remove(dead); dead.clearUnitBoxes(); } } /** * Replaces conditional branches by unconditional branches as given by the mapping. **/ protected void replaceStmts(Map<Stmt, GotoStmt> stmtsToReplace) { Chain<Unit> units = sb.getUnits(); for (Map.Entry<Stmt, GotoStmt> e : stmtsToReplace.entrySet()) { // important not to call clearUnitBoxes() on key since // replacement uses the same UnitBox units.swapWith(e.getKey(), e.getValue()); } } } /** * The actual branching flow analysis implementation. Briefly, a sketch of the sketch from the Cytron et al paper: * * <p> * Initially the algorithm assumes that each edge is unexecutable (the entry nodes are reachable) and that each variable is * constant with an unknown value, Top. Assumptions are corrected until they stabilise. * * <p> * For example, if <tt>q</tt> is found to be not a constant (Bottom) in <tt>if(q == 0) goto label1</tt> then both edges * leaving the the statement are considered executable, if <tt>q</tt> is found to be a constant then only one of the edges * are executable. * * <p> * Whenever a reachable definition statement such as "x = 3" is found, the information is propagated to all uses of x (this * works due to the SSA property). * * <p> * Perhaps the crucial point is that if a node such as <tt>x = * Phi(x_1, x_2)</tt> is ever found, information on <tt>x</tt> is assumed as follows: * * <ul> * <li>If <tt>x_1</tt> and <tt>x_2</tt> are the same assumed constant, <tt>x</tt> is assumed to be that constant. If they are * not the same constant, <tt>x</tt> is Bottom.</li> * * <li>If either one is Top and the other is a constant, <tt>x</tt> is assumed to be the same as the known constant.</li> * * <li>If either is Bottom, <tt>x</tt> is assumed to be Bottom.</li> * </ul> * * <p> * The crucial point about the crucial point is that if definitions of <tt>x_1</tt> or <tt>x_2</tt> are never reached, the * Phi node will still assume them to be Top and hence they will not influence the decision as to whether <tt>x</tt> is a * constant or not. **/ class SCPFAnalysis extends ForwardBranchedFlowAnalysis<FlowSet<Object>> { protected final static ArraySparseSet<Object> EMPTY_SET = new ArraySparseSet<Object>(); /** * A mapping of the locals to their current assumed constant value (which may be Top or Bottom). **/ protected final Map<Local, Constant> localToConstant; /** * A map from conditional branches to their possible replacement unit, an unconditional branch. **/ protected final Map<Stmt, GotoStmt> stmtToReplacement; /** * A list of IfStmts that always fall through. **/ protected final List<IfStmt> deadStmts; public SCPFAnalysis(UnitGraph graph) { super(graph); this.stmtToReplacement = new HashMap<Stmt, GotoStmt>(); this.deadStmts = new ArrayList<IfStmt>(); this.localToConstant = new HashMap<Local, Constant>(graph.size() * 2 + 1, 0.7f); // initialise localToConstant map -- assume all scalars are constant (Top) { Map<Local, Constant> ref = this.localToConstant; for (Local local : graph.getBody().getLocals()) { ref.put(local, TopConstant.v()); } } doAnalysis(); } /** * Returns the localToConstant map. **/ public Map<Local, Constant> getResults() { return localToConstant; } /** * Returns the list of fall through IfStmts. **/ public List<IfStmt> getDeadStmts() { return deadStmts; } /** * Returns a Map from conditional branches to the unconditional branches that can replace them. **/ public Map<Stmt, GotoStmt> getStmtsToReplace() { return stmtToReplacement; } // *** NOTE: this is here because ForwardBranchedFlowAnalysis does // *** not handle exceptional control flow properly in the // *** dataflow analysis. this should be removed when // *** ForwardBranchedFlowAnalysis is fixed. @Override protected boolean treatTrapHandlersAsEntries() { return true; } /** * If a node has empty IN sets we assume that it is not reachable. Hence, we initialise the entry sets to be non-empty to * indicate that they are reachable. **/ @Override protected FlowSet<Object> entryInitialFlow() { FlowSet<Object> entrySet = EMPTY_SET.emptySet(); entrySet.add(TopConstant.v()); return entrySet; } /** * All other nodes are assumed to be unreachable by default. **/ @Override protected FlowSet<Object> newInitialFlow() { return EMPTY_SET.emptySet(); } /** * Since we are interested in control flow from all branches, take the union. **/ @Override protected void merge(FlowSet<Object> in1, FlowSet<Object> in2, FlowSet<Object> out) { in1.union(in2, out); } /** * Defer copy to FlowSet. **/ @Override protected void copy(FlowSet<Object> source, FlowSet<Object> dest) { source.copy(dest); } /** * If a node has an empty in set, it is considered unreachable. Otherwise the node is examined and if any assumptions have * to be corrected, a Pair containing the corrected assumptions is flowed to the reachable nodes. If no assumptions have to * be corrected then no information other than the in set is propagated to the reachable nodes. * * <p> * Pair serves no other purpose than to keep the analysis flowing for as long as needed. The final results are accumulated * in the localToConstant map. **/ @Override protected void flowThrough(FlowSet<Object> in, final Unit s, List<FlowSet<Object>> fallOut, List<FlowSet<Object>> branchOuts) { if (in.isEmpty()) { return; // not reachable } FlowSet<Object> fin = in.clone(); // If s is a definition, check if any assumptions have to be corrected. Pair<Unit, Constant> pair = processDefinitionStmt(s); if (pair != null) { fin.add(pair); } // normal, non-branching statement if (!s.branches() && s.fallsThrough()) { for (FlowSet<Object> fallSet : fallOut) { fallSet.union(fin); } return; } /* determine which nodes are reachable. */ boolean conservative = true; boolean fall = false; boolean branch = false; FlowSet<Object> oneBranch = null; if (s instanceof IfStmt) { IfStmt ifStmt = (IfStmt) s; Constant constant = SEvaluator.getFuzzyConstantValueOf(ifStmt.getCondition(), localToConstant); if (constant instanceof TopConstant) { // no flow return; } else if (constant instanceof BottomConstant) { // flow both ways deadStmts.remove(ifStmt); stmtToReplacement.remove(ifStmt); } else { // determine whether to flow through or branch conservative = false; if (IntConstant.v(0).equals(constant)) { fall = true; deadStmts.add(ifStmt); } else if (IntConstant.v(1).equals(constant)) { branch = true; stmtToReplacement.put(ifStmt, Jimple.v().newGotoStmt(ifStmt.getTargetBox())); } else { throw new RuntimeException("IfStmt condition must be 0 or 1! Found: " + constant); } } } else if (s instanceof TableSwitchStmt) { TableSwitchStmt table = (TableSwitchStmt) s; Constant keyC = SEvaluator.getFuzzyConstantValueOf(table.getKey(), localToConstant); if (keyC instanceof TopConstant) { // no flow return; } else if (keyC instanceof BottomConstant) { // flow all branches stmtToReplacement.remove(table); } else if (keyC instanceof IntConstant) { // find the one branch we need to flow to conservative = false; int index = ((IntConstant) keyC).value - table.getLowIndex(); UnitBox branchBox = (index < 0 || index > table.getHighIndex()) ? table.getDefaultTargetBox() : table.getTargetBox(index); stmtToReplacement.put(table, Jimple.v().newGotoStmt(branchBox)); oneBranch = branchOuts.get(table.getUnitBoxes().indexOf(branchBox)); } else { // flow all branches } } else if (s instanceof LookupSwitchStmt) { LookupSwitchStmt lookup = (LookupSwitchStmt) s; Constant keyC = SEvaluator.getFuzzyConstantValueOf(lookup.getKey(), localToConstant); if (keyC instanceof TopConstant) { // no flow return; } else if (keyC instanceof BottomConstant) { // flow all branches stmtToReplacement.remove(lookup); } else if (keyC instanceof IntConstant) { // find the one branch we need to flow to conservative = false; int index = lookup.getLookupValues().indexOf(keyC); UnitBox branchBox = (index < 0) ? lookup.getDefaultTargetBox() : lookup.getTargetBox(index); stmtToReplacement.put(lookup, Jimple.v().newGotoStmt(branchBox)); oneBranch = branchOuts.get(lookup.getUnitBoxes().indexOf(branchBox)); } else { // flow all branches } } // conservative control flow estimates if (conservative) { fall = s.fallsThrough(); branch = s.branches(); } if (fall) { for (FlowSet<Object> fallSet : fallOut) { fallSet.union(fin); } } if (branch) { for (FlowSet<Object> branchSet : branchOuts) { branchSet.union(fin); } } if (oneBranch != null) { oneBranch.union(fin); } } /** * Returns (Unit, Constant) Pair if an assumption has changed due to the fact that u is reachable, else returns null. **/ protected Pair<Unit, Constant> processDefinitionStmt(Unit u) { if (u instanceof DefinitionStmt) { DefinitionStmt dStmt = (DefinitionStmt) u; Value value = dStmt.getLeftOp(); if (value instanceof Local) { Local local = (Local) value; /* update assumptions */ if (merge(local, SEvaluator.getFuzzyConstantValueOf(dStmt.getRightOp(), localToConstant))) { return new Pair<>(u, localToConstant.get(local)); } } } return null; } /** * Verifies if the given assumption "constant" changes the previous assumption about "local" and merges the information * into the localToConstant map. Returns true if something changed. **/ protected boolean merge(Local local, Constant constant) { Constant current = localToConstant.get(local); if (current instanceof BottomConstant) { return false; } if (current instanceof TopConstant) { localToConstant.put(local, constant); return true; } if (current.equals(constant)) { return false; } // not equal localToConstant.put(local, BottomConstant.v()); return true; } }
16,715
32.906694
125
java
soot
soot-master/src/main/java/soot/shimple/toolkits/scalar/SEvaluator.java
package soot.shimple.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.Local; import soot.Type; import soot.UnitBoxOwner; import soot.UnknownType; import soot.Value; import soot.ValueBox; import soot.jimple.Constant; import soot.jimple.Expr; import soot.jimple.toolkits.scalar.Evaluator; import soot.shimple.PhiExpr; import soot.util.Switch; /** * Extension of soot.jimple.toolkits.scalar.Evaluator to handle Phi expressions. * * @author Navindra Umanee. * @see soot.jimple.toolkits.scalar.Evaluator * @see SConstantPropagatorAndFolder **/ public class SEvaluator { /** * Returns true if given value is determined to be constant valued, false otherwise **/ public static boolean isValueConstantValued(Value op) { if (op instanceof PhiExpr) { Constant firstConstant = null; for (Value arg : ((PhiExpr) op).getValues()) { if (!(arg instanceof Constant)) { return false; } if (firstConstant == null) { firstConstant = (Constant) arg; } else if (!firstConstant.equals(arg)) { return false; } } return true; } return Evaluator.isValueConstantValued(op); } /** * Returns the constant value of <code>op</code> if it is easy to find the constant value; else returns <code>null</code>. **/ public static Value getConstantValueOf(Value op) { if (op instanceof PhiExpr) { return isValueConstantValued(op) ? ((PhiExpr) op).getValue(0) : null; } else { return Evaluator.getConstantValueOf(op); } } /** * If a normal expression contains Bottom, always return Bottom. Otherwise, if a normal expression contains Top, returns * Top. Else determine the constant value of the expression if possible, if not return Bottom. * * <p> * If a Phi expression contains Bottom, always return Bottom. Otherwise, if all the constant arguments are the same * (ignoring Top and locals) return that constant or Top if no concrete constant is present, else return Bottom. * * @see SEvaluator.TopConstant * @see SEvaluator.BottomConstant **/ public static Constant getFuzzyConstantValueOf(Value v) { if (v instanceof Constant) { return (Constant) v; } else if (v instanceof Local) { return BottomConstant.v(); } else if (!(v instanceof Expr)) { return BottomConstant.v(); } Constant constant = null; if (v instanceof PhiExpr) { PhiExpr phi = (PhiExpr) v; for (Value arg : phi.getValues()) { if (!(arg instanceof Constant)) { continue; } if (arg instanceof TopConstant) { continue; } if (constant == null) { constant = (Constant) arg; } else if (!constant.equals(arg)) { constant = BottomConstant.v(); break; } } if (constant == null) { constant = TopConstant.v(); } } else { for (ValueBox name : v.getUseBoxes()) { Value value = name.getValue(); if (value instanceof BottomConstant) { constant = BottomConstant.v(); break; } if (value instanceof TopConstant) { constant = TopConstant.v(); } } if (constant == null) { constant = (Constant) getConstantValueOf(v); } if (constant == null) { constant = BottomConstant.v(); } } return constant; } /** * Get the constant value of the expression given the assumptions in the localToConstant map (may contain Top and Bottom). * Does not change expression. * * @see SEvaluator.TopConstant * @see SEvaluator.BottomConstant **/ public static Constant getFuzzyConstantValueOf(Value v, Map<Local, Constant> localToConstant) { if (v instanceof Constant) { return (Constant) v; } else if (v instanceof Local) { return localToConstant.get((Local) v); } else if (!(v instanceof Expr)) { return BottomConstant.v(); } /* clone expr and update the clone with our assumptions */ Expr expr = (Expr) v.clone(); for (ValueBox useBox : expr.getUseBoxes()) { Value use = useBox.getValue(); if (use instanceof Local) { Constant constant = localToConstant.get((Local) use); if (useBox.canContainValue(constant)) { useBox.setValue(constant); } } } // oops -- clear spurious pointers to the unit chain! if (expr instanceof UnitBoxOwner) { ((UnitBoxOwner) expr).clearUnitBoxes(); } /* evaluate the expression */ return getFuzzyConstantValueOf(expr); } /** * Head of a new hierarchy of constants -- Top and Bottom. **/ public static abstract class MetaConstant extends Constant { } /** * Top i.e. assumed to be a constant, but of unknown value. **/ public static class TopConstant extends MetaConstant { private static final TopConstant constant = new TopConstant(); private TopConstant() { } public static Constant v() { return constant; } @Override public Type getType() { return UnknownType.v(); } @Override public void apply(Switch sw) { throw new RuntimeException("Not implemented."); } } /** * Bottom i.e. known not to be a constant. **/ public static class BottomConstant extends MetaConstant { private static final BottomConstant constant = new BottomConstant(); private BottomConstant() { } public static Constant v() { return constant; } @Override public Type getType() { return UnknownType.v(); } @Override public void apply(Switch sw) { throw new RuntimeException("Not implemented."); } } }
6,571
26.157025
124
java
soot
soot-master/src/main/java/soot/shimple/toolkits/scalar/ShimpleLocalDefs.java
package soot.shimple.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.List; import java.util.Map; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.shimple.ShimpleBody; import soot.toolkits.scalar.LocalDefs; import soot.util.Chain; /** * This class implements the LocalDefs interface for Shimple. ShimpleLocalDefs can be used in conjunction with * SimpleLocalUses to provide Definition/Use and Use/Definition chains in SSA. * * <p> * This implementation can be considered a small demo for how SSA can be put to good use since it is much simpler than * soot.toolkits.scalar.SimpleLocalDefs. Shimple can often be treated as Jimple with the added benefits of SSA assumptions. * * <p> * In addition to the interface required by LocalDefs, ShimpleLocalDefs also provides a method for obtaining the definition * Unit given only the Local. * * @author Navindra Umanee * @see ShimpleLocalUses * @see soot.toolkits.scalar.SimpleLocalDefs * @see soot.toolkits.scalar.SimpleLocalUses **/ public class ShimpleLocalDefs implements LocalDefs { protected Map<Value, List<Unit>> localToDefs; /** * Build a LocalDefs interface from a ShimpleBody. Proper SSA form is required, otherwise correct behaviour is not * guaranteed. **/ public ShimpleLocalDefs(ShimpleBody sb) { // Instead of rebuilding the ShimpleBody without the // programmer's knowledge, throw a RuntimeException if (!sb.isSSA()) { throw new RuntimeException("ShimpleBody is not in proper SSA form as required by ShimpleLocalDefs. " + "You may need to rebuild it or use SimpleLocalDefs instead."); } // build localToDefs map simply by iterating through all the // units in the body and saving the unique definition site for // each local -- no need for fancy analysis Chain<Unit> unitsChain = sb.getUnits(); this.localToDefs = new HashMap<Value, List<Unit>>(unitsChain.size() * 2 + 1, 0.7f); for (Unit unit : unitsChain) { for (ValueBox vb : unit.getDefBoxes()) { Value value = vb.getValue(); // only map locals if (value instanceof Local) { localToDefs.put(value, Collections.<Unit>singletonList(unit)); } } } } /** * Unconditionally returns the definition site of a local (as a singleton list). **/ @Override public List<Unit> getDefsOf(Local l) { List<Unit> defs = localToDefs.get(l); if (defs == null) { throw new RuntimeException("Local not found in Body."); } return defs; } /** * Returns the definition site for a Local at a certain point (Unit) in a method as a singleton list. * * @param l * the Local in question. * @param s * a unit that specifies the method context (location) to query for the definitions of the Local. * @return a singleton list containing the definition site. **/ @Override public List<Unit> getDefsOfAt(Local l, Unit s) { // For consistency with SimpleLocalDefs, check that the local is indeed used // in the given Unit. This neatly sidesteps the problem of checking whether // the local is actually defined at the given point in the program. { boolean defined = false; for (ValueBox vb : s.getUseBoxes()) { if (vb.getValue().equals(l)) { defined = true; break; } } if (!defined) { throw new RuntimeException("Illegal LocalDefs query; local " + l + " is not being used at " + s); } } return getDefsOf(l); } }
4,432
33.364341
123
java
soot
soot-master/src/main/java/soot/shimple/toolkits/scalar/ShimpleLocalUses.java
package soot.shimple.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.shimple.ShimpleBody; import soot.toolkits.scalar.LocalUses; import soot.toolkits.scalar.UnitValueBoxPair; /** * This class implements the LocalUses interface for Shimple. ShimpleLocalUses can be used in conjunction with * SimpleLocalDefs to provide Definition/Use and Use/Definition chains in SSA. * * <p> * In addition to the interface required by LocalUses, ShimpleLocalUses also provides a method for obtaining the list of uses * given only the Local. Furthermore, unlike SimpleLocalUses, a LocalDefs object is not required when constructing * ShimpleLocalUses. * * @author Navindra Umanee * @see ShimpleLocalDefs * @see soot.toolkits.scalar.SimpleLocalDefs * @see soot.toolkits.scalar.SimpleLocalUses **/ public class ShimpleLocalUses implements LocalUses { private static final Logger logger = LoggerFactory.getLogger(ShimpleLocalUses.class); protected Map<Local, List<UnitValueBoxPair>> localToUses = new HashMap<Local, List<UnitValueBoxPair>>(); /** * Build a LocalUses interface from a ShimpleBody. Proper SSA form is required, otherwise correct behaviour is not * guaranteed. **/ public ShimpleLocalUses(ShimpleBody sb) { // Instead of rebuilding the ShimpleBody without the // programmer's knowledge, throw a RuntimeException if (!sb.isSSA()) { throw new RuntimeException("ShimpleBody is not in proper SSA form as required by ShimpleLocalUses. " + "You may need to rebuild it or use SimpleLocalUses instead."); } // initialise the map Map<Local, List<UnitValueBoxPair>> localToUsesRef = this.localToUses; for (Local local : sb.getLocals()) { localToUsesRef.put(local, new ArrayList<UnitValueBoxPair>()); } // Iterate through the units and save each Local use in the appropriate list. Due // to SSA form, each Local has a unique def, and therefore one appropriate list. for (Unit unit : sb.getUnits()) { for (ValueBox box : unit.getUseBoxes()) { Value value = box.getValue(); if (value instanceof Local) { localToUsesRef.get((Local) value).add(new UnitValueBoxPair(unit, box)); } } } } /** * Returns all the uses of the given Local as a list of UnitValueBoxPairs, each containing a Unit that uses the local and * the corresponding ValueBox containing the Local. * * <p> * This method is currently not required by the LocalUses interface. **/ public List<UnitValueBoxPair> getUsesOf(Local local) { List<UnitValueBoxPair> uses = localToUses.get(local); return (uses != null) ? uses : Collections.<UnitValueBoxPair>emptyList(); } /** * If a Local is defined in the Unit, returns all the uses of that Local as a list of UnitValueBoxPairs, each containing a * Unit that uses the local and the corresponding ValueBox containing the Local. **/ @Override public List<UnitValueBoxPair> getUsesOf(Unit unit) { List<ValueBox> defBoxes = unit.getDefBoxes(); switch (defBoxes.size()) { case 0: return Collections.<UnitValueBoxPair>emptyList(); case 1: Value val = defBoxes.get(0).getValue(); if (val instanceof Local) { return getUsesOf((Local) val); } else { return Collections.<UnitValueBoxPair>emptyList(); } default: logger.warn("Unit has multiple definition boxes?"); List<UnitValueBoxPair> usesList = new ArrayList<UnitValueBoxPair>(); for (ValueBox next : defBoxes) { Value def = next.getValue(); if (def instanceof Local) { usesList.addAll(getUsesOf((Local) def)); } } return usesList; } } }
4,813
35.195489
125
java
soot
soot-master/src/main/java/soot/sootify/StmtTemplatePrinter.java
package soot.sootify; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import soot.PatchingChain; import soot.Unit; import soot.UnitBox; import soot.Value; import soot.jimple.AssignStmt; import soot.jimple.BreakpointStmt; import soot.jimple.EnterMonitorStmt; import soot.jimple.ExitMonitorStmt; import soot.jimple.GotoStmt; import soot.jimple.IdentityStmt; import soot.jimple.IfStmt; import soot.jimple.IntConstant; import soot.jimple.InvokeStmt; import soot.jimple.LookupSwitchStmt; import soot.jimple.NopStmt; import soot.jimple.RetStmt; import soot.jimple.ReturnStmt; import soot.jimple.ReturnVoidStmt; import soot.jimple.StmtSwitch; import soot.jimple.TableSwitchStmt; import soot.jimple.ThrowStmt; class StmtTemplatePrinter implements StmtSwitch { private final TemplatePrinter p; private final ValueTemplatePrinter vtp; // text for expression private List<Unit> jumpTargets = new ArrayList<Unit>(); public StmtTemplatePrinter(TemplatePrinter templatePrinter, PatchingChain<Unit> units) { this.p = templatePrinter; this.vtp = new ValueTemplatePrinter(p); for (Unit u : units) { for (UnitBox ub : u.getUnitBoxes()) { jumpTargets.add(ub.getUnit()); } } Collections.sort(jumpTargets, new Comparator<Unit>() { final List<Unit> unitsList = new ArrayList<Unit>(units); @Override public int compare(Unit o1, Unit o2) { return unitsList.indexOf(o1) - unitsList.indexOf(o2); } }); for (int i = 0; i < jumpTargets.size(); i++) { p.println("NopStmt jumpTarget" + i + "= Jimple.v().newNopStmt();"); } } private String nameOfJumpTarget(Unit u) { if (!isJumpTarget(u)) { throw new InternalError("not a jumpt target! " + u); } return "jumpTarget" + jumpTargets.indexOf(u); } private boolean isJumpTarget(Unit u) { return jumpTargets.contains(u); } private String printValueAssignment(Value value, String varName) { return vtp.printValueAssignment(value, varName); } private void printStmt(Unit u, String... ops) { String stmtClassName = u.getClass().getSimpleName(); if (stmtClassName.charAt(0) == 'J') { stmtClassName = stmtClassName.substring(1); } if (isJumpTarget(u)) { String nameOfJumpTarget = nameOfJumpTarget(u); p.println("units.add(" + nameOfJumpTarget + ");"); } p.print("units.add("); printFactoryMethodCall(stmtClassName, ops); p.printlnNoIndent(");"); } private void printFactoryMethodCall(String stmtClassName, String... ops) { p.printNoIndent("Jimple.v().new"); p.printNoIndent(stmtClassName); p.printNoIndent("("); int i = 1; for (String op : ops) { p.printNoIndent(op); if (i < ops.length) { p.printNoIndent(","); } i++; } p.printNoIndent(")"); } @Override public void caseThrowStmt(ThrowStmt stmt) { String varName = printValueAssignment(stmt.getOp(), "op"); printStmt(stmt, varName); } @Override public void caseTableSwitchStmt(TableSwitchStmt stmt) { p.openBlock(); String varName = printValueAssignment(stmt.getKey(), "key"); int lowIndex = stmt.getLowIndex(); p.println("int lowIndex=" + lowIndex + ";"); int highIndex = stmt.getHighIndex(); p.println("int highIndex=" + highIndex + ";"); p.println("List<Unit> targets = new LinkedList<Unit>();"); for (Unit s : stmt.getTargets()) { String nameOfJumpTarget = nameOfJumpTarget(s); p.println("targets.add(" + nameOfJumpTarget + ")"); } Unit defaultTarget = stmt.getDefaultTarget(); p.println("Unit defaultTarget = " + nameOfJumpTarget(defaultTarget) + ";"); printStmt(stmt, varName, "lowIndex", "highIndex", "targets", "defaultTarget"); p.closeBlock(); } @Override public void caseReturnVoidStmt(ReturnVoidStmt stmt) { printStmt(stmt); } @Override public void caseReturnStmt(ReturnStmt stmt) { String varName = printValueAssignment(stmt.getOp(), "retVal"); printStmt(stmt, varName); } @Override public void caseRetStmt(RetStmt stmt) { String varName = printValueAssignment(stmt.getStmtAddress(), "stmtAddress"); printStmt(stmt, varName); } @Override public void caseNopStmt(NopStmt stmt) { printStmt(stmt); } @Override public void caseLookupSwitchStmt(LookupSwitchStmt stmt) { p.openBlock(); String keyVarName = printValueAssignment(stmt.getKey(), "key"); p.println("List<IntConstant> lookupValues = new LinkedList<IntConstant>();"); int i = 0; for (IntConstant c : (List<IntConstant>) stmt.getLookupValues()) { vtp.suggestVariableName("lookupValue" + i); c.apply(vtp); i++; p.println("lookupValues.add(lookupValue" + i + ");"); } p.println("List<Unit> targets = new LinkedList<Unit>();"); for (Unit u : stmt.getTargets()) { String nameOfJumpTarget = nameOfJumpTarget(u); p.println("targets.add(" + nameOfJumpTarget + ")"); } Unit defaultTarget = stmt.getDefaultTarget(); p.println("Unit defaultTarget=" + defaultTarget.toString() + ";"); printStmt(stmt, keyVarName, "lookupValues", "targets", "defaultTarget"); p.closeBlock(); } @Override public void caseInvokeStmt(InvokeStmt stmt) { String varName = printValueAssignment(stmt.getInvokeExpr(), "ie"); printStmt(stmt, varName); } @Override public void caseIfStmt(IfStmt stmt) { String varName = printValueAssignment(stmt.getCondition(), "condition"); Unit target = stmt.getTarget(); vtp.suggestVariableName("target"); String targetName = vtp.getLastAssignedVarName(); p.println("Unit " + targetName + "=" + nameOfJumpTarget(target) + ";"); printStmt(stmt, varName, targetName); } @Override public void caseIdentityStmt(IdentityStmt stmt) { String varName = printValueAssignment(stmt.getLeftOp(), "lhs"); String varName2 = printValueAssignment(stmt.getRightOp(), "idRef"); printStmt(stmt, varName, varName2); } @Override public void caseGotoStmt(GotoStmt stmt) { Unit target = stmt.getTarget(); vtp.suggestVariableName("target"); String targetName = vtp.getLastAssignedVarName(); p.println("Unit " + targetName + "=" + nameOfJumpTarget(target) + ";"); printStmt(stmt, targetName); } @Override public void caseExitMonitorStmt(ExitMonitorStmt stmt) { String varName = printValueAssignment(stmt.getOp(), "monitor"); printStmt(stmt, varName); } @Override public void caseEnterMonitorStmt(EnterMonitorStmt stmt) { String varName = printValueAssignment(stmt.getOp(), "monitor"); printStmt(stmt, varName); } @Override public void caseBreakpointStmt(BreakpointStmt stmt) { printStmt(stmt); } @Override public void caseAssignStmt(AssignStmt stmt) { String varName = printValueAssignment(stmt.getLeftOp(), "lhs"); String varName2 = printValueAssignment(stmt.getRightOp(), "rhs"); printStmt(stmt, varName, varName2); } @Override public void defaultCase(Object obj) { throw new InternalError("should never be called"); } }
7,992
27.343972
90
java
soot
soot-master/src/main/java/soot/sootify/TemplatePrinter.java
package soot.sootify; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2010 Hela Oueslati, Eric Bodden * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.PrintWriter; import soot.Body; import soot.G; import soot.Local; import soot.Singletons; import soot.SootClass; import soot.SootMethod; import soot.Unit; public class TemplatePrinter { private PrintWriter out; private int indentationLevel = 0; public TemplatePrinter(Singletons.Global g) { } public static TemplatePrinter v() { return G.v().soot_sootify_TemplatePrinter(); } // see also class soot.Printer! public void printTo(SootClass c, PrintWriter out) { this.out = out; printTo(c); } private void printTo(SootClass c) { // imports println("import java.util.*;"); println("import soot.*;"); println("import soot.jimple.*;"); println("import soot.util.*;"); println(""); // open class print("public class "); print(c.getName().replace('.', '_') + "_Maker"); println(" {"); println("private static Local localByName(Body b, String name) {"); println(" for(Local l: b.getLocals()) {"); println(" if(l.getName().equals(name))"); println(" return l;"); println(" }"); println(" throw new IllegalArgumentException(\"No such local: \"+name);"); println("}"); // open main method indent(); println("public void create() {"); indent(); println("SootClass c = new SootClass(\"" + c.getName() + "\");"); println("c.setApplicationClass();"); // todo modifiers, extends etc. println("Scene.v().addClass(c);"); for (int i = 0; i < c.getMethodCount(); i++) { println("createMethod" + i + "(c);"); } // close main method closeMethod(); int i = 0; for (SootMethod m : c.getMethods()) { newMethod("createMethod" + i); // TODO modifiers, types println("SootMethod m = new SootMethod(\"" + m.getName() + "\",null,null);"); println("Body b = Jimple.v().newBody(m);"); println("m.setActiveBody(b);"); if (!m.hasActiveBody()) { continue; } Body b = m.getActiveBody(); println("Chain<Local> locals = b.getLocals();"); for (Local l : b.getLocals()) { // TODO properly treat primitive types println("locals.add(Jimple.v().newLocal(\"" + l.getName() + "\", RefType.v(\"" + l.getType() + "\")));"); } println("Chain<Unit> units = b.getUnits();"); StmtTemplatePrinter sw = new StmtTemplatePrinter(this, b.getUnits()); for (Unit u : b.getUnits()) { u.apply(sw); } // TODO print traps closeMethod(); i++; } // close class println("}"); } private void closeMethod() { unindent(); println("}"); unindent(); println(""); } private void newMethod(String name) { indent(); println("public void " + name + "(SootClass c) {"); indent(); } public void printlnNoIndent(String s) { printNoIndent(s); print("\n"); } public void println(String s) { print(s); print("\n"); } public void printNoIndent(String s) { out.print(s); } public void print(String s) { for (int i = 0; i < indentationLevel; i++) { out.print(" "); } out.print(s); } public void indent() { indentationLevel++; } public void unindent() { indentationLevel--; } public void openBlock() { println("{"); indent(); } public void closeBlock() { unindent(); println("}"); } }
4,235
21.897297
113
java
soot
soot-master/src/main/java/soot/sootify/TypeTemplatePrinter.java
package soot.sootify; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2010 Hela Oueslati, Eric Bodden * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.AnySubType; import soot.ArrayType; import soot.BooleanType; import soot.ByteType; import soot.CharType; import soot.DoubleType; import soot.ErroneousType; import soot.FloatType; import soot.IntType; import soot.LongType; import soot.NullType; import soot.RefType; import soot.ShortType; import soot.StmtAddressType; import soot.Type; import soot.TypeSwitch; import soot.UnknownType; import soot.VoidType; public class TypeTemplatePrinter extends TypeSwitch { private String varName; private final TemplatePrinter p; public void printAssign(String v, Type t) { String oldName = varName; varName = v; t.apply(this); varName = oldName; } public TypeTemplatePrinter(TemplatePrinter p) { this.p = p; } public void setVariableName(String name) { this.varName = name; } private void emit(String rhs) { p.println("Type " + varName + " = " + rhs + ';'); } private void emitSpecial(String type, String rhs) { p.println(type + ' ' + varName + " = " + rhs + ';'); } @Override public void caseAnySubType(AnySubType t) { throw new IllegalArgumentException("cannot print this type"); } @Override public void caseArrayType(ArrayType t) { printAssign("baseType", t.getElementType()); p.println("int numDimensions=" + t.numDimensions + ';'); emit("ArrayType.v(baseType, numDimensions)"); } @Override public void caseBooleanType(BooleanType t) { emit("BooleanType.v()"); } @Override public void caseByteType(ByteType t) { emit("ByteType.v()"); } @Override public void caseCharType(CharType t) { emit("CharType.v()"); } @Override public void defaultCase(Type t) { throw new IllegalArgumentException("cannot print this type"); } @Override public void caseDoubleType(DoubleType t) { emit("DoubleType.v()"); } @Override public void caseErroneousType(ErroneousType t) { throw new IllegalArgumentException("cannot print this type"); } @Override public void caseFloatType(FloatType t) { emit("FloatType.v()"); } @Override public void caseIntType(IntType t) { emit("IntType.v()"); } @Override public void caseLongType(LongType t) { emit("LongType.v()"); } @Override public void caseNullType(NullType t) { emit("NullType.v()"); } @Override public void caseRefType(RefType t) { emitSpecial("RefType", "RefType.v(\"" + t.getClassName() + "\")"); } @Override public void caseShortType(ShortType t) { emit("ShortType.v()"); } @Override public void caseStmtAddressType(StmtAddressType t) { throw new IllegalArgumentException("cannot print this type"); } @Override public void caseUnknownType(UnknownType t) { throw new IllegalArgumentException("cannot print this type"); } @Override public void caseVoidType(VoidType t) { emit("VoidType.v()"); } }
3,721
22.118012
71
java
soot
soot-master/src/main/java/soot/sootify/ValueTemplatePrinter.java
package soot.sootify; /*- * #%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.HashSet; import java.util.Set; import soot.Local; import soot.SootField; import soot.SootMethod; import soot.SootMethodRef; import soot.Type; import soot.Value; import soot.jimple.AddExpr; import soot.jimple.AndExpr; import soot.jimple.ArrayRef; import soot.jimple.BinopExpr; import soot.jimple.CastExpr; import soot.jimple.CaughtExceptionRef; import soot.jimple.ClassConstant; import soot.jimple.CmpExpr; import soot.jimple.CmpgExpr; import soot.jimple.CmplExpr; import soot.jimple.DivExpr; import soot.jimple.DoubleConstant; import soot.jimple.DynamicInvokeExpr; import soot.jimple.EqExpr; import soot.jimple.FieldRef; import soot.jimple.FloatConstant; import soot.jimple.GeExpr; import soot.jimple.GtExpr; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InstanceOfExpr; import soot.jimple.IntConstant; import soot.jimple.InterfaceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.JimpleValueSwitch; import soot.jimple.LeExpr; import soot.jimple.LengthExpr; import soot.jimple.LongConstant; import soot.jimple.LtExpr; import soot.jimple.MethodHandle; import soot.jimple.MethodType; import soot.jimple.MulExpr; import soot.jimple.NeExpr; import soot.jimple.NegExpr; import soot.jimple.NewArrayExpr; import soot.jimple.NewExpr; import soot.jimple.NewMultiArrayExpr; import soot.jimple.NullConstant; import soot.jimple.OrExpr; import soot.jimple.ParameterRef; import soot.jimple.RemExpr; import soot.jimple.ShlExpr; import soot.jimple.ShrExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticFieldRef; import soot.jimple.StaticInvokeExpr; import soot.jimple.StringConstant; import soot.jimple.SubExpr; import soot.jimple.ThisRef; import soot.jimple.UshrExpr; import soot.jimple.VirtualInvokeExpr; import soot.jimple.XorExpr; public class ValueTemplatePrinter implements JimpleValueSwitch { private final TemplatePrinter p; private final TypeTemplatePrinter ttp; private String varName; private final Set<String> varnamesAlreadyUsed = new HashSet<String>(); public ValueTemplatePrinter(TemplatePrinter p) { this.p = p; this.ttp = new TypeTemplatePrinter(p); this.varnamesAlreadyUsed.add("b");// body this.varnamesAlreadyUsed.add("m");// method this.varnamesAlreadyUsed.add("units");// unit chain } public String printValueAssignment(Value value, String varName) { suggestVariableName(varName); value.apply(this); return getLastAssignedVarName(); } private void printConstant(Value v, String... ops) { String stmtClassName = v.getClass().getSimpleName(); p.print("Value " + varName + " = "); p.printNoIndent(stmtClassName); p.printNoIndent(".v("); int i = 1; for (String op : ops) { p.printNoIndent(op); if (i < ops.length) { p.printNoIndent(","); } i++; } p.printNoIndent(")"); p.printlnNoIndent(";"); } private void printExpr(Value v, String... ops) { String stmtClassName = v.getClass().getSimpleName(); if (stmtClassName.charAt(0) == 'J') { stmtClassName = stmtClassName.substring(1); } p.print("Value " + varName + " = "); printFactoryMethodCall(stmtClassName, ops); p.printlnNoIndent(";"); } private void printFactoryMethodCall(String stmtClassName, String... ops) { p.printNoIndent("Jimple.v().new"); p.printNoIndent(stmtClassName); p.printNoIndent("("); int i = 1; for (String op : ops) { p.printNoIndent(op); if (i < ops.length) { p.printNoIndent(","); } i++; } p.printNoIndent(")"); } public void suggestVariableName(String name) { String actualName = name; int i = 0; do { actualName = name + i; i++; } while (varnamesAlreadyUsed.contains(actualName)); this.varName = actualName; this.varnamesAlreadyUsed.add(actualName); } public String getLastAssignedVarName() { return varName; } @Override public void caseDoubleConstant(DoubleConstant v) { printConstant(v, Double.toString(v.value)); } @Override public void caseFloatConstant(FloatConstant v) { printConstant(v, Float.toString(v.value)); } @Override public void caseIntConstant(IntConstant v) { printConstant(v, Integer.toString(v.value)); } @Override public void caseLongConstant(LongConstant v) { printConstant(v, Long.toString(v.value)); } @Override public void caseNullConstant(NullConstant v) { printConstant(v); } @Override public void caseStringConstant(StringConstant v) { printConstant(v, "\"" + v.value + "\""); } @Override public void caseClassConstant(ClassConstant v) { printConstant(v, "\"" + v.value + "\""); } @Override public void caseAddExpr(AddExpr v) { printBinaryExpr(v); } @Override public void caseMethodHandle(MethodHandle handle) { throw new UnsupportedOperationException("we have not yet determined how to print Java 7 method handles"); } @Override public void caseMethodType(MethodType type) { throw new UnsupportedOperationException("we have not yet determined how to print Java 8 method handles"); } private void printBinaryExpr(BinopExpr v) { String className = v.getClass().getSimpleName(); if (className.charAt(0) == 'J') { className = className.substring(1); } String oldName = varName; String v1 = printValueAssignment(v.getOp1(), "left"); String v2 = printValueAssignment(v.getOp2(), "right"); p.println("Value " + oldName + " = Jimple.v().new" + className + "(" + v1 + "," + v2 + ");"); varName = oldName; } @Override public void caseAndExpr(AndExpr v) { printBinaryExpr(v); } @Override public void caseCmpExpr(CmpExpr v) { printBinaryExpr(v); } @Override public void caseCmpgExpr(CmpgExpr v) { printBinaryExpr(v); } @Override public void caseCmplExpr(CmplExpr v) { printBinaryExpr(v); } @Override public void caseDivExpr(DivExpr v) { printBinaryExpr(v); } @Override public void caseEqExpr(EqExpr v) { printBinaryExpr(v); } @Override public void caseNeExpr(NeExpr v) { printBinaryExpr(v); } @Override public void caseGeExpr(GeExpr v) { printBinaryExpr(v); } @Override public void caseGtExpr(GtExpr v) { printBinaryExpr(v); } @Override public void caseLeExpr(LeExpr v) { printBinaryExpr(v); } @Override public void caseLtExpr(LtExpr v) { printBinaryExpr(v); } @Override public void caseMulExpr(MulExpr v) { printBinaryExpr(v); } @Override public void caseOrExpr(OrExpr v) { printBinaryExpr(v); } @Override public void caseRemExpr(RemExpr v) { printBinaryExpr(v); } @Override public void caseShlExpr(ShlExpr v) { printBinaryExpr(v); } @Override public void caseShrExpr(ShrExpr v) { printBinaryExpr(v); } @Override public void caseUshrExpr(UshrExpr v) { printBinaryExpr(v); } @Override public void caseSubExpr(SubExpr v) { printBinaryExpr(v); } @Override public void caseXorExpr(XorExpr v) { printBinaryExpr(v); } @Override public void caseInterfaceInvokeExpr(InterfaceInvokeExpr v) { printInvokeExpr(v); } private void printInvokeExpr(InvokeExpr v) { p.openBlock(); String oldName = varName; SootMethodRef method = v.getMethodRef(); SootMethod m = method.resolve(); if (!m.isStatic()) { Local base = (Local) ((InstanceInvokeExpr) v).getBase(); p.println("Local base = localByName(b,\"" + base.getName() + "\");"); } p.println("List<Type> parameterTypes = new LinkedList<Type>();"); int i = 0; for (Type t : m.getParameterTypes()) { ttp.setVariableName("type" + i); t.apply(ttp); p.println("parameterTypes.add(type" + i + ");"); i++; } ttp.setVariableName("returnType"); m.getReturnType().apply(ttp); p.print("SootMethodRef methodRef = "); p.printNoIndent("Scene.v().makeMethodRef("); String className = m.getDeclaringClass().getName(); p.printNoIndent("Scene.v().getSootClass(\"" + className + "\"),"); p.printNoIndent("\"" + m.getName() + "\","); p.printNoIndent("parameterTypes,"); p.printNoIndent("returnType,"); p.printlnNoIndent(m.isStatic() + ");"); printExpr(v, "base", "methodRef"); varName = oldName; p.closeBlock(); } @Override public void caseSpecialInvokeExpr(SpecialInvokeExpr v) { printInvokeExpr(v); } @Override public void caseStaticInvokeExpr(StaticInvokeExpr v) { printInvokeExpr(v); } @Override public void caseVirtualInvokeExpr(VirtualInvokeExpr v) { printInvokeExpr(v); } @Override public void caseDynamicInvokeExpr(DynamicInvokeExpr v) { printInvokeExpr(v); } // private void printBinaryExpr(BinopExpr v, Value lhs, String l, Value rhs, String r) { // String className = v.getClass().getSimpleName(); // if(className.charAt(0)=='J') className = className.substring(1); // // String oldName = varName; // // String v1 = printValueAssignment(lhs, l); // // String v2 = printValueAssignment(rhs, r); // // p.println("Value "+oldName+" = Jimple.v().new"+className+"("+v1+","+v2+");"); // // varName = oldName; // } @Override public void caseCastExpr(CastExpr v) { String oldName = varName; suggestVariableName("type"); String lhsName = varName; ttp.setVariableName(varName); v.getType().apply(ttp); String rhsName = printValueAssignment(v.getOp(), "op"); p.println("Value " + oldName + " = Jimple.v().newCastExpr(" + lhsName + "," + rhsName + ");"); varName = oldName; } @Override public void caseInstanceOfExpr(InstanceOfExpr v) { String oldName = varName; suggestVariableName("type"); String lhsName = varName; ttp.setVariableName(varName); v.getType().apply(ttp); String rhsName = printValueAssignment(v.getOp(), "op"); p.println("Value " + oldName + " = Jimple.v().newInstanceOfExpr(" + lhsName + "," + rhsName + ");"); varName = oldName; } @Override public void caseNewArrayExpr(NewArrayExpr v) { String oldName = varName; Value size = v.getSize(); suggestVariableName("size"); String sizeName = varName; size.apply(this); suggestVariableName("type"); String lhsName = varName; ttp.setVariableName(varName); v.getType().apply(ttp); p.println("Value " + oldName + " = Jimple.v().newNewArrayExpr(" + lhsName + ", " + sizeName + ");"); varName = oldName; } @Override public void caseNewMultiArrayExpr(NewMultiArrayExpr v) { p.openBlock(); String oldName = varName; ttp.setVariableName("arrayType"); v.getType().apply(ttp); p.println("List<IntConstant> sizes = new LinkedList<IntConstant>();"); int i = 0; for (Value s : v.getSizes()) { this.suggestVariableName("size" + i); s.apply(this); i++; p.println("sizes.add(sizes" + i + ");"); } p.println("Value " + oldName + " = Jimple.v().newNewMultiArrayExpr(arrayType, sizes);"); varName = oldName; p.closeBlock(); } @Override public void caseNewExpr(NewExpr v) { String oldName = varName; suggestVariableName("type"); String typeName = varName; ttp.setVariableName(varName); v.getType().apply(ttp); p.println("Value " + oldName + " = Jimple.v().newNewExpr(" + typeName + ");"); varName = oldName; } @Override public void caseLengthExpr(LengthExpr v) { String oldName = varName; Value op = v.getOp(); suggestVariableName("op"); String opName = varName; op.apply(this); p.println("Value " + oldName + " = Jimple.v().newLengthExpr(" + opName + ");"); varName = oldName; } @Override public void caseNegExpr(NegExpr v) { String oldName = varName; Value op = v.getOp(); suggestVariableName("op"); String opName = varName; op.apply(this); p.println("Value " + oldName + " = Jimple.v().newNegExpr(" + opName + ");"); varName = oldName; } @Override public void caseArrayRef(ArrayRef v) { String oldName = varName; Value base = v.getBase(); suggestVariableName("base"); String baseName = varName; base.apply(this); Value index = v.getIndex(); suggestVariableName("index"); String indexName = varName; index.apply(this); p.println("Value " + oldName + " = Jimple.v().newArrayRef(" + baseName + ", " + indexName + ");"); varName = oldName; } @Override public void caseStaticFieldRef(StaticFieldRef v) { printFieldRef(v); } private void printFieldRef(FieldRef v) { String refTypeName = v.getClass().getSimpleName(); p.openBlock(); String oldName = varName; SootField f = v.getField(); ttp.setVariableName("type"); f.getType().apply(ttp); p.print("SootFieldRef fieldRef = "); p.printNoIndent("Scene.v().makeFieldRef("); String className = f.getDeclaringClass().getName(); p.printNoIndent("Scene.v().getSootClass(\"" + className + "\"),"); p.printNoIndent("\"" + f.getName() + "\","); p.printNoIndent("type,"); p.printNoIndent(f.isStatic() + ");"); p.println("Value " + oldName + " = Jimple.v().new" + refTypeName + "(fieldRef);"); varName = oldName; p.closeBlock(); } @Override public void caseInstanceFieldRef(InstanceFieldRef v) { printFieldRef(v); } @Override public void caseParameterRef(ParameterRef v) { String oldName = varName; Type paramType = v.getType(); suggestVariableName("paramType"); String paramTypeName = this.varName; ttp.setVariableName(paramTypeName); paramType.apply(ttp); suggestVariableName("number"); p.println("int " + varName + "=" + v.getIndex() + ";"); p.println("Value " + oldName + " = Jimple.v().newParameterRef(" + paramTypeName + ", " + varName + ");"); varName = oldName; } @Override public void caseCaughtExceptionRef(CaughtExceptionRef v) { p.println("Value " + varName + " = Jimple.v().newCaughtExceptionRef();"); } @Override public void caseThisRef(ThisRef v) { String oldName = varName; suggestVariableName("type"); String typeName = this.varName; ttp.setVariableName(typeName); v.getType().apply(ttp); p.println("Value " + oldName + " = Jimple.v().newThisRef(" + typeName + ");"); varName = oldName; } @Override public void caseLocal(Local l) { String oldName = varName; p.println("Local " + varName + " = localByName(b,\"" + l.getName() + "\");"); varName = oldName; } @Override public void defaultCase(Object object) { throw new InternalError(); } }
15,553
24.046699
109
java
soot
soot-master/src/main/java/soot/tagkit/AbstractAnnotationElemTypeSwitch.java
package soot.tagkit; /*- * #%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% */ public abstract class AbstractAnnotationElemTypeSwitch<T> implements IAnnotationElemTypeSwitch { T result; @Override public void caseAnnotationAnnotationElem(AnnotationAnnotationElem v) { defaultCase(v); } @Override public void caseAnnotationArrayElem(AnnotationArrayElem v) { defaultCase(v); } @Override public void caseAnnotationBooleanElem(AnnotationBooleanElem v) { defaultCase(v); } @Override public void caseAnnotationClassElem(AnnotationClassElem v) { defaultCase(v); } @Override public void caseAnnotationDoubleElem(AnnotationDoubleElem v) { defaultCase(v); } @Override public void caseAnnotationEnumElem(AnnotationEnumElem v) { defaultCase(v); } @Override public void caseAnnotationFloatElem(AnnotationFloatElem v) { defaultCase(v); } @Override public void caseAnnotationIntElem(AnnotationIntElem v) { defaultCase(v); } @Override public void caseAnnotationLongElem(AnnotationLongElem v) { defaultCase(v); } @Override public void caseAnnotationStringElem(AnnotationStringElem v) { defaultCase(v); } @Override public void defaultCase(Object obj) { } public void setResult(T result) { this.result = result; } public T getResult() { return result; } }
2,135
22.472527
96
java
soot
soot-master/src/main/java/soot/tagkit/AbstractHost.java
package soot.tagkit; /*- * #%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.Collections; import java.util.List; // extended by SootClass, SootField, SootMethod, Scene /** * This class is the reference implementation for the Host interface, which allows arbitrary taggable data to be stored with * Soot objects. */ public class AbstractHost implements Host { protected int line, col; // avoid creating an empty list for each element, when it is not used // use lazy instantiation (in addTag) instead protected List<Tag> mTagList = null; /** * Get the {@link List} of {@link Tag Tags} on {@code this} {@link Host}. This list should not be modified! * * @return */ @Override public List<Tag> getTags() { return (mTagList == null) ? Collections.<Tag>emptyList() : mTagList; } /** * Remove the {@link Tag} named {@code aName} from {@code this} {@link Host}. * * @param aName */ @Override public void removeTag(String aName) { int tagIndex = searchForTag(aName); if (tagIndex != -1) { mTagList.remove(tagIndex); } } /** * Search for {@link Tag} named {@code aName}. */ private int searchForTag(String aName) { if (mTagList != null) { int i = 0; for (Tag tag : mTagList) { if (tag != null && tag.getName().equals(aName)) { return i; } i++; } } return -1; } /** * Return the {@link Tag} named {@code aName} from {@code this} {@link Host} or {@code null} if there is no such * {@link Tag}. * * @param aName * * @return */ @Override public Tag getTag(String aName) { int tagIndex = searchForTag(aName); return (tagIndex == -1) ? null : mTagList.get(tagIndex); } /** * Check if {@code this} {@link Host} has a {@link Tag} named {@code aName}. * * @param aName * * @return */ @Override public boolean hasTag(String aName) { return (searchForTag(aName) != -1); } /** * Add the given {@link Tag} to {@code this} {@link Host}. * * @param t */ @Override public void addTag(Tag t) { if (mTagList == null) { mTagList = new ArrayList<Tag>(1); } mTagList.add(t); } /** * Removes all the tags from {@code this} {@link Host}. */ @Override public void removeAllTags() { mTagList = null; } /** * Adds all the tags from the given {@link Host} to {@code this} {@link Host}. * * @param h */ @Override public void addAllTagsOf(Host h) { List<Tag> tags = h.getTags(); if (!tags.isEmpty()) { if (mTagList == null) { mTagList = new ArrayList<Tag>(tags.size()); } mTagList.addAll(tags); } } @Override public int getJavaSourceStartLineNumber() { if (line <= 0) { // get line from source SourceLnPosTag tag = (SourceLnPosTag) getTag(SourceLnPosTag.NAME); if (tag != null) { line = tag.startLn(); } else { // get line from bytecode LineNumberTag tag2 = (LineNumberTag) getTag(LineNumberTag.NAME); line = (tag2 == null) ? -1 : tag2.getLineNumber(); } } return line; } @Override public int getJavaSourceStartColumnNumber() { if (col <= 0) { // get line from source SourceLnPosTag tag = (SourceLnPosTag) getTag(SourceLnPosTag.NAME); col = (tag == null) ? -1 : tag.startPos(); } return col; } }
4,222
23.695906
124
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationAnnotationElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the Annotation annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationAnnotationElem extends AnnotationElem { private final AnnotationTag value; public AnnotationAnnotationElem(AnnotationTag t, char kind, String name) { super(kind, name); this.value = t; } @Override public String toString() { return super.toString() + "value: " + value.toString(); } public AnnotationTag getValue() { return value; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationAnnotationElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationAnnotationElem other = (AnnotationAnnotationElem) obj; if (this.value == null) { if (other.value != null) { return false; } } else if (!this.value.equals(other.value)) { return false; } return true; } }
2,156
24.987952
103
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationArrayElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import soot.util.Switch; /** * Represents the Array annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationArrayElem extends AnnotationElem { private final ArrayList<AnnotationElem> values; public AnnotationArrayElem(ArrayList<AnnotationElem> t, char kind, String name) { super(kind, name); this.values = t; } @Override public String toString() { return super.toString() + " values: " + values.toString(); } public ArrayList<AnnotationElem> getValues() { return values; } public int getNumValues() { if (values == null) { return 0; } else { return values.size(); } } public AnnotationElem getValueAt(int i) { return values.get(i); } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationArrayElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((values == null) ? 0 : values.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationArrayElem other = (AnnotationArrayElem) obj; if (this.values == null) { if (other.values != null) { return false; } } else if (!this.values.equals(other.values)) { return false; } return true; } }
2,403
23.783505
98
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationBooleanElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2012 Eric Bodden * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the boolean annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationBooleanElem extends AnnotationElem { private final boolean value; public AnnotationBooleanElem(boolean v, char kind, String name) { super(kind, name); this.value = v; } @Override public String toString() { return super.toString() + " value: " + value; } public boolean getValue() { return value; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationBooleanElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (value ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationBooleanElem other = (AnnotationBooleanElem) obj; return this.value == other.value; } }
1,938
24.853333
100
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationClassElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the Class annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationClassElem extends AnnotationElem { private final String desc; public AnnotationClassElem(String s, char kind, String name) { super(kind, name); this.desc = s; } @Override public String toString() { return super.toString() + " decription: " + desc; } public String getDesc() { return desc; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationClassElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((desc == null) ? 0 : desc.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationClassElem other = (AnnotationClassElem) obj; if (this.desc == null) { if (other.desc != null) { return false; } } else if (!this.desc.equals(other.desc)) { return false; } return true; } }
2,089
24.180723
98
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationConstants.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 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% */ /** * Represents the annotation constants for Java 1.5. */ public class AnnotationConstants { public static final int RUNTIME_VISIBLE = 0; public static final int RUNTIME_INVISIBLE = 1; public static final int SOURCE_VISIBLE = 2; }
1,064
29.428571
71
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationDefaultTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 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% */ /** * Represents the annotation default attribute attached method - could have at most one annotation default each for Java 1.5. */ public class AnnotationDefaultTag implements Tag { public static final String NAME = "AnnotationDefaultTag"; private final AnnotationElem defaultVal; public AnnotationDefaultTag(AnnotationElem def) { this.defaultVal = def; } @Override public String toString() { return "Annotation Default: " + defaultVal; } @Override public String getName() { return NAME; } public String getInfo() { return "AnnotationDefault"; } public AnnotationElem getDefaultVal() { return defaultVal; } @Override public byte[] getValue() { throw new RuntimeException("AnnotationDefaultTag has no value for bytecode"); } }
1,617
25.52459
125
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationDoubleElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the double annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationDoubleElem extends AnnotationElem { private final double value; public AnnotationDoubleElem(double v, char kind, String name) { super(kind, name); this.value = v; } @Override public String toString() { return super.toString() + " value: " + value; } public double getValue() { return value; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationDoubleElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); long temp = Double.doubleToLongBits(value); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationDoubleElem other = (AnnotationDoubleElem) obj; return Double.doubleToLongBits(this.value) == Double.doubleToLongBits(other.value); } }
2,039
25.493506
99
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switchable; /** * Represents the base class of annotation elements each annotation can have several elements for Java 1.5. */ public abstract class AnnotationElem implements Switchable { private final char kind; private String name; public AnnotationElem(char k, String name) { this.kind = k; this.name = name; } @Override public String toString() { return "Annotation Element: kind: " + kind + " name: " + name; } public char getKind() { return kind; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + kind; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } AnnotationElem other = (AnnotationElem) obj; if (this.kind != other.kind) { return false; } if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } return true; } }
2,145
23.386364
107
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationEnumElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the Enum annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationEnumElem extends AnnotationElem { private String typeName; private String constantName; public AnnotationEnumElem(String t, String c, char kind, String name) { super(kind, name); this.typeName = t; this.constantName = c; } @Override public String toString() { return super.toString() + " type name: " + typeName + " constant name: " + constantName; } public String getTypeName() { return typeName; } public void setTypeName(String newValue) { typeName = newValue; } public String getConstantName() { return constantName; } public void setConstantName(String newValue) { constantName = newValue; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationEnumElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((constantName == null) ? 0 : constantName.hashCode()); result = prime * result + ((typeName == null) ? 0 : typeName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationEnumElem other = (AnnotationEnumElem) obj; if (this.constantName == null) { if (other.constantName != null) { return false; } } else if (!this.constantName.equals(other.constantName)) { return false; } if (this.typeName == null) { if (other.typeName != null) { return false; } } else if (!this.typeName.equals(other.typeName)) { return false; } return true; } }
2,731
25.019048
97
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationFloatElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the float annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationFloatElem extends AnnotationElem { private final float value; public AnnotationFloatElem(float v, char kind, String name) { super(kind, name); this.value = v; } @Override public String toString() { return super.toString() + " value: " + value; } public float getValue() { return value; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationFloatElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Float.floatToIntBits(value); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationFloatElem other = (AnnotationFloatElem) obj; return Float.floatToIntBits(this.value) == Float.floatToIntBits(other.value); } }
1,975
25
98
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationIntElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the int annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationIntElem extends AnnotationElem { private final int value; public AnnotationIntElem(int v, char kind, String name) { super(kind, name); this.value = v; } @Override public String toString() { return super.toString() + " value: " + value; } public int getValue() { return value; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationIntElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + value; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationIntElem other = (AnnotationIntElem) obj; return this.value == other.value; } }
1,891
23.894737
96
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationLongElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the long annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationLongElem extends AnnotationElem { private final long value; public AnnotationLongElem(long v, char kind, String name) { super(kind, name); this.value = v; } @Override public String toString() { return super.toString() + " value: " + value; } public long getValue() { return value; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationLongElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (int) (value ^ (value >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationLongElem other = (AnnotationLongElem) obj; return this.value == other.value; } }
1,925
24.342105
97
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationStringElem.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; /** * Represents the String annotation element each annotation can have several elements for Java 1.5. */ public class AnnotationStringElem extends AnnotationElem { private final String value; public AnnotationStringElem(String s, char kind, String name) { super(kind, name); this.value = s; } @Override public String toString() { return super.toString() + " value: " + value; } public String getValue() { return value; } @Override public void apply(Switch sw) { ((IAnnotationElemTypeSwitch) sw).caseAnnotationStringElem(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } AnnotationStringElem other = (AnnotationStringElem) obj; if (this.value == null) { if (other.value != null) { return false; } } else if (!this.value.equals(other.value)) { return false; } return true; } }
2,101
24.325301
99
java
soot
soot-master/src/main/java/soot/tagkit/AnnotationTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * Copyright (C) 2013 Tata Consultancy Services & Ecole Polytechnique de Montreal * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.List; /** * Represents the annotation attribute attached to a class, method, field, method param - they could have many annotations * each for Java 1.5. */ public class AnnotationTag implements Tag { public static final String NAME = "AnnotationTag"; // type - the question here is the class of the type is potentially // not loaded -- Does it need to be ??? - If it does then this may // be something difficult (if just passing the attributes through // then it maybe doesn't need to - but if they are runtime visible // attributes then won't the annotation class need to be created // in the set of output classes for use by tools when using // reflection ??? // number of elem value pairs // a bunch of element value pairs // a type B C D F I J S Z s e c @ [ // for B C D F I J S Z s elem is a constant value (entry to cp) // in Soot rep as // for e elem is a type and the simple name of the enum class // rep in Soot as a type and SootClass or as two strings // for c elem is a descriptor of the class represented // rep in Soot as a SootClass ?? or a string ?? // for @ (nested annotation) // for [ elem is num values and array of values // should probably make a bunch of subclasses for all the // different kinds - with second level for the constant kinds /** * The type */ private final String type; /** * The annotations */ private List<AnnotationElem> elems; public AnnotationTag(String type) { this.type = type; this.elems = null; } public AnnotationTag(String type, Collection<AnnotationElem> elements) { this.type = type; if (elements == null || elements.isEmpty()) { this.elems = null; } else if (elements instanceof List<?>) { this.elems = (List<AnnotationElem>) elements; } else { this.elems = new ArrayList<AnnotationElem>(elements); } } @Deprecated public AnnotationTag(String type, int numElem) { this.type = type; this.elems = new ArrayList<AnnotationElem>(numElem); } // should also print here number of annotations and perhaps the annotations themselves @Override public String toString() { if (elems != null) { StringBuilder sb = new StringBuilder("Annotation: type: "); sb.append(type).append(" num elems: ").append(elems.size()).append(" elems: "); for (AnnotationElem next : elems) { sb.append('\n').append(next); } sb.append('\n'); return sb.toString(); } else { return "Annotation type: " + type + " without elements"; } } @Override public String getName() { return NAME; } public String getInfo() { return "Annotation"; } public String getType() { return type; } @Override public byte[] getValue() { throw new RuntimeException("AnnotationTag has no value for bytecode"); } /** * Adds one element to the list * * @param elem * the element */ public void addElem(AnnotationElem elem) { if (elems == null) { elems = new ArrayList<AnnotationElem>(); } elems.add(elem); } /** * Overwrites the elements stored previously * * @param list * the new list of elements */ public void setElems(List<AnnotationElem> list) { this.elems = list; } /** * @return an immutable collection of the elements */ public Collection<AnnotationElem> getElems() { return elems == null ? Collections.<AnnotationElem>emptyList() : Collections.unmodifiableCollection(elems); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((elems == null) ? 0 : elems.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } AnnotationTag other = (AnnotationTag) obj; if (this.elems == null) { if (other.elems != null) { return false; } } else if (!this.elems.equals(other.elems)) { return false; } if (this.type == null) { if (other.type != null) { return false; } } else if (!this.type.equals(other.type)) { return false; } return true; } }
5,377
26.865285
122
java
soot
soot-master/src/main/java/soot/tagkit/ArtificialEntityTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2020 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Used to tag entities (class, method, variable, etc.) as artificially generated by Soot itself, i.e. entities that do not * exist in the original bytecode. This can, for instance, be used to exclude such entities from being written out or * processed by clients. * * @author Manuel Benz at 02.03.20 */ public class ArtificialEntityTag implements Tag { public static final String NAME = "ArtificialEntityTag"; @Override public String getName() { return NAME; } @Override public byte[] getValue() throws AttributeValueException { throw new RuntimeException("ArtificialEntityTag has no value for bytecode"); } }
1,461
30.782609
123
java
soot
soot-master/src/main/java/soot/tagkit/Attribute.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville and Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Tags that are attached to the class file, field, method, or method body should implement this interface. */ public interface Attribute extends Tag { /** * Sets the value of the attribute from a byte[]. */ public void setValue(byte[] v); }
1,097
30.371429
107
java
soot
soot-master/src/main/java/soot/tagkit/AttributeValueException.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville and Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class AttributeValueException extends RuntimeException { /** * */ private static final long serialVersionUID = 5318900011605820606L; }
993
30.0625
71
java
soot
soot-master/src/main/java/soot/tagkit/Base64.java
//////////////////////license & copyright header///////////////////////// // // // Base64 - encode/decode data using the Base64 encoding scheme // // // // Copyright (c) 1998 by Kevin Kelley // // // // This library is free software; you can redistribute it and/or // // modify it under the terms of the GNU Lesser General Public // // License as published by the Free Software Foundation; either // // version 2.1 of the License, or (at your option) any later version. // // // // This library is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU Lesser General Public License for more details. // // // // You should have received a copy of the GNU Lesser General Public // // License along with this library; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // // 02111-1307, USA, or contact the author: // // // // Kevin Kelley <kelley@ruralnet.net> - 30718 Rd. 28, La Junta, CO, // // 81050 USA. // // // ////////////////////end license & copyright header/////////////////////// package soot.tagkit; import java.util.Arrays; /*- * #%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% */ /** * Provides encoding of raw bytes to base64-encoded characters, and decoding of base64 characters to raw bytes. * * @author Kevin Kelley (kelley@ruralnet.net) * @version 1.3 * @date 06 August 1998 * @modified 14 February 2000 * @modified 22 September 2000 */ public class Base64 { // // code characters for values 0..63 // private static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray(); // // lookup table for converting base64 characters to value in range 0..63 // private static final byte[] codes = new byte[256]; static { for (int i = 0; i < 256; i++) { codes[i] = -1; } for (int i = 'A'; i <= 'Z'; i++) { codes[i] = (byte) (i - 'A'); } for (int i = 'a'; i <= 'z'; i++) { codes[i] = (byte) (26 + i - 'a'); } for (int i = '0'; i <= '9'; i++) { codes[i] = (byte) (52 + i - '0'); } codes['+'] = 62; codes['/'] = 63; } /** * returns an array of base64-encoded characters to represent the passed data array. * * @param data * the array of bytes to encode * @return base64-coded character array. */ public static char[] encode(byte[] data) { char[] out = new char[((data.length + 2) / 3) * 4]; // // 3 bytes encode to 4 chars. Output is always an even // multiple of 4 characters. // for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { boolean quad = false; boolean trip = false; int val = (0xFF & data[i]); val <<= 8; if ((i + 1) < data.length) { val |= (0xFF & data[i + 1]); trip = true; } val <<= 8; if ((i + 2) < data.length) { val |= (0xFF & data[i + 2]); quad = true; } out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; val >>= 6; out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; val >>= 6; out[index + 1] = alphabet[val & 0x3F]; val >>= 6; out[index + 0] = alphabet[val & 0x3F]; } return out; } /** * Decodes a BASE-64 encoded stream to recover the original data. White space before and after will be trimmed away, but no * other manipulation of the input will be performed. * * As of version 1.2 this method will properly handle input containing junk characters (newlines and the like) rather than * throwing an error. It does this by pre-parsing the input and generating from that a count of VALID input characters. **/ public static byte[] decode(char[] data) { // as our input could contain non-BASE64 data (newlines, // whitespace of any sort, whatever) we must first adjust // our count of USABLE data so that... // (a) we don't misallocate the output array, and // (b) think that we miscalculated our data length // just because of extraneous throw-away junk int tempLen = data.length; for (char element : data) { if ((element > 255) || codes[element] < 0) { --tempLen; // ignore non-valid chars and padding } } // calculate required length: // -- 3 bytes for every 4 valid base64 chars // -- plus 2 bytes if there are 3 extra base64 chars, // or plus 1 byte if there are 2 extra. int len = (tempLen / 4) * 3; if ((tempLen % 4) == 3) { len += 2; } if ((tempLen % 4) == 2) { len += 1; } byte[] out = new byte[len]; int shift = 0; // # of excess bits stored in accum int accum = 0; // excess bits int index = 0; for (char element : data) { int value = (element > 255) ? -1 : codes[element]; if (value >= 0) // skip over non-code { accum <<= 6; // bits shift up by 6 each time thru shift += 6; // loop, with new bits being put in accum |= value; // at the bottom. if (shift >= 8) // whenever there are 8 or more shifted in, { shift -= 8; // write them out (from the top, leaving any out[index++] = // excess at the bottom for next iteration. (byte) ((accum >> shift) & 0xff); } } // we will also have skipped processing a padding null byte ('=') here; // these are used ONLY for padding to an even length and do not legally // occur as encoded data. for this reason we can ignore the fact that // no index++ operation occurs in that special case: the out[] array is // initialized to all-zero bytes to start with and that works to our // advantage in this combination. } // if there is STILL something wrong we just have to throw up now! if (index != out.length) { throw new Error("Miscalculated data length (wrote " + index + " instead of " + out.length + ")"); } return out; } }
7,509
36.178218
125
java
soot
soot-master/src/main/java/soot/tagkit/BytecodeOffsetTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2002 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% */ /** * This class represents a tag for byte-code offset of instructions that correspond to Jimple statements. * * @author Roman Manevich. * @since October 3 2002 Initial creation. */ public class BytecodeOffsetTag implements Tag { public static final String NAME = "BytecodeOffsetTag"; /** * The index of the last byte-code instruction. */ protected final int offset; /** * Constructs a tag from the index offset. */ public BytecodeOffsetTag(int offset) { this.offset = offset; } @Override public String getName() { return NAME; } /** * Returns the offset in a four byte array. */ @Override public byte[] getValue() { byte[] v = new byte[4]; v[0] = (byte) ((offset >> 24) % 256); v[1] = (byte) ((offset >> 16) % 256); v[2] = (byte) ((offset >> 8) % 256); v[3] = (byte) (offset % 256); return v; } /** * Returns the offset as an int. */ public int getBytecodeOffset() { return offset; } /** * Returns the offset in a string. */ @Override public String toString() { return Integer.toString(offset); } }
1,950
23.696203
105
java
soot
soot-master/src/main/java/soot/tagkit/CodeAttribute.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville and Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Unit; import soot.UnitBox; import soot.baf.Baf; import soot.options.Options; /** * A CodeAttribute object holds PC -> Tag pairs. It represents abstracted attributes of Code_attribute such as * LineNumberTable, ArrayBoundsCheck. */ public class CodeAttribute extends JasminAttribute { private static final Logger logger = LoggerFactory.getLogger(CodeAttribute.class); protected List<Unit> mUnits; protected List<Tag> mTags; private final String name; private byte[] value; public CodeAttribute() { this("CodeAtribute"); } /** Creates an attribute object with the given name. */ public CodeAttribute(String name) { this.name = name; } /** Create an attribute object with the name and lists of unit-tag pairs. */ public CodeAttribute(String name, List<Unit> units, List<Tag> tags) { this.name = name; this.mUnits = units; this.mTags = tags; } /** Returns the name. */ @Override public String toString() { return name; } /** Returns the attribute name. */ @Override public String getName() { return name; } /** Only used by SOOT to read in an existing attribute without interpret it. */ @Override public void setValue(byte[] v) { this.value = v; } /** Also only used as setValue(). */ @Override public byte[] getValue() throws AttributeValueException { if (value == null) { throw new AttributeValueException(); } else { return value; } } /** Generates Jasmin Value String */ @Override public String getJasminValue(Map<Unit, String> instToLabel) { if (mTags.size() != mUnits.size()) { throw new RuntimeException("Sizes must match!"); } // some benchmarks fail because of the returned string larger than the possible buffer size. StringBuilder buf = new StringBuilder(); Iterator<Unit> unitIt = mUnits.iterator(); for (Tag tag : mTags) { Unit unit = unitIt.next(); buf.append('%').append(instToLabel.get(unit)); buf.append('%').append(new String(Base64.encode(tag.getValue()))); } return buf.toString(); } /** Returns a list of unit boxes that have tags attached. */ public List<UnitBox> getUnitBoxes() { List<UnitBox> unitBoxes = new ArrayList<UnitBox>(mUnits.size()); for (Unit next : mUnits) { unitBoxes.add(Baf.v().newInstBox(next)); } return unitBoxes; } @Override public byte[] decode(String attr, Hashtable<String, Integer> labelToPc) { if (Options.v().verbose()) { logger.debug("[] JasminAttribute decode..."); } List<byte[]> attributeHunks = new LinkedList<byte[]>(); int attributeSize = 0, tablesize = 0; boolean isLabel = attr.startsWith("%"); StringTokenizer st = new StringTokenizer(attr, "%"); while (st.hasMoreTokens()) { String token = st.nextToken(); if (isLabel) { Integer pc = labelToPc.get(token); if (pc == null) { throw new RuntimeException("PC is null, the token is " + token); } int pcvalue = pc; if (pcvalue > 65535) { throw new RuntimeException("PC great than 65535, the token is " + token + " : " + pcvalue); } attributeHunks.add(new byte[] { (byte) (pcvalue & 0x0FF), (byte) ((pcvalue >> 8) & 0x0FF) }); attributeSize += 2; tablesize++; } else { byte[] hunk = Base64.decode(token.toCharArray()); attributeSize += hunk.length; attributeHunks.add(hunk); } isLabel = !isLabel; } /* first two bytes indicate the length of attribute table. */ attributeSize += 2; byte[] attributeValue = new byte[attributeSize]; { attributeValue[0] = (byte) ((tablesize >> 8) & 0x0FF); attributeValue[1] = (byte) (tablesize & 0x0FF); } int index = 2; for (byte[] hunk : attributeHunks) { for (byte element : hunk) { attributeValue[index++] = element; } } if (index != attributeSize) { throw new RuntimeException("Index does not euqal to attrubute size : " + index + " -- " + attributeSize); } if (Options.v().verbose()) { logger.debug("[] Jasmin.decode finished..."); } return attributeValue; } }
5,314
27.88587
111
java
soot
soot-master/src/main/java/soot/tagkit/ColorTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.awt.Color; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ColorTag implements Tag { private static final Logger logger = LoggerFactory.getLogger(ColorTag.class); public static final String NAME = "ColorTag"; public static final int RED = 0; public static final int GREEN = 1; public static final int YELLOW = 2; public static final int BLUE = 3; public static final int ORANGE = 4; public static final int PURPLE = 5; private static final boolean DEFAULT_FOREGROUND = false; private static final String DEFAULT_ANALYSIS_TYPE = "Unknown"; /* it is a value representing red. */ private final int red; /* it is a value representing green. */ private final int green; /* it is a value representing blue. */ private final int blue; /* for highlighting foreground of text default is to higlight background */ private final boolean foreground; private final String analysisType; public ColorTag(Color c) { this(c.getRed(), c.getGreen(), c.getBlue(), DEFAULT_FOREGROUND, DEFAULT_ANALYSIS_TYPE); } public ColorTag(int r, int g, int b) { this(r, g, b, DEFAULT_FOREGROUND, DEFAULT_ANALYSIS_TYPE); } public ColorTag(int r, int g, int b, boolean fg) { this(r, g, b, fg, DEFAULT_ANALYSIS_TYPE); } public ColorTag(int r, int g, int b, String type) { this(r, g, b, DEFAULT_FOREGROUND, type); } public ColorTag(int r, int g, int b, boolean fg, String type) { this.red = r; this.green = g; this.blue = b; this.foreground = fg; this.analysisType = type; } public ColorTag(int color) { this(color, DEFAULT_FOREGROUND, DEFAULT_ANALYSIS_TYPE); } public ColorTag(int color, String type) { this(color, DEFAULT_FOREGROUND, type); } public ColorTag(int color, boolean fg) { this(color, fg, DEFAULT_ANALYSIS_TYPE); } public ColorTag(int color, boolean fg, String type) { switch (color) { case RED: { this.red = 255; this.green = 0; this.blue = 0; break; } case GREEN: { this.red = 45; this.green = 255; this.blue = 84; break; } case YELLOW: { this.red = 255; this.green = 248; this.blue = 35; break; } case BLUE: { this.red = 174; this.green = 210; this.blue = 255; break; } case ORANGE: { this.red = 255; this.green = 163; this.blue = 0; break; } case PURPLE: { this.red = 159; this.green = 34; this.blue = 193; break; } default: { this.red = 220; this.green = 220; this.blue = 220; break; } } this.foreground = fg; this.analysisType = type; } public String getAnalysisType() { return analysisType; } public int getRed() { return red; } public int getGreen() { return green; } public int getBlue() { return blue; } public boolean isForeground() { return foreground; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { return new byte[2]; } @Override public String toString() { return "" + red + " " + green + " " + blue; } }
4,132
22.752874
91
java
soot
soot-master/src/main/java/soot/tagkit/ConstantValueTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Archie L. Cobbs * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Arrays; import soot.jimple.Constant; public abstract class ConstantValueTag implements Tag { protected final byte[] bytes; // encoded constant protected ConstantValueTag(byte[] bytes) { this.bytes = bytes; } @Override public byte[] getValue() { return bytes; } public abstract Constant getConstant(); @Override public abstract String toString(); @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(bytes); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } ConstantValueTag other = (ConstantValueTag) obj; return Arrays.equals(bytes, other.bytes); } }
1,670
23.940299
71
java
soot
soot-master/src/main/java/soot/tagkit/DebugTypeTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 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% */ /** * Represents the signature attribute used by fields, methods and classes for dealing with generics in Java 1.5. */ public class DebugTypeTag extends SignatureTag { public static final String NAME = "DebugTypeTag"; public DebugTypeTag(String signature) { super(signature); } @Override public String toString() { return "DebugType: " + getSignature(); } @Override public String getName() { return NAME; } @Override public String getInfo() { return "DebugType"; } @Override public byte[] getValue() { throw new RuntimeException("DebugTypeTag has no value for bytecode"); } }
1,456
25.017857
112
java
soot
soot-master/src/main/java/soot/tagkit/DeprecatedTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 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% */ /** * Represents the deprecated attribute used by fields, methods and classes * * The two attributes <code>forRemoval</code> and <code>since</code> were introduced with Java 9. */ public class DeprecatedTag implements Tag { public static final String NAME = "DeprecatedTag"; private final Boolean forRemoval; private final String since; public DeprecatedTag() { forRemoval = null; since = null; } public DeprecatedTag(Boolean forRemoval, String since) { super(); this.forRemoval = forRemoval; this.since = since; } @Override public String toString() { return "Deprecated"; } @Override public String getName() { return NAME; } public String getInfo() { return "Deprecated"; } public Boolean getForRemoval() { return forRemoval; } public String getSince() { return since; } @Override public byte[] getValue() { throw new RuntimeException("DeprecatedTag has no value for bytecode"); } }
1,810
22.828947
97
java
soot
soot-master/src/main/java/soot/tagkit/DoubleConstantValueTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Archie L. Cobbs * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.DoubleConstant; public class DoubleConstantValueTag extends ConstantValueTag { public static final String NAME = "DoubleConstantValueTag"; private final double value; public DoubleConstantValueTag(double val) { super(null); this.value = val; } public double getDoubleValue() { return value; } @Override public String getName() { return NAME; } @Override public String toString() { return "ConstantValue: " + Double.toString(value); } @Override public DoubleConstant getConstant() { return DoubleConstant.v(value); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); long temp = Double.doubleToLongBits(value); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } DoubleConstantValueTag other = (DoubleConstantValueTag) obj; return Double.doubleToLongBits(this.value) == Double.doubleToLongBits(other.value); } }
2,035
24.135802
87
java
soot
soot-master/src/main/java/soot/tagkit/EnclosingMethodTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 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% */ /** * Represents the enclosing method attribute attached to anon and inner classes to indicate the class and method it is * declared in for Java 1.5. */ public class EnclosingMethodTag implements Tag { public static final String NAME = "EnclosingMethodTag"; private final String enclosingClass; private final String enclosingMethod; private final String enclosingMethodSig; public EnclosingMethodTag(String c, String m, String s) { this.enclosingClass = c; this.enclosingMethod = m; this.enclosingMethodSig = s; } @Override public String toString() { return "Enclosing Class: " + enclosingClass + " Enclosing Method: " + enclosingMethod + " Sig: " + enclosingMethodSig; } @Override public String getName() { return NAME; } public String getInfo() { return "EnclosingMethod"; } public String getEnclosingClass() { return enclosingClass; } public String getEnclosingMethod() { return enclosingMethod; } public String getEnclosingMethodSig() { return enclosingMethodSig; } @Override public byte[] getValue() { throw new RuntimeException("EnclosingMethodTag has no value for bytecode"); } }
2,008
26.148649
122
java
soot
soot-master/src/main/java/soot/tagkit/EnclosingTag.java
package soot.tagkit; /*- * #%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% */ /** * Represents the synthetic attribute. */ public class EnclosingTag extends SyntheticParamTag { public static final String NAME = "EnclosingTag"; @Override public String getName() { return NAME; } }
1,040
27.135135
71
java
soot
soot-master/src/main/java/soot/tagkit/FirstTagAggregator.java
package soot.tagkit; /*- * #%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 soot.Unit; /** * A tag aggregator that associates a tag with the <b>first</b> instruction that is tagged with it. */ public abstract class FirstTagAggregator extends TagAggregator { /** Decide whether this tag should be aggregated by this aggregator. */ @Override public void considerTag(Tag t, Unit u, LinkedList<Tag> tags, LinkedList<Unit> units) { if (units.size() <= 0 || units.getLast() != u) { units.add(u); tags.add(t); } } }
1,322
29.767442
99
java
soot
soot-master/src/main/java/soot/tagkit/FloatConstantValueTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Archie L. Cobbs * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.FloatConstant; public class FloatConstantValueTag extends ConstantValueTag { public static final String NAME = "FloatConstantValueTag"; private final float value; public FloatConstantValueTag(float value) { super(null); this.value = value; } public float getFloatValue() { return value; } @Override public String getName() { return NAME; } @Override public String toString() { return "ConstantValue: " + Float.toString(value); } @Override public FloatConstant getConstant() { return FloatConstant.v(value); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Float.floatToIntBits(value); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } FloatConstantValueTag other = (FloatConstantValueTag) obj; return Float.floatToIntBits(this.value) == Float.floatToIntBits(other.value); } }
1,971
23.65
81
java
soot
soot-master/src/main/java/soot/tagkit/GenericAttribute.java
package soot.tagkit; /*- * #%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.Arrays; import java.util.Collections; import java.util.List; import soot.UnitBox; /** * Represents a general attribute which can be attached to implementations of Host. It can be directly used to add attributes * of class files, fields, and methods. * * @see CodeAttribute */ public class GenericAttribute implements Attribute { private final String mName; private byte[] mValue; public GenericAttribute(String name, byte[] value) { this.mName = name; this.mValue = value != null ? value : new byte[0]; } @Override public String getName() { return mName; } @Override public byte[] getValue() { return mValue; } @Override public String toString() { return mName + ' ' + Arrays.toString(Base64.encode(mValue)); } @Override public void setValue(byte[] value) { mValue = value; } public List<UnitBox> getUnitBoxes() { return Collections.emptyList(); } }
1,774
24
125
java
soot
soot-master/src/main/java/soot/tagkit/Host.java
package soot.tagkit; /*- * #%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; // implemented by SootClass, SootField, SootMethod, Scene /** * A "taggable" object. Implementing classes can have arbitrary labelled data attached to them. * * Currently, only classes, fields, methods and the Scene are Hosts. * * One example of a tag would be to store Boolean values, associated with array accesses, indicating whether bounds checks * can be omitted. * * @see Tag */ public interface Host { /** Gets a list of tags associated with the current object. */ public List<Tag> getTags(); /** Returns the tag with the given name. */ public Tag getTag(String aName); /** Adds a tag. */ public void addTag(Tag t); /** Removes the first tag with the given name. */ public void removeTag(String name); /** Returns true if this host has a tag with the given name. */ public boolean hasTag(String aName); /** Removes all the tags from this host. */ public void removeAllTags(); /** Adds all the tags from h to this host. */ public void addAllTagsOf(Host h); /** * Returns the Java source line number if available. Returns -1 if not. */ public int getJavaSourceStartLineNumber(); /** * Returns the Java source line column if available. Returns -1 if not. */ public int getJavaSourceStartColumnNumber(); }
2,128
28.985915
122
java
soot
soot-master/src/main/java/soot/tagkit/IAnnotationElemTypeSwitch.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.util.Switch; public interface IAnnotationElemTypeSwitch extends Switch { public abstract void caseAnnotationAnnotationElem(AnnotationAnnotationElem v); public abstract void caseAnnotationArrayElem(AnnotationArrayElem v); public abstract void caseAnnotationBooleanElem(AnnotationBooleanElem v); public abstract void caseAnnotationClassElem(AnnotationClassElem v); public abstract void caseAnnotationDoubleElem(AnnotationDoubleElem v); public abstract void caseAnnotationEnumElem(AnnotationEnumElem v); public abstract void caseAnnotationFloatElem(AnnotationFloatElem v); public abstract void caseAnnotationIntElem(AnnotationIntElem v); public abstract void caseAnnotationLongElem(AnnotationLongElem v); public abstract void caseAnnotationStringElem(AnnotationStringElem v); public abstract void defaultCase(Object object); }
1,710
32.54902
80
java
soot
soot-master/src/main/java/soot/tagkit/ImportantTagAggregator.java
package soot.tagkit; /*- * #%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 soot.Unit; import soot.baf.Inst; /** * A tag aggregator that associates a tag with the <b>most important</b> instruction that is tagged with it. An instruction * is important if it contains a field or array reference, a method invocation, or an object allocation. */ public abstract class ImportantTagAggregator extends TagAggregator { /** Decide whether this tag should be aggregated by this aggregator. */ @Override public void considerTag(Tag t, Unit u, LinkedList<Tag> tags, LinkedList<Unit> units) { Inst i = (Inst) u; if (i.containsInvokeExpr() || i.containsFieldRef() || i.containsArrayRef() || i.containsNewExpr()) { units.add(u); tags.add(t); } } }
1,552
32.76087
123
java
soot
soot-master/src/main/java/soot/tagkit/InnerClassAttribute.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Represents an inner class attribute which can be attached to implementations of Host. It can be directly used to add * attributes to class files. */ public class InnerClassAttribute implements Tag { public static final String NAME = "InnerClassAttribute"; private ArrayList<InnerClassTag> list; public InnerClassAttribute() { this.list = null; } public InnerClassAttribute(ArrayList<InnerClassTag> list) { this.list = list; } public String getClassSpecs() { if (list == null) { return ""; } else { StringBuilder sb = new StringBuilder(); for (InnerClassTag ict : list) { sb.append(".inner_class_spec_attr "); sb.append(ict.getInnerClass()); sb.append(' '); sb.append(ict.getOuterClass()); sb.append(' '); sb.append(ict.getShortName()); sb.append(' '); sb.append(ict.getAccessFlags()); sb.append(' '); sb.append(".end .inner_class_spec_attr "); } return sb.toString(); } } @Override public String getName() { return NAME; } @Override public byte[] getValue() throws AttributeValueException { return new byte[1]; } public List<InnerClassTag> getSpecs() { return list == null ? Collections.<InnerClassTag>emptyList() : list; } public void add(InnerClassTag newt) { ArrayList<InnerClassTag> this_list = this.list; if (this_list == null) { this.list = this_list = new ArrayList<InnerClassTag>(); } else { String newt_inner = newt.getInnerClass(); int newt_accessFlags = newt.getAccessFlags(); for (InnerClassTag ict : this_list) { if (newt_inner.equals(ict.getInnerClass())) { int ict_accessFlags = ict.getAccessFlags(); if (ict_accessFlags != 0 && newt_accessFlags > 0 && ict_accessFlags != newt_accessFlags) { throw new RuntimeException("Error: trying to add an InnerClassTag twice with different access flags! (" + ict_accessFlags + " and " + newt_accessFlags + ")"); } if (ict_accessFlags == 0 && newt_accessFlags != 0) { // The Dalvik parser may find an InnerClass annotation without accessFlags in the outer class // and then an annotation with the accessFlags in the inner class. // When we have more information about the accessFlags we update the InnerClassTag. this_list.remove(ict); this_list.add(newt); } return; } } } this_list.add(newt); } }
3,465
30.509091
119
java
soot
soot-master/src/main/java/soot/tagkit/InnerClassTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Archie L. Cobbs * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.UnsupportedEncodingException; public class InnerClassTag implements Tag { public static final String NAME = "InnerClassTag"; private final String innerClass; private final String outerClass; private final String name; private final int accessFlags; public InnerClassTag(String innerClass, String outerClass, String name, int accessFlags) { this.innerClass = innerClass; this.outerClass = outerClass; this.name = name; this.accessFlags = accessFlags; if (innerClass != null && (innerClass.startsWith("L") && innerClass.endsWith(";"))) { throw new RuntimeException( "InnerClass annotation type string must be of the form a/b/ClassName not '" + innerClass + "'"); } if (outerClass != null && (outerClass.startsWith("L") && outerClass.endsWith(";"))) { throw new RuntimeException( "OuterType annotation type string must be of the form a/b/ClassName not '" + innerClass + "'"); } if (name != null && name.endsWith(";")) { throw new RuntimeException("InnerClass name cannot end with ';', got '" + name + "'"); } } @Override public String getName() { return NAME; } /** * Returns the inner class name (only) encoded in UTF8. There is no obvious standalone byte[] encoding for this attribute * because it contains embedded constant pool indices. */ @Override public byte[] getValue() { try { return innerClass.getBytes("UTF8"); } catch (UnsupportedEncodingException e) { return new byte[0]; } } public String getInnerClass() { return innerClass; } public String getOuterClass() { return outerClass; } public String getShortName() { return name; } public int getAccessFlags() { return accessFlags; } @Override public String toString() { return "[inner=" + innerClass + ", outer=" + outerClass + ", name=" + name + ",flags=" + accessFlags + "]"; } }
2,773
28.827957
123
java
soot
soot-master/src/main/java/soot/tagkit/InnerClassTagAggregator.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Map; import soot.G; import soot.Scene; import soot.SceneTransformer; import soot.Singletons; import soot.SootClass; /** The aggregator for LineNumberTable attribute. */ public class InnerClassTagAggregator extends SceneTransformer { public InnerClassTagAggregator(Singletons.Global g) { } public static InnerClassTagAggregator v() { return G.v().soot_tagkit_InnerClassTagAggregator(); } public String aggregatedName() { return "InnerClasses"; } @Override public void internalTransform(String phaseName, Map<String, String> options) { for (SootClass nextSc : Scene.v().getApplicationClasses()) { ArrayList<InnerClassTag> list = new ArrayList<InnerClassTag>(); for (Tag t : nextSc.getTags()) { if (t instanceof InnerClassTag) { list.add((InnerClassTag) t); } } if (!list.isEmpty()) { nextSc.addTag(new InnerClassAttribute(list)); } } } }
1,807
27.698413
80
java
soot
soot-master/src/main/java/soot/tagkit/IntegerConstantValueTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Archie L. Cobbs * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.IntConstant; public class IntegerConstantValueTag extends ConstantValueTag { public static final String NAME = "IntegerConstantValueTag"; private final int value; public IntegerConstantValueTag(int value) { super(new byte[] { (byte) ((value >> 24) & 0xff), (byte) ((value >> 16) & 0xff), (byte) ((value >> 8) & 0xff), (byte) ((value) & 0xff) }); this.value = value; } public int getIntValue() { return value; } @Override public String getName() { return NAME; } @Override public String toString() { return "ConstantValue: " + Integer.toString(value); } @Override public IntConstant getConstant() { return IntConstant.v(value); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + value; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } IntegerConstantValueTag other = (IntegerConstantValueTag) obj; return this.value == other.value; } }
2,037
24.160494
114
java
soot
soot-master/src/main/java/soot/tagkit/JasminAttribute.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville and Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Hashtable; import java.util.Map; import soot.Unit; /** * This class must be extended by Attributes that can be emitted in Jasmin. The attributes must format their data in Base64 * and if Unit references they may contain must be emitted as labels embedded and escaped in the attribute's Base64 data * stream at the location where the value of their pc is to occur. For example: * * <pre> aload_1 iload_2 label2: iaload label3: iastore iinc 2 1 label0: iload_2 aload_0 arraylength label4: if_icmplt label1 return .code_attribute ArrayCheckAttribute "%label2%Aw==%label3%Ag==%label4%Ag==" * * </pre> * */ public abstract class JasminAttribute implements Attribute { public abstract byte[] decode(String attr, Hashtable<String, Integer> labelToPc); public abstract String getJasminValue(Map<Unit, String> instToLabel); }
1,739
27.52459
123
java
soot
soot-master/src/main/java/soot/tagkit/JimpleLineNumberTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class JimpleLineNumberTag implements Tag { public static final String NAME = "JimpleLineNumberTag"; /* it is a value representing line number. */ private final int startLineNumber; private final int endLineNumber; public JimpleLineNumberTag(int ln) { this.startLineNumber = ln; this.endLineNumber = ln; } public JimpleLineNumberTag(int startLn, int endLn) { this.startLineNumber = startLn; this.endLineNumber = endLn; } public int getLineNumber() { return startLineNumber; } public int getStartLineNumber() { return startLineNumber; } public int getEndLineNumber() { return endLineNumber; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { return new byte[2]; } @Override public String toString() { return "Jimple Line Tag: " + startLineNumber; } }
1,713
23.485714
71
java
soot
soot-master/src/main/java/soot/tagkit/KeyTag.java
package soot.tagkit; /*- * #%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 class KeyTag implements Tag { public static final String NAME = "KeyTag"; private final int red; private final int green; private final int blue; private final String key; private final String analysisType; public KeyTag(int r, int g, int b, String k, String type) { this.red = r; this.green = g; this.blue = b; this.key = k; this.analysisType = type; } public KeyTag(int color, String k, String type) { switch (color) { case ColorTag.RED: { this.red = 255; this.green = 0; this.blue = 0; break; } case ColorTag.GREEN: { this.red = 45; this.green = 255; this.blue = 84; break; } case ColorTag.YELLOW: { this.red = 255; this.green = 248; this.blue = 35; break; } case ColorTag.BLUE: { this.red = 174; this.green = 210; this.blue = 255; break; } case ColorTag.ORANGE: { this.red = 255; this.green = 163; this.blue = 0; break; } case ColorTag.PURPLE: { this.red = 159; this.green = 34; this.blue = 193; break; } default: { this.red = 220; this.green = 220; this.blue = 220; break; } } this.key = k; this.analysisType = type; } public KeyTag(int color, String k) { this(color, k, null); } public int red() { return red; } public int green() { return green; } public int blue() { return blue; } public String key() { return key; } public String analysisType() { return analysisType; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { return new byte[4]; } }
2,665
20.15873
71
java
soot
soot-master/src/main/java/soot/tagkit/LineNumberTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2001 Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class LineNumberTag implements Tag { public static final String NAME = "LineNumberTag"; /* it is a u2 value representing line number. */ protected int line_number; public LineNumberTag(int ln) { this.line_number = ln; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { byte[] v = new byte[2]; v[0] = (byte) (line_number / 256); v[1] = (byte) (line_number % 256); return v; } public int getLineNumber() { return line_number; } public void setLineNumber(int value) { line_number = value; } @Override public String toString() { return String.valueOf(line_number); } }
1,507
23.322581
71
java
soot
soot-master/src/main/java/soot/tagkit/LineNumberTagAggregator.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.LinkedList; import soot.G; import soot.IdentityUnit; import soot.Singletons; import soot.Unit; /** The aggregator for LineNumberTable attribute. */ public class LineNumberTagAggregator extends FirstTagAggregator { public LineNumberTagAggregator(Singletons.Global g) { } public static LineNumberTagAggregator v() { return G.v().soot_tagkit_LineNumberTagAggregator(); } /** Decide whether this tag should be aggregated by this aggregator. */ @Override public boolean wantTag(Tag t) { return (t instanceof LineNumberTag) || (t instanceof SourceLnPosTag); } @Override public String aggregatedName() { return "LineNumberTable"; } @Override public void considerTag(Tag t, Unit u, LinkedList<Tag> tags, LinkedList<Unit> units) { // System.out.println("consider tag for unit: "+u.getClass()); if (!(u instanceof IdentityUnit)) { super.considerTag(t, u, tags, units); } } }
1,770
28.032787
88
java
soot
soot-master/src/main/java/soot/tagkit/LinkTag.java
package soot.tagkit; /*- * #%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% */ /** * Represents a tag that just has a string to be printed with the code. */ public class LinkTag extends StringTag { public static final String NAME = "LinkTag"; private final Host link; private final String className; public LinkTag(String string, Host link, String className, String type) { super(string, type); this.link = link; this.className = className; } public LinkTag(String string, Host link, String className) { super(string); this.link = link; this.className = className; } public String getClassName() { return className; } public Host getLink() { return link; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { throw new RuntimeException("LinkTag has no value for bytecode"); } }
1,639
24.230769
75
java
soot
soot-master/src/main/java/soot/tagkit/LongConstantValueTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Archie L. Cobbs * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.LongConstant; public class LongConstantValueTag extends ConstantValueTag { public static final String NAME = "LongConstantValueTag"; private final long value; public LongConstantValueTag(long value) { super(new byte[] { (byte) ((value >> 56) & 0xff), (byte) ((value >> 48) & 0xff), (byte) ((value >> 40) & 0xff), (byte) ((value >> 32) & 0xff), (byte) ((value >> 24) & 0xff), (byte) ((value >> 16) & 0xff), (byte) ((value >> 8) & 0xff), (byte) ((value) & 0xff) }); this.value = value; } public long getLongValue() { return value; } @Override public String getName() { return NAME; } @Override public String toString() { return "ConstantValue: " + Long.toString(value); } @Override public LongConstant getConstant() { return LongConstant.v(value); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (int) (value ^ (value >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } LongConstantValueTag other = (LongConstantValueTag) obj; return this.value == other.value; } }
2,183
25.634146
115
java
soot
soot-master/src/main/java/soot/tagkit/LoopInvariantTag.java
package soot.tagkit; /*- * #%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% */ /** * Represents a tag that just has a string to be printed with the code. */ public class LoopInvariantTag extends StringTag { public static final String NAME = "LoopInvariantTag"; public LoopInvariantTag(String s) { super(s); } @Override public String getName() { return NAME; } }
1,130
26.585366
71
java
soot
soot-master/src/main/java/soot/tagkit/OuterClassTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.UnsupportedEncodingException; import soot.SootClass; public class OuterClassTag implements Tag { public static final String NAME = "OuterClassTag"; private final SootClass outerClass; private final String simpleName; private final boolean anon; public OuterClassTag(SootClass outer, String simpleName, boolean anon) { this.outerClass = outer; this.simpleName = simpleName; this.anon = anon; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { try { return outerClass.getName().getBytes("UTF8"); } catch (UnsupportedEncodingException e) { return new byte[0]; } } public SootClass getOuterClass() { return outerClass; } public String getSimpleName() { return simpleName; } public boolean isAnon() { return anon; } @Override public String toString() { return "[outer class=" + outerClass.getName() + "]"; } }
1,790
23.202703
74
java
soot
soot-master/src/main/java/soot/tagkit/ParamNamesTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Arrays; import java.util.List; /** * Represents a tag that just has a string to be printed with the code. */ public class ParamNamesTag implements Tag { public static final String NAME = "ParamNamesTag"; private final String[] names; /** * Backwards compatibility * * @param parameterNames */ public ParamNamesTag(List<String> parameterNames) { this(parameterNames.toArray(new String[parameterNames.size()])); } public ParamNamesTag(String[] parameterNames) { this.names = parameterNames; } @Override public String toString() { return Arrays.toString(names); } public List<String> getNames() { return Arrays.asList(names); } public String[] getNameArray() { return names; } @Override public String getName() { return NAME; } public List<String> getInfo() { return getNames(); } @Override public byte[] getValue() { throw new RuntimeException("ParamNamesTag has no value for bytecode"); } }
1,831
22.792208
74
java
soot
soot-master/src/main/java/soot/tagkit/PositionTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class PositionTag implements Tag { public static final String NAME = "PositionTag"; /* it is a value representing end offset. */ private final int endOffset; /* it is a value representing start offset. */ private final int startOffset; public PositionTag(int start, int end) { this.startOffset = start; this.endOffset = end; } public int getEndOffset() { return endOffset; } public int getStartOffset() { return startOffset; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { return new byte[2]; } @Override public String toString() { return "Jimple pos tag: spos: " + startOffset + " epos: " + endOffset; } }
1,555
23.698413
74
java
soot
soot-master/src/main/java/soot/tagkit/QualifyingTag.java
package soot.tagkit; /*- * #%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% */ /** * Represents the synthetic attribute. */ public class QualifyingTag extends SyntheticParamTag { public static final String NAME = "QualifyingTag"; @Override public String getName() { return NAME; } }
1,042
27.189189
71
java
soot
soot-master/src/main/java/soot/tagkit/SignatureTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 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% */ /** * Represents the signature attribute used by fields, methods and classes for dealing with generics in Java 1.5. */ public class SignatureTag implements Tag { public static final String NAME = "SignatureTag"; private final String signature; public SignatureTag(String signature) { this.signature = signature; } public String getSignature() { return signature; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { throw new RuntimeException(NAME + " has no value for bytecode"); } public String getInfo() { return "Signature"; } @Override public String toString() { return "Signature: " + signature; } }
1,533
24.147541
112
java
soot
soot-master/src/main/java/soot/tagkit/SourceFileTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Archie L. Cobbs * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.nio.charset.StandardCharsets; public class SourceFileTag implements Tag { public static final String NAME = "SourceFileTag"; private String sourceFile; private String absolutePath; public SourceFileTag(String sourceFile) { this(sourceFile, null); } public SourceFileTag(String sourceFile, String path) { this.sourceFile = sourceFile.intern(); this.absolutePath = path; } public SourceFileTag() { } @Override public String getName() { return NAME; } @Override public byte[] getValue() { return sourceFile.getBytes(StandardCharsets.UTF_8); } public void setSourceFile(String srcFile) { sourceFile = srcFile.intern(); } public String getSourceFile() { return sourceFile; } public void setAbsolutePath(String path) { absolutePath = path; } public String getAbsolutePath() { return absolutePath; } @Override public String toString() { return sourceFile; } }
1,792
22.285714
71
java
soot
soot-master/src/main/java/soot/tagkit/SourceLineNumberTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class SourceLineNumberTag implements Tag { public static final String NAME = "SourceLineNumberTag"; /* it is a value representing line number. */ protected int startLineNumber; protected int endLineNumber; public SourceLineNumberTag(int ln) { this.startLineNumber = ln; this.endLineNumber = ln; } public SourceLineNumberTag(int startLn, int endLn) { this.startLineNumber = startLn; this.endLineNumber = endLn; } public int getLineNumber() { return startLineNumber; } public int getStartLineNumber() { return startLineNumber; } public int getEndLineNumber() { return endLineNumber; } public void setLineNumber(int value) { this.startLineNumber = value; this.endLineNumber = value; } public void setStartLineNumber(int value) { this.startLineNumber = value; } public void setEndLineNumber(int value) { this.endLineNumber = value; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { return new byte[2]; } @Override public String toString() { return String.valueOf(startLineNumber); } }
1,977
22.831325
71
java
soot
soot-master/src/main/java/soot/tagkit/SourceLnNamePosTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Eric Bodden * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * @author Eric Bodden */ public class SourceLnNamePosTag extends SourceLnPosTag { protected final String fileName; public SourceLnNamePosTag(String fileName, int sline, int eline, int spos, int epos) { super(sline, eline, spos, epos); this.fileName = fileName; } /** * @return the fileName */ public String getFileName() { return fileName; } /** * {@inheritDoc} */ @Override public String toString() { return super.toString() + " file: " + this.fileName; } }
1,335
24.692308
88
java
soot
soot-master/src/main/java/soot/tagkit/SourceLnPosTag.java
package soot.tagkit; /*- * #%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 class SourceLnPosTag implements Tag { public static final String NAME = "SourceLnPosTag"; private final int startLn; private final int endLn; private final int startPos; private final int endPos; public SourceLnPosTag(int sline, int eline, int spos, int epos) { this.startLn = sline; this.endLn = eline; this.startPos = spos; this.endPos = epos; } public int startLn() { return startLn; } public int endLn() { return endLn; } public int startPos() { return startPos; } public int endPos() { return endPos; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { byte[] v = new byte[2]; v[0] = (byte) (startLn / 256); v[1] = (byte) (startLn % 256); return v; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Source Line Pos Tag: "); sb.append("sline: ").append(startLn); sb.append(" eline: ").append(endLn); sb.append(" spos: ").append(startPos); sb.append(" epos: ").append(endPos); return sb.toString(); } }
1,951
23.098765
71
java
soot
soot-master/src/main/java/soot/tagkit/SourcePositionTag.java
package soot.tagkit; /*- * #%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 class SourcePositionTag extends PositionTag { public static final String NAME = "SourcePositionTag"; public SourcePositionTag(int i, int j) { super(i, j); } @Override public String getName() { return NAME; } }
1,062
26.973684
71
java
soot
soot-master/src/main/java/soot/tagkit/StdTagPrinter.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville and Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Default tag printer. */ public class StdTagPrinter implements TagPrinter { /** * Prints out the given tag. */ @Override public String print(String aClassName, String aFieldOrMtdSignature, Tag aTag) { return aTag.toString(); } }
1,093
28.567568
81
java
soot
soot-master/src/main/java/soot/tagkit/StringConstantValueTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Archie L. Cobbs * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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.coffi.CONSTANT_Utf8_info; import soot.jimple.StringConstant; public class StringConstantValueTag extends ConstantValueTag { public static final String NAME = "StringConstantValueTag"; private final String value; public StringConstantValueTag(String value) { super(CONSTANT_Utf8_info.toUtf8(value)); this.value = value; } public String getStringValue() { return value; } @Override public String getName() { return NAME; } @Override public String toString() { return "ConstantValue: " + value; } @Override public StringConstant getConstant() { return StringConstant.v(value); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } StringConstantValueTag other = (StringConstantValueTag) obj; if (this.value == null) { if (other.value != null) { return false; } } else if (!this.value.equals(other.value)) { return false; } return true; } }
2,150
23.443182
71
java
soot
soot-master/src/main/java/soot/tagkit/StringTag.java
package soot.tagkit; /*- * #%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% */ /** * Represents a tag that just has a string to be printed with the code. */ public class StringTag implements Tag { public static final String NAME = "StringTag"; private final String s; private final String analysisType; public StringTag(String s, String type) { this.s = s; this.analysisType = type; } public StringTag(String s) { this(s, "Unknown"); } @Override public String toString() { return s; } public String getAnalysisType() { return analysisType; } @Override public String getName() { return NAME; } public String getInfo() { return s; } @Override public byte[] getValue() { throw new RuntimeException("StringTag has no value for bytecode"); } }
1,563
22.343284
71
java
soot
soot-master/src/main/java/soot/tagkit/SyntheticParamTag.java
package soot.tagkit; /*- * #%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% */ /** * Represents the synthetic attribute. */ public class SyntheticParamTag implements Tag { public static final String NAME = "SyntheticParamTag"; public SyntheticParamTag() { } @Override public String toString() { return "SyntheticParam"; } @Override public String getName() { return NAME; } public String getInfo() { return "SyntheticParam"; } @Override public byte[] getValue() { throw new RuntimeException("SyntheticParamTag has no value for bytecode"); } }
1,337
23.777778
78
java
soot
soot-master/src/main/java/soot/tagkit/SyntheticTag.java
package soot.tagkit; /*- * #%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% */ /** * Represents the synthetic attribute. */ public class SyntheticTag implements Tag { public static final String NAME = "SyntheticTag"; public SyntheticTag() { } @Override public String toString() { return "Synthetic"; } @Override public String getName() { return NAME; } public String getInfo() { return "Synthetic"; } @Override public byte[] getValue() { throw new RuntimeException("SyntheticTag has no value for bytecode"); } }
1,307
23.222222
73
java
soot
soot-master/src/main/java/soot/tagkit/Tag.java
package soot.tagkit; /*- * #%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% */ /** * Represents a tag; these get attached to implementations of Host. */ public interface Tag { /** * Returns the tag name. */ public String getName(); /** * Returns the tag raw data. */ public byte[] getValue() throws AttributeValueException; }
1,099
27.205128
71
java
soot
soot-master/src/main/java/soot/tagkit/TagAggregator.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville and Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.LinkedList; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.Unit; import soot.baf.BafBody; /** Interface to aggregate tags of units. */ public abstract class TagAggregator extends BodyTransformer { /** Decide whether this tag should be aggregated by this aggregator. */ public abstract boolean wantTag(Tag t); /** Aggregate the given tag assigned to the given unit */ public abstract void considerTag(Tag t, Unit u, LinkedList<Tag> tags, LinkedList<Unit> units); /** Return name of the resulting aggregated tag. */ public abstract String aggregatedName(); @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { BafBody body = (BafBody) b; LinkedList<Tag> tags = new LinkedList<Tag>(); LinkedList<Unit> units = new LinkedList<Unit>(); /* aggregate all tags */ for (Unit unit : body.getUnits()) { for (Tag tag : unit.getTags()) { if (wantTag(tag)) { considerTag(tag, unit, tags, units); } } } if (units.size() > 0) { b.addTag(new CodeAttribute(aggregatedName(), new LinkedList<Unit>(units), new LinkedList<Tag>(tags))); } fini(); } /** Called after all tags for a method have been aggregated. */ public void fini() { } }
2,167
29.535211
108
java
soot
soot-master/src/main/java/soot/tagkit/TagManager.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville and Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.G; import soot.Singletons; /** Utility functions for tags. */ public class TagManager { public TagManager(Singletons.Global g) { } public static TagManager v() { return G.v().soot_tagkit_TagManager(); } private TagPrinter tagPrinter = new StdTagPrinter(); /** * Returns the Tag class with the given name. * * (This does not seem to be necessary.) */ public Tag getTagFor(String tagName) { try { Class<?> cc = Class.forName("soot.tagkit." + tagName); return (Tag) cc.newInstance(); } catch (ClassNotFoundException e) { return null; } catch (IllegalAccessException e) { throw new RuntimeException(); } catch (InstantiationException e) { throw new RuntimeException(e.toString()); } } /** Sets the default tag printer. */ public void setTagPrinter(TagPrinter p) { tagPrinter = p; } /** Prints the given Tag, assuming that it belongs to the given class and field or method. */ public String print(String aClassName, String aFieldOrMtdSignature, Tag aTag) { return tagPrinter.print(aClassName, aFieldOrMtdSignature, aTag); } }
1,980
28.567164
95
java
soot
soot-master/src/main/java/soot/tagkit/TagPrinter.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrice Pominville and Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Interface to allow display of tags. */ public interface TagPrinter { public String print(String aClassName, String aFieldOrMtdSignature, Tag aTag); }
999
31.258065
80
java
soot
soot-master/src/main/java/soot/tagkit/ThrowCreatedByCompilerTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Represents a tag that just has a string to be printed with the code. */ public class ThrowCreatedByCompilerTag implements Tag { public static final String NAME = "ThrowCreatedByCompilerTag"; public ThrowCreatedByCompilerTag() { } @Override public String getName() { return NAME; } @Override public byte[] getValue() { throw new RuntimeException("ThrowCreatedByCompilerTag has no value for bytecode"); } }
1,265
27.133333
86
java
soot
soot-master/src/main/java/soot/tagkit/TryCatchTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2012 Eric Bodden * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashMap; import java.util.Map; import soot.Unit; public class TryCatchTag implements Tag { public static final String NAME = "TryCatchTag"; protected Map<Unit, Unit> handlerUnitToFallThroughUnit = new HashMap<Unit, Unit>(); public void register(Unit handler, Unit fallThrough) { handlerUnitToFallThroughUnit.put(handler, fallThrough); } public Unit getFallThroughUnitOf(Unit handlerUnit) { return handlerUnitToFallThroughUnit.get(handlerUnit); } @Override public String getName() { return NAME; } @Override public byte[] getValue() throws AttributeValueException { throw new UnsupportedOperationException(); } }
1,494
27.207547
85
java
soot
soot-master/src/main/java/soot/tagkit/VisibilityAnnotationTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; /** * Represents the visibility of an annotation attribute attached to a class, field, method or method param (only one of these * each) has one or more annotations for Java 1.5. */ public class VisibilityAnnotationTag implements Tag { public static final String NAME = "VisibilityAnnotationTag"; private final int visibility; private ArrayList<AnnotationTag> annotations; /** * @param vis * one of {@link soot.tagkit.AnnotationConstants} */ public VisibilityAnnotationTag(int vis) { this.visibility = vis; } @Override public String toString() { // should also print here number of annotations and perhaps the annotations themselves StringBuilder sb = new StringBuilder("Visibility Annotation: level: "); switch (visibility) { case AnnotationConstants.RUNTIME_INVISIBLE: sb.append("CLASS (runtime-invisible)"); break; case AnnotationConstants.RUNTIME_VISIBLE: sb.append("RUNTIME (runtime-visible)"); break; case AnnotationConstants.SOURCE_VISIBLE: sb.append("SOURCE"); break; } sb.append("\n Annotations:"); if (annotations != null) { for (AnnotationTag tag : annotations) { sb.append('\n'); sb.append(tag.toString()); } } sb.append('\n'); return sb.toString(); } @Override public String getName() { return NAME; } public String getInfo() { return "VisibilityAnnotation"; } public int getVisibility() { return visibility; } @Override public byte[] getValue() { throw new RuntimeException("VisibilityAnnotationTag has no value for bytecode"); } public void addAnnotation(AnnotationTag a) { if (annotations == null) { annotations = new ArrayList<AnnotationTag>(); } annotations.add(a); } public ArrayList<AnnotationTag> getAnnotations() { return annotations; } public boolean hasAnnotations() { return annotations != null && !annotations.isEmpty(); } }
2,860
26.247619
125
java
soot
soot-master/src/main/java/soot/tagkit/VisibilityLocalVariableAnnotationTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 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% */ /** * Represents the visibility of an annotation attribute attached to method local variable. Only mark the local variable tag * different with{@link soot.tagkit.VisibilityParameterAnnotationTag} * * @author raintung.li */ public class VisibilityLocalVariableAnnotationTag extends VisibilityParameterAnnotationTag { public static final String NAME = "VisibilityLocalVariableAnnotationTag"; /** * @param num * number of local variable annotations * @param kind * one of {@link soot.tagkit.AnnotationConstants} */ public VisibilityLocalVariableAnnotationTag(int num, int kind) { super(num, kind); } @Override public String toString() { // should also print here number of annotations and perhaps the annotations themselves int num_var = getVisibilityAnnotations() != null ? getVisibilityAnnotations().size() : 0; StringBuilder sb = new StringBuilder("Visibility LocalVariable Annotation: num Annotation: "); sb.append(num_var).append(" kind: ").append(getKind()); if (num_var > 0) { for (VisibilityAnnotationTag tag : getVisibilityAnnotations()) { sb.append('\n'); if (tag != null) { sb.append(tag.toString()); } } } sb.append('\n'); return sb.toString(); } @Override public String getName() { return NAME; } /** * Returns Local Variable tag info * * @return string */ @Override public String getInfo() { return "VisibilityLocalVariableAnnotation"; } /** * VisibilityLocalVariableAnnotationTag not support * * @return */ @Override public byte[] getValue() { throw new RuntimeException("VisibilityLocalVariableAnnotationTag has no value for bytecode"); } }
2,577
28.295455
123
java
soot
soot-master/src/main/java/soot/tagkit/VisibilityParameterAnnotationTag.java
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; /** * Represents the visibility of an annotation attribute attached to a class, field, method or method param (only one of these * each) has one or more annotations for Java 1.5. */ public class VisibilityParameterAnnotationTag implements Tag { public static final String NAME = "VisibilityParameterAnnotationTag"; private final int num_params; private final int kind; private ArrayList<VisibilityAnnotationTag> visibilityAnnotations; /** * NOTE: any parameter without annotations has a {@code null} entry in the list * * @param num * total number of parameters * @param kind * one of {@link soot.tagkit.AnnotationConstants} */ public VisibilityParameterAnnotationTag(int num, int kind) { this.num_params = num; this.kind = kind; } @Override public String toString() { // should also print here number of annotations and perhaps the annotations themselves StringBuilder sb = new StringBuilder("Visibility Param Annotation: num params: "); sb.append(num_params).append(" kind: ").append(kind); if (visibilityAnnotations != null) { for (VisibilityAnnotationTag tag : visibilityAnnotations) { sb.append('\n'); if (tag != null) { sb.append(tag.toString()); } } } sb.append('\n'); return sb.toString(); } @Override public String getName() { return NAME; } public String getInfo() { return "VisibilityParameterAnnotation"; } @Override public byte[] getValue() { throw new RuntimeException("VisibilityParameterAnnotationTag has no value for bytecode"); } public void addVisibilityAnnotation(VisibilityAnnotationTag a) { if (visibilityAnnotations == null) { visibilityAnnotations = new ArrayList<VisibilityAnnotationTag>(); } visibilityAnnotations.add(a); } public ArrayList<VisibilityAnnotationTag> getVisibilityAnnotations() { return visibilityAnnotations; } public int getKind() { return kind; } public int getNumParams() { return num_params; } }
2,923
27.666667
125
java
soot
soot-master/src/main/java/soot/toDex/ConstantVisitor.java
package soot.toDex; /*- * #%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 org.jf.dexlib2.Opcode; import org.jf.dexlib2.iface.reference.StringReference; import org.jf.dexlib2.iface.reference.TypeReference; import org.jf.dexlib2.immutable.reference.ImmutableStringReference; import org.jf.dexlib2.immutable.reference.ImmutableTypeReference; import soot.jimple.AbstractConstantSwitch; import soot.jimple.ClassConstant; import soot.jimple.DoubleConstant; import soot.jimple.FloatConstant; import soot.jimple.IntConstant; import soot.jimple.LongConstant; import soot.jimple.NullConstant; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.toDex.instructions.Insn; import soot.toDex.instructions.Insn11n; import soot.toDex.instructions.Insn21c; import soot.toDex.instructions.Insn21s; import soot.toDex.instructions.Insn31i; import soot.toDex.instructions.Insn51l; import soot.util.Switchable; /** * A visitor that builds a list of instructions from the Jimple constants it visits.<br> * <br> * Use {@link Switchable#apply(soot.util.Switch)} with this visitor to add statements. These are added to the instructions in * the {@link StmtVisitor}.<br> * Do not forget to use {@link #setDestination(Register)} to set the storage location for the constant. * * @see StmtVisitor */ public class ConstantVisitor extends AbstractConstantSwitch { private StmtVisitor stmtV; private Register destinationReg; private Stmt origStmt; public ConstantVisitor(StmtVisitor stmtV) { this.stmtV = stmtV; } public void setDestination(Register destinationReg) { this.destinationReg = destinationReg; } public void setOrigStmt(Stmt stmt) { this.origStmt = stmt; } @Override public void defaultCase(Object o) { // const* opcodes not used since there seems to be no point in doing so: // CONST_HIGH16, CONST_WIDE_HIGH16 throw new Error("unknown Object (" + o.getClass() + ") as Constant: " + o); } @Override public void caseStringConstant(StringConstant s) { StringReference ref = new ImmutableStringReference(s.value); stmtV.addInsn(new Insn21c(Opcode.CONST_STRING, destinationReg, ref), origStmt); } @Override public void caseClassConstant(ClassConstant c) { TypeReference referencedClass = new ImmutableTypeReference(c.getValue()); stmtV.addInsn(new Insn21c(Opcode.CONST_CLASS, destinationReg, referencedClass), origStmt); } @Override public void caseLongConstant(LongConstant l) { long constant = l.value; stmtV.addInsn(buildConstWideInsn(constant), origStmt); } private Insn buildConstWideInsn(long literal) { if (SootToDexUtils.fitsSigned16(literal)) { return new Insn21s(Opcode.CONST_WIDE_16, destinationReg, (short) literal); } else if (SootToDexUtils.fitsSigned32(literal)) { return new Insn31i(Opcode.CONST_WIDE_32, destinationReg, (int) literal); } else { return new Insn51l(Opcode.CONST_WIDE, destinationReg, literal); } } @Override public void caseDoubleConstant(DoubleConstant d) { long longBits = Double.doubleToLongBits(d.value); stmtV.addInsn(buildConstWideInsn(longBits), origStmt); } @Override public void caseFloatConstant(FloatConstant f) { int intBits = Float.floatToIntBits(f.value); stmtV.addInsn(buildConstInsn(intBits), origStmt); } private Insn buildConstInsn(int literal) { if (SootToDexUtils.fitsSigned4(literal)) { return new Insn11n(Opcode.CONST_4, destinationReg, (byte) literal); } else if (SootToDexUtils.fitsSigned16(literal)) { return new Insn21s(Opcode.CONST_16, destinationReg, (short) literal); } else { return new Insn31i(Opcode.CONST, destinationReg, literal); } } @Override public void caseIntConstant(IntConstant i) { stmtV.addInsn(buildConstInsn(i.value), origStmt); } @Override public void caseNullConstant(NullConstant v) { // dex bytecode spec says: "In terms of bitwise representation, (Object) // null == (int) 0." stmtV.addInsn(buildConstInsn(0), origStmt); } }
4,824
31.823129
125
java
soot
soot-master/src/main/java/soot/toDex/Debug.java
// // (c) 2012 University of Luxembourg - Interdisciplinary Centre for // Security Reliability and Trust (SnT) - All rights reserved // // Author: Alexandre Bartel // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 2.1 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // package soot.toDex; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.options.Options; public class Debug { public static boolean TODEX_DEBUG; public static void printDbg(String s, Object... objects) { TODEX_DEBUG = Options.v().verbose(); if (TODEX_DEBUG) { for (Object o : objects) { s += o.toString(); } System.out.println(s); } } public static void printDbg(boolean c, String s, Object... objects) { if (c) { printDbg(s, objects); } } }
2,130
30.80597
78
java
soot
soot-master/src/main/java/soot/toDex/DexArrayInitDetector.java
package soot.toDex; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import soot.Body; import soot.Trap; import soot.Unit; import soot.Value; import soot.jimple.ArrayRef; import soot.jimple.AssignStmt; import soot.jimple.IntConstant; import soot.jimple.NewArrayExpr; /** * Detector class that identifies array initializations and packs them into a single instruction: * * a = new char[2]; a[0] = 42; a[1] = 3; * * In dex, this can be expressed in a more concise way: * * a = new char[2]; fill(a, ...) * * @author Steven Arzt * */ public class DexArrayInitDetector { private Map<Unit, List<Value>> arrayInitToFillValues = new HashMap<Unit, List<Value>>(); private Set<Unit> ignoreUnits = new HashSet<Unit>(); private int minimumArrayLength = -1; /** * Constructs packed array initializations from the individual element assignments in the given body * * @param body * The body in which to look for element assignments */ public void constructArrayInitializations(Body body) { // Find an array construction followed by consecutive element // assignments Unit arrayInitStmt = null; List<Value> arrayValues = null; Set<Unit> curIgnoreUnits = null; int arraySize = 0; Value concernedArray = null; for (Unit u : body.getUnits()) { if (!(u instanceof AssignStmt)) { arrayValues = null; continue; } AssignStmt assignStmt = (AssignStmt) u; if (assignStmt.getRightOp() instanceof NewArrayExpr) { NewArrayExpr newArrayExp = (NewArrayExpr) assignStmt.getRightOp(); if (newArrayExp.getSize() instanceof IntConstant) { IntConstant intConst = (IntConstant) newArrayExp.getSize(); if (minimumArrayLength == -1 || intConst.value >= minimumArrayLength) { arrayValues = new ArrayList<Value>(); arraySize = intConst.value; curIgnoreUnits = new HashSet<Unit>(); concernedArray = assignStmt.getLeftOp(); } } else { arrayValues = null; } } else if (assignStmt.getLeftOp() instanceof ArrayRef && assignStmt.getRightOp() instanceof IntConstant /* * NumericConstant */ && arrayValues != null) { ArrayRef aref = (ArrayRef) assignStmt.getLeftOp(); if (aref.getBase() != concernedArray) { arrayValues = null; continue; } if (aref.getIndex() instanceof IntConstant) { IntConstant intConst = (IntConstant) aref.getIndex(); if (intConst.value == arrayValues.size()) { arrayValues.add(assignStmt.getRightOp()); if (intConst.value == 0) { arrayInitStmt = u; } else if (intConst.value == arraySize - 1) { curIgnoreUnits.add(u); checkAndSave(arrayInitStmt, arrayValues, arraySize, curIgnoreUnits); arrayValues = null; } else { curIgnoreUnits.add(u); } } else { arrayValues = null; } } else { arrayValues = null; } } else { arrayValues = null; } } } /** * Sets the minimum array length to consider * * Only arrays with more than this number of elements will be identified, because we only need to handle those explicitly. * For small arrays, we can have individual assignments for each element in the code, but for larger methods, this would * exceed the allowed method size according to the JVM / Dalvik Spec. * * @param l * the minimum length of arrays */ public void setMinimumArrayLength(int l) { minimumArrayLength = l; } private void checkAndSave(Unit arrayInitStmt, List<Value> arrayValues, int arraySize, Set<Unit> curIgnoreUnits) { // If we already have all assignments, construct the filler if (arrayValues != null && arrayValues.size() == arraySize && arrayInitStmt != null) { arrayInitToFillValues.put(arrayInitStmt, arrayValues); ignoreUnits.addAll(curIgnoreUnits); } } public List<Value> getValuesForArrayInit(Unit arrayInit) { return arrayInitToFillValues.get(arrayInit); } public Set<Unit> getIgnoreUnits() { return ignoreUnits; } /** * Fixes the traps in the given body to account for assignments to individual array elements being replaced by a single * fill instruction. If a trap starts or ends in the middle of the replaced instructions, we have to move the trap. * * @param activeBody * The body in which to fix the traps */ public void fixTraps(Body activeBody) { traps: for (Iterator<Trap> trapIt = activeBody.getTraps().iterator(); trapIt.hasNext();) { Trap t = trapIt.next(); Unit beginUnit = t.getBeginUnit(); Unit endUnit = t.getEndUnit(); while (ignoreUnits.contains(beginUnit)) { beginUnit = activeBody.getUnits().getPredOf(beginUnit); if (beginUnit == endUnit) { trapIt.remove(); continue traps; } // The trap must start no earlier than the initial array filling if (arrayInitToFillValues.containsKey(beginUnit)) { break; } } while (ignoreUnits.contains(endUnit)) { endUnit = activeBody.getUnits().getSuccOf(endUnit); if (beginUnit == endUnit) { trapIt.remove(); continue traps; } } t.setBeginUnit(beginUnit); t.setEndUnit(endUnit); } } }
6,460
31.467337
124
java
soot
soot-master/src/main/java/soot/toDex/DexPrinter.java
package soot.toDex; /*- * #%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.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; 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.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.jf.dexlib2.AnnotationVisibility; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.Opcodes; import org.jf.dexlib2.builder.BuilderInstruction; import org.jf.dexlib2.builder.BuilderOffsetInstruction; import org.jf.dexlib2.builder.Label; import org.jf.dexlib2.builder.MethodImplementationBuilder; import org.jf.dexlib2.iface.Annotation; import org.jf.dexlib2.iface.AnnotationElement; import org.jf.dexlib2.iface.ClassDef; import org.jf.dexlib2.iface.ExceptionHandler; import org.jf.dexlib2.iface.Field; import org.jf.dexlib2.iface.Method; import org.jf.dexlib2.iface.MethodImplementation; import org.jf.dexlib2.iface.MethodParameter; import org.jf.dexlib2.iface.instruction.Instruction; import org.jf.dexlib2.iface.reference.FieldReference; import org.jf.dexlib2.iface.reference.MethodReference; import org.jf.dexlib2.iface.reference.StringReference; import org.jf.dexlib2.iface.reference.TypeReference; import org.jf.dexlib2.iface.value.EncodedValue; import org.jf.dexlib2.immutable.ImmutableAnnotation; import org.jf.dexlib2.immutable.ImmutableAnnotationElement; import org.jf.dexlib2.immutable.ImmutableClassDef; import org.jf.dexlib2.immutable.ImmutableExceptionHandler; import org.jf.dexlib2.immutable.ImmutableField; import org.jf.dexlib2.immutable.ImmutableMethod; import org.jf.dexlib2.immutable.ImmutableMethodParameter; import org.jf.dexlib2.immutable.reference.ImmutableFieldReference; import org.jf.dexlib2.immutable.reference.ImmutableMethodReference; import org.jf.dexlib2.immutable.reference.ImmutableStringReference; import org.jf.dexlib2.immutable.reference.ImmutableTypeReference; import org.jf.dexlib2.immutable.value.ImmutableAnnotationEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableArrayEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableBooleanEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableByteEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableCharEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableDoubleEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableEnumEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableFieldEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableFloatEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableIntEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableLongEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableMethodEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableNullEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableShortEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableStringEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableTypeEncodedValue; import org.jf.dexlib2.writer.builder.BuilderEncodedValues; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BooleanType; import soot.ByteType; import soot.CharType; import soot.CompilationDeathException; import soot.IntType; import soot.Local; import soot.PackManager; import soot.RefType; import soot.Scene; import soot.ShortType; import soot.SootClass; import soot.SootField; import soot.SootFieldRef; import soot.SootMethod; import soot.SootMethodRef; import soot.SourceLocator; import soot.Trap; import soot.Type; import soot.Unit; import soot.dexpler.DexInnerClassParser; import soot.dexpler.DexType; import soot.dexpler.Util; import soot.jimple.ClassConstant; import soot.jimple.IdentityStmt; import soot.jimple.Jimple; import soot.jimple.MonitorStmt; import soot.jimple.NopStmt; import soot.jimple.Stmt; import soot.jimple.toolkits.scalar.EmptySwitchEliminator; import soot.options.Options; import soot.tagkit.AbstractHost; import soot.tagkit.AnnotationAnnotationElem; import soot.tagkit.AnnotationArrayElem; import soot.tagkit.AnnotationBooleanElem; import soot.tagkit.AnnotationClassElem; import soot.tagkit.AnnotationConstants; import soot.tagkit.AnnotationDefaultTag; import soot.tagkit.AnnotationDoubleElem; import soot.tagkit.AnnotationElem; import soot.tagkit.AnnotationEnumElem; import soot.tagkit.AnnotationFloatElem; import soot.tagkit.AnnotationIntElem; import soot.tagkit.AnnotationLongElem; import soot.tagkit.AnnotationStringElem; import soot.tagkit.AnnotationTag; import soot.tagkit.ConstantValueTag; import soot.tagkit.DeprecatedTag; import soot.tagkit.DoubleConstantValueTag; import soot.tagkit.EnclosingMethodTag; import soot.tagkit.FloatConstantValueTag; import soot.tagkit.InnerClassAttribute; import soot.tagkit.InnerClassTag; import soot.tagkit.IntegerConstantValueTag; import soot.tagkit.LineNumberTag; import soot.tagkit.LongConstantValueTag; import soot.tagkit.ParamNamesTag; import soot.tagkit.SignatureTag; import soot.tagkit.SourceFileTag; import soot.tagkit.StringConstantValueTag; import soot.tagkit.Tag; import soot.tagkit.VisibilityAnnotationTag; import soot.tagkit.VisibilityParameterAnnotationTag; import soot.toDex.instructions.Insn; import soot.toDex.instructions.Insn10t; import soot.toDex.instructions.Insn30t; import soot.toDex.instructions.InsnWithOffset; import soot.util.Chain; /** * <p> * Creates {@code apk} or {@code jar} file with compiled {@code dex} classes. Main entry point for the "dex" output format. * </p> * <p> * Use {@link #add(SootClass)} to add classes that should be printed as dex output and {@link #print()} to finally print the * classes. * </p> * <p> * If the printer has found the original {@code APK} of an added class (via {@link SourceLocator#dexClassIndex()}), the files * in the {@code APK} are copied to a new one, replacing it's {@code classes.dex} and excluding the signature files. Note * that you have to sign and align the APK yourself, with jarsigner and zipalign, respectively. * </p> * <p> * If {@link Options#output_jar} flag is set, the printer produces {@code JAR} file. * </p> * <p> * If there is no original {@code APK} and {@link Options#output_jar} flag is not set the printer just emits a * {@code classes.dex}. * </p> * * @see <a href= "https://docs.oracle.com/javase/8/docs/technotes/tools/windows/jarsigner.html">jarsigner documentation</a> * @see <a href="http://developer.android.com/tools/help/zipalign.html">zipalign documentation</a> */ public class DexPrinter { private static final Logger LOGGER = LoggerFactory.getLogger(DexPrinter.class); public static final Pattern SIGNATURE_FILE_PATTERN = Pattern.compile("META-INF/[^/]+(\\.SF|\\.DSA|\\.RSA|\\.EC)$"); protected MultiDexBuilder dexBuilder; protected File originalApk; public DexPrinter() { dexBuilder = createDexBuilder(); } /** * Creates the {@link MultiDexBuilder} that shall be used for creating potentially multiple dex files. This method makes * sure that users of Soot can overwrite the {@link MultiDexBuilder} with custom strategies. * * @return The new {@link MultiDexBuilder} */ protected MultiDexBuilder createDexBuilder() { // we have to create a dex file with the minimum sdk level set. If we build with the target sdk version, // we break the backwards compatibility of the app. Scene.AndroidVersionInfo androidSDKVersionInfo = Scene.v().getAndroidSDKVersionInfo(); int apiLevel; if (androidSDKVersionInfo == null) { apiLevel = Scene.v().getAndroidAPIVersion(); } else { apiLevel = Math.min(androidSDKVersionInfo.minSdkVersion, androidSDKVersionInfo.sdkTargetVersion); } return new MultiDexBuilder(Opcodes.forApi(apiLevel)); } private static boolean isSignatureFile(String fileName) { return SIGNATURE_FILE_PATTERN.matcher(fileName).matches(); } /** * Converts Jimple visibility to Dexlib visibility * * @param visibility * Jimple visibility * @return Dexlib visibility */ private static int getVisibility(int visibility) { if (visibility == AnnotationConstants.RUNTIME_VISIBLE) { return AnnotationVisibility.RUNTIME; } if (visibility == AnnotationConstants.RUNTIME_INVISIBLE) { return AnnotationVisibility.SYSTEM; } if (visibility == AnnotationConstants.SOURCE_VISIBLE) { return AnnotationVisibility.BUILD; } throw new DexPrinterException("Unknown annotation visibility: '" + visibility + "'"); } protected static FieldReference toFieldReference(SootField f) { FieldReference fieldRef = new ImmutableFieldReference(SootToDexUtils.getDexClassName(f.getDeclaringClass().getName()), f.getName(), SootToDexUtils.getDexTypeDescriptor(f.getType())); return fieldRef; } protected static FieldReference toFieldReference(SootFieldRef ref) { FieldReference fieldRef = new ImmutableFieldReference(SootToDexUtils.getDexClassName(ref.declaringClass().getName()), ref.name(), SootToDexUtils.getDexTypeDescriptor(ref.type())); return fieldRef; } protected static MethodReference toMethodReference(SootMethodRef m) { List<String> parameters = new ArrayList<String>(); for (Type t : m.getParameterTypes()) { parameters.add(SootToDexUtils.getDexTypeDescriptor(t)); } return new ImmutableMethodReference(SootToDexUtils.getDexClassName(m.getDeclaringClass().getName()), m.getName(), parameters, SootToDexUtils.getDexTypeDescriptor(m.getReturnType())); } public static TypeReference toTypeReference(Type t) { return new ImmutableTypeReference(SootToDexUtils.getDexTypeDescriptor(t)); } private void printZip() throws IOException { try (ZipOutputStream outputZip = getZipOutputStream()) { LOGGER.info("Do not forget to sign the .apk file with jarsigner and to align it with zipalign"); if (originalApk != null) { // Copy over additional resources from original APK try (ZipFile original = new ZipFile(originalApk)) { copyAllButClassesDexAndSigFiles(original, outputZip); } } // put our dex files into the zip archive final Path tempPath = Files.createTempDirectory(Long.toString(System.nanoTime())); final List<File> files = dexBuilder.writeTo(tempPath.toString()); if (!files.isEmpty()) { final byte[] buffer = new byte[16 * 1024]; for (File file : files) { try (InputStream is = Files.newInputStream(file.toPath())) { outputZip.putNextEntry(new ZipEntry(file.getName())); for (int read; (read = is.read(buffer)) > 0;) { outputZip.write(buffer, 0, read); } outputZip.closeEntry(); } } } if (Options.v().output_jar()) { // if we create JAR file, MANIFEST.MF is preferred addManifest(outputZip, files); } // remove tmp dir and contents Files.walkFileTree(tempPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } } private ZipOutputStream getZipOutputStream() throws IOException { if (Options.v().output_jar()) { LOGGER.info("Writing JAR to \"{}\"", Options.v().output_dir()); return PackManager.v().getJarFile(); } final String name = originalApk == null ? "out.apk" : originalApk.getName(); if (originalApk == null) { LOGGER.warn("Setting output file name to \"{}\" as original APK has not been found.", name); } final Path outputFile = Paths.get(SourceLocator.v().getOutputDir(), name); if (Files.exists(outputFile, LinkOption.NOFOLLOW_LINKS)) { if (!Options.v().force_overwrite()) { throw new CompilationDeathException("Output file \"" + outputFile + "\" exists. Not overwriting."); } try { Files.delete(outputFile); } catch (IOException exception) { throw new IllegalStateException("Removing \"" + outputFile + "\" failed. Not writing out anything.", exception); } } LOGGER.info("Writing APK to \"{}\".", outputFile); return new ZipOutputStream(Files.newOutputStream(outputFile, StandardOpenOption.CREATE_NEW)); } private void copyAllButClassesDexAndSigFiles(ZipFile source, ZipOutputStream destination) throws IOException { for (Enumeration<? extends ZipEntry> sourceEntries = source.entries(); sourceEntries.hasMoreElements();) { ZipEntry sourceEntry = sourceEntries.nextElement(); String sourceEntryName = sourceEntry.getName(); if (sourceEntryName.endsWith(".dex") || isSignatureFile(sourceEntryName)) { continue; } // separate ZipEntry avoids compression problems due to encodings ZipEntry destinationEntry = new ZipEntry(sourceEntryName); // use the same compression method as the original (certain files // are stored, not compressed) destinationEntry.setMethod(sourceEntry.getMethod()); // copy other necessary fields for STORE method destinationEntry.setSize(sourceEntry.getSize()); destinationEntry.setCrc(sourceEntry.getCrc()); // finally craft new entry destination.putNextEntry(destinationEntry); try (InputStream zipEntryInput = source.getInputStream(sourceEntry)) { byte[] buffer = new byte[2048]; for (int bytesRead; (bytesRead = zipEntryInput.read(buffer)) > 0;) { destination.write(buffer, 0, bytesRead); } } } } private void addManifest(ZipOutputStream destination, Collection<File> dexFiles) throws IOException { final Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(new Attributes.Name("Created-By"), "Soot Dex Printer"); if (dexFiles != null && !dexFiles.isEmpty()) { manifest.getMainAttributes().put(new Attributes.Name("Dex-Location"), dexFiles.stream().map(File::getName).collect(Collectors.joining(" "))); } final ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME); destination.putNextEntry(manifestEntry); try (BufferedOutputStream bufOut = new BufferedOutputStream(destination)) { manifest.write(bufOut); bufOut.flush(); } destination.closeEntry(); } /** * Encodes Annotations Elements from Jimple to Dexlib * * @param elem * Jimple Element * @return Dexlib encoded element */ private EncodedValue buildEncodedValueForAnnotation(AnnotationElem elem) { switch (elem.getKind()) { case 'Z': { if (elem instanceof AnnotationIntElem) { AnnotationIntElem e = (AnnotationIntElem) elem; switch (e.getValue()) { case 0: return ImmutableBooleanEncodedValue.FALSE_VALUE; case 1: return ImmutableBooleanEncodedValue.TRUE_VALUE; default: throw new DexPrinterException("error: boolean value from int with value != 0 or 1."); } } else if (elem instanceof AnnotationBooleanElem) { AnnotationBooleanElem e = (AnnotationBooleanElem) elem; if (e.getValue()) { return ImmutableBooleanEncodedValue.TRUE_VALUE; } else { return ImmutableBooleanEncodedValue.FALSE_VALUE; } } else { throw new DexPrinterException("Annotation type incompatible with target type boolean"); } } case 'S': { AnnotationIntElem e = (AnnotationIntElem) elem; return new ImmutableShortEncodedValue((short) e.getValue()); } case 'B': { AnnotationIntElem e = (AnnotationIntElem) elem; return new ImmutableByteEncodedValue((byte) e.getValue()); } case 'C': { AnnotationIntElem e = (AnnotationIntElem) elem; return new ImmutableCharEncodedValue((char) e.getValue()); } case 'I': { AnnotationIntElem e = (AnnotationIntElem) elem; return new ImmutableIntEncodedValue(e.getValue()); } case 'J': { AnnotationLongElem e = (AnnotationLongElem) elem; return new ImmutableLongEncodedValue(e.getValue()); } case 'F': { AnnotationFloatElem e = (AnnotationFloatElem) elem; return new ImmutableFloatEncodedValue(e.getValue()); } case 'D': { AnnotationDoubleElem e = (AnnotationDoubleElem) elem; return new ImmutableDoubleEncodedValue(e.getValue()); } case 's': { AnnotationStringElem e = (AnnotationStringElem) elem; return new ImmutableStringEncodedValue(e.getValue()); } case 'e': { AnnotationEnumElem e = (AnnotationEnumElem) elem; String classT = SootToDexUtils.getDexClassName(e.getTypeName()); String fieldT = classT; return new ImmutableEnumEncodedValue(new ImmutableFieldReference(classT, e.getConstantName(), fieldT)); } case 'c': { AnnotationClassElem e = (AnnotationClassElem) elem; return new ImmutableTypeEncodedValue(e.getDesc()); } case '[': { AnnotationArrayElem e = (AnnotationArrayElem) elem; List<EncodedValue> values = new ArrayList<EncodedValue>(); for (int i = 0; i < e.getNumValues(); i++) { values.add(buildEncodedValueForAnnotation(e.getValueAt(i))); } return new ImmutableArrayEncodedValue(values); } case '@': { AnnotationAnnotationElem e = (AnnotationAnnotationElem) elem; List<AnnotationElement> elements = null; Collection<AnnotationElem> elems = e.getValue().getElems(); if (!elems.isEmpty()) { elements = new ArrayList<AnnotationElement>(); Set<String> alreadyWritten = new HashSet<String>(); for (AnnotationElem ae : elems) { if (!alreadyWritten.add(ae.getName())) { throw new DexPrinterException("Duplicate annotation attribute: " + ae.getName()); } elements.add(new ImmutableAnnotationElement(ae.getName(), buildEncodedValueForAnnotation(ae))); } } return new ImmutableAnnotationEncodedValue(SootToDexUtils.getDexClassName(e.getValue().getType()), elements); } case 'f': { // field (Dalvik specific?) AnnotationStringElem e = (AnnotationStringElem) elem; String fSig = e.getValue(); String[] sp = fSig.split(" "); String classString = SootToDexUtils.getDexClassName(sp[0].split(":")[0]); if (classString.isEmpty()) { throw new DexPrinterException("Empty class name in annotation"); } String typeString = sp[1]; if (typeString.isEmpty()) { throw new DexPrinterException("Empty type string in annotation"); } String fieldName = sp[2]; return new ImmutableFieldEncodedValue(new ImmutableFieldReference(classString, fieldName, typeString)); } case 'M': { // method (Dalvik specific?) AnnotationStringElem e = (AnnotationStringElem) elem; String[] sp = e.getValue().split(" "); String classString = SootToDexUtils.getDexClassName(sp[0].split(":")[0]); if (classString.isEmpty()) { throw new DexPrinterException("Empty class name in annotation"); } String returnType = sp[1]; String[] sp2 = sp[2].split("\\("); String methodNameString = sp2[0]; String parameters = sp2[1].replaceAll("\\)", ""); List<String> paramTypeList = parameters.isEmpty() ? null : Arrays.asList(parameters.split(",")); return new ImmutableMethodEncodedValue( new ImmutableMethodReference(classString, methodNameString, paramTypeList, returnType)); } case 'N': { // null (Dalvik specific?) return ImmutableNullEncodedValue.INSTANCE; } default: throw new DexPrinterException("Unknown Elem Attr Kind: " + elem.getKind()); } } protected EncodedValue makeConstantItem(SootField sf, Tag t) { if (!(t instanceof ConstantValueTag)) { throw new DexPrinterException("error: t not ConstantValueTag."); } if (t instanceof IntegerConstantValueTag) { IntegerConstantValueTag i = (IntegerConstantValueTag) t; Type sft = sf.getType(); if (sft instanceof BooleanType) { int v = i.getIntValue(); switch (v) { case 0: return ImmutableBooleanEncodedValue.FALSE_VALUE; case 1: return ImmutableBooleanEncodedValue.TRUE_VALUE; default: throw new DexPrinterException("error: boolean value from int with value != 0 or 1."); } } else if (sft instanceof CharType) { return new ImmutableCharEncodedValue((char) i.getIntValue()); } else if (sft instanceof ByteType) { return new ImmutableByteEncodedValue((byte) i.getIntValue()); } else if (sft instanceof IntType) { return new ImmutableIntEncodedValue(i.getIntValue()); } else if (sft instanceof ShortType) { return new ImmutableShortEncodedValue((short) i.getIntValue()); } else { throw new DexPrinterException("error: unexpected constant tag type: " + t + " for field " + sf); } } else if (t instanceof LongConstantValueTag) { LongConstantValueTag l = (LongConstantValueTag) t; return new ImmutableLongEncodedValue(l.getLongValue()); } else if (t instanceof DoubleConstantValueTag) { DoubleConstantValueTag d = (DoubleConstantValueTag) t; return new ImmutableDoubleEncodedValue(d.getDoubleValue()); } else if (t instanceof FloatConstantValueTag) { FloatConstantValueTag f = (FloatConstantValueTag) t; return new ImmutableFloatEncodedValue(f.getFloatValue()); } else if (t instanceof StringConstantValueTag) { StringConstantValueTag s = (StringConstantValueTag) t; if (sf.getType().equals(RefType.v("java.lang.String"))) { return new ImmutableStringEncodedValue(s.getStringValue()); } else { // Not supported in Dalvik // See // https://android.googlesource.com/platform/dalvik.git/+/android-4.3_r3/vm/oo/Class.cpp // Results in "Bogus static initialization" return null; } } else { throw new DexPrinterException("Unexpected constant type"); } } private void addAsClassDefItem(SootClass c) { // add source file tag if any SourceFileTag sft = (SourceFileTag) c.getTag(SourceFileTag.NAME); String sourceFile = sft == null ? null : sft.getSourceFile(); String classType = SootToDexUtils.getDexTypeDescriptor(c.getType()); int accessFlags = c.getModifiers(); String superClass = c.hasSuperclass() ? SootToDexUtils.getDexTypeDescriptor(c.getSuperclass().getType()) : null; List<String> interfaces = null; if (!c.getInterfaces().isEmpty()) { interfaces = new ArrayList<String>(); for (SootClass ifc : c.getInterfaces()) { interfaces.add(SootToDexUtils.getDexTypeDescriptor(ifc.getType())); } } List<Field> fields = null; if (!c.getFields().isEmpty()) { fields = new ArrayList<Field>(); for (SootField f : c.getFields()) { // We do not want to write out phantom fields if (isIgnored(f)) { continue; } // Look for a static initializer EncodedValue staticInit = null; for (Tag t : f.getTags()) { if (t instanceof ConstantValueTag) { if (staticInit != null) { LOGGER.warn("More than one constant tag for field \"{}\": \"{}\"", f, t); } else { staticInit = makeConstantItem(f, t); } } } if (staticInit == null) { staticInit = BuilderEncodedValues.defaultValueForType(SootToDexUtils.getDexTypeDescriptor(f.getType())); } // Build field annotations Set<Annotation> fieldAnnotations = buildFieldAnnotations(f); ImmutableField field = new ImmutableField(classType, f.getName(), SootToDexUtils.getDexTypeDescriptor(f.getType()), f.getModifiers(), staticInit, fieldAnnotations, null); fields.add(field); } } Collection<Method> methods = toMethods(c); ClassDef classDef = new ImmutableClassDef(classType, accessFlags, superClass, interfaces, sourceFile, buildClassAnnotations(c), fields, methods); dexBuilder.internClass(classDef); } private Set<Annotation> buildClassAnnotations(SootClass c) { Set<String> skipList = new HashSet<String>(); Set<Annotation> annotations = buildCommonAnnotations(c, skipList); // Classes can have either EnclosingMethod or EnclosingClass tags. Soot // sets the outer class for both "normal" and anonymous inner classes, // so we test for enclosing methods first. EnclosingMethodTag eMethTag = (EnclosingMethodTag) c.getTag(EnclosingMethodTag.NAME); if (eMethTag != null) { Annotation enclosingMethodItem = buildEnclosingMethodTag(eMethTag, skipList); if (enclosingMethodItem != null) { annotations.add(enclosingMethodItem); } } else if (c.hasOuterClass()) { if (skipList.add("Ldalvik/annotation/EnclosingClass;")) { // EnclosingClass annotation ImmutableAnnotationElement enclosingElement = new ImmutableAnnotationElement("value", new ImmutableTypeEncodedValue(SootToDexUtils.getDexClassName(c.getOuterClass().getName()))); annotations.add(new ImmutableAnnotation(AnnotationVisibility.SYSTEM, "Ldalvik/annotation/EnclosingClass;", Collections.singleton(enclosingElement))); } } // If we have an outer class, we also pick up the InnerClass annotations // from there. Note that Java and Soot associate InnerClass annotations // with the respective outer classes, while Dalvik puts them on the // respective inner classes. if (c.hasOuterClass()) { InnerClassAttribute icTag = (InnerClassAttribute) c.getOuterClass().getTag(InnerClassAttribute.NAME); if (icTag != null) { List<Annotation> innerClassItem = buildInnerClassAttribute(c, icTag, skipList); if (innerClassItem != null) { annotations.addAll(innerClassItem); } } } writeMemberClasses(c, skipList, annotations); for (Tag t : c.getTags()) { if (VisibilityAnnotationTag.NAME.equals(t.getName())) { annotations.addAll(buildVisibilityAnnotationTag((VisibilityAnnotationTag) t, skipList)); } } // Write default-annotation tags List<AnnotationElem> defaults = new ArrayList<AnnotationElem>(); for (SootMethod method : c.getMethods()) { AnnotationDefaultTag tag = (AnnotationDefaultTag) method.getTag(AnnotationDefaultTag.NAME); if (tag != null) { tag.getDefaultVal().setName(method.getName()); defaults.add(tag.getDefaultVal()); } } if (!defaults.isEmpty()) { VisibilityAnnotationTag defaultAnnotationTag = new VisibilityAnnotationTag(AnnotationConstants.RUNTIME_INVISIBLE); AnnotationTag a = new AnnotationTag("Ldalvik/annotation/AnnotationDefault;"); defaultAnnotationTag.addAnnotation(a); AnnotationTag at = new AnnotationTag(SootToDexUtils.getDexClassName(c.getName())); AnnotationAnnotationElem ae = new AnnotationAnnotationElem(at, '@', "value"); a.addElem(ae); for (AnnotationElem aelem : defaults) { at.addElem(aelem); } annotations.addAll(buildVisibilityAnnotationTag(defaultAnnotationTag, skipList)); } return annotations; } protected void writeMemberClasses(SootClass c, Set<String> skipList, Set<Annotation> annotations) { // Write the MemberClasses tag InnerClassAttribute icTag = (InnerClassAttribute) c.getTag(InnerClassAttribute.NAME); if (icTag != null) { List<Annotation> memberClassesItem = buildMemberClassesAttribute(c, icTag, skipList); if (memberClassesItem != null) { annotations.addAll(memberClassesItem); } } } private Set<Annotation> buildFieldAnnotations(SootField f) { Set<String> skipList = new HashSet<String>(); Set<Annotation> annotations = buildCommonAnnotations(f, skipList); for (Tag t : f.getTags()) { if (VisibilityAnnotationTag.NAME.equals(t.getName())) { annotations.addAll(buildVisibilityAnnotationTag((VisibilityAnnotationTag) t, skipList)); } } return annotations; } private Set<Annotation> buildMethodAnnotations(SootMethod m) { Set<String> skipList = new HashSet<String>(); Set<Annotation> annotations = buildCommonAnnotations(m, skipList); for (Tag t : m.getTags()) { if (VisibilityAnnotationTag.NAME.equals(t.getName())) { annotations.addAll(buildVisibilityAnnotationTag((VisibilityAnnotationTag) t, skipList)); } } List<SootClass> exceptionList = m.getExceptionsUnsafe(); if (exceptionList != null && !exceptionList.isEmpty()) { List<ImmutableEncodedValue> valueList = new ArrayList<ImmutableEncodedValue>(exceptionList.size()); for (SootClass exceptionClass : exceptionList) { valueList.add(new ImmutableTypeEncodedValue(DexType.toDalvikICAT(exceptionClass.getName()).replace(".", "/"))); } ImmutableArrayEncodedValue valueValue = new ImmutableArrayEncodedValue(valueList); ImmutableAnnotationElement valueElement = new ImmutableAnnotationElement("value", valueValue); Set<ImmutableAnnotationElement> elements = Collections.singleton(valueElement); ImmutableAnnotation ann = new ImmutableAnnotation(AnnotationVisibility.SYSTEM, "Ldalvik/annotation/Throws;", elements); annotations.add(ann); } return annotations; } /** * Returns all method parameter annotations (or null) for a specific parameter * * @param m * the method * @param paramIdx * the parameter index * @return the annotations (or null) */ private Set<Annotation> buildMethodParameterAnnotations(SootMethod m, final int paramIdx) { Set<String> skipList = null; Set<Annotation> annotations = null; for (Tag t : m.getTags()) { if (VisibilityParameterAnnotationTag.NAME.equals(t.getName())) { VisibilityParameterAnnotationTag vat = (VisibilityParameterAnnotationTag) t; if (skipList == null) { skipList = new HashSet<String>(); annotations = new HashSet<Annotation>(); } annotations.addAll(buildVisibilityParameterAnnotationTag(vat, skipList, paramIdx)); } } return annotations; } private Set<Annotation> buildCommonAnnotations(AbstractHost host, Set<String> skipList) { Set<Annotation> annotations = new HashSet<Annotation>(); // handle deprecated tag if (host.hasTag(DeprecatedTag.NAME) && !skipList.contains("Ljava/lang/Deprecated;")) { ImmutableAnnotation ann = new ImmutableAnnotation(AnnotationVisibility.RUNTIME, "Ljava/lang/Deprecated;", Collections.<AnnotationElement>emptySet()); annotations.add(ann); skipList.add("Ljava/lang/Deprecated;"); } // handle signature tag if (!skipList.contains("Ldalvik/annotation/Signature;")) { SignatureTag tag = (SignatureTag) host.getTag(SignatureTag.NAME); if (tag != null) { List<String> splitSignature = SootToDexUtils.splitSignature(tag.getSignature()); Set<ImmutableAnnotationElement> elements = null; if (splitSignature != null && splitSignature.size() > 0) { List<ImmutableEncodedValue> valueList = new ArrayList<ImmutableEncodedValue>(); for (String s : splitSignature) { valueList.add(new ImmutableStringEncodedValue(s)); } ImmutableArrayEncodedValue valueValue = new ImmutableArrayEncodedValue(valueList); ImmutableAnnotationElement valueElement = new ImmutableAnnotationElement("value", valueValue); elements = Collections.singleton(valueElement); } else { LOGGER.info("Signature annotation without value detected"); } annotations.add(new ImmutableAnnotation(AnnotationVisibility.SYSTEM, "Ldalvik/annotation/Signature;", elements)); skipList.add("Ldalvik/annotation/Signature;"); } } return annotations; } private List<ImmutableAnnotation> buildVisibilityAnnotationTag(VisibilityAnnotationTag t, Set<String> skipList) { if (t.getAnnotations() == null) { return Collections.emptyList(); } List<ImmutableAnnotation> annotations = new ArrayList<ImmutableAnnotation>(); for (AnnotationTag at : t.getAnnotations()) { String type = at.getType(); if (!skipList.add(type)) { continue; } List<AnnotationElement> elements = null; Collection<AnnotationElem> elems = at.getElems(); if (!elems.isEmpty()) { elements = new ArrayList<AnnotationElement>(); Set<String> alreadyWritten = new HashSet<String>(); for (AnnotationElem ae : elems) { if (ae.getName() == null || ae.getName().isEmpty()) { throw new DexPrinterException("Null or empty annotation name encountered"); } if (!alreadyWritten.add(ae.getName())) { throw new DexPrinterException("Duplicate annotation attribute: " + ae.getName()); } EncodedValue value = buildEncodedValueForAnnotation(ae); ImmutableAnnotationElement element = new ImmutableAnnotationElement(ae.getName(), value); elements.add(element); } } String typeName = SootToDexUtils.getDexClassName(at.getType()); annotations.add(new ImmutableAnnotation(getVisibility(t.getVisibility()), typeName, elements)); } return annotations; } private List<ImmutableAnnotation> buildVisibilityParameterAnnotationTag(VisibilityParameterAnnotationTag t, Set<String> skipList, int paramIdx) { if (t.getVisibilityAnnotations() == null) { return Collections.emptyList(); } int paramTagIdx = 0; List<ImmutableAnnotation> annotations = new ArrayList<ImmutableAnnotation>(); for (VisibilityAnnotationTag vat : t.getVisibilityAnnotations()) { if (paramTagIdx == paramIdx && vat != null && vat.getAnnotations() != null) { for (AnnotationTag at : vat.getAnnotations()) { String type = at.getType(); if (!skipList.add(type)) { continue; } List<AnnotationElement> elements = null; Collection<AnnotationElem> elems = at.getElems(); if (!elems.isEmpty()) { elements = new ArrayList<AnnotationElement>(); Set<String> alreadyWritten = new HashSet<String>(); for (AnnotationElem ae : elems) { if (ae.getName() == null || ae.getName().isEmpty()) { throw new DexPrinterException("Null or empty annotation name encountered"); } if (!alreadyWritten.add(ae.getName())) { throw new DexPrinterException("Duplicate annotation attribute: " + ae.getName()); } EncodedValue value = buildEncodedValueForAnnotation(ae); elements.add(new ImmutableAnnotationElement(ae.getName(), value)); } } ImmutableAnnotation ann = new ImmutableAnnotation(getVisibility(vat.getVisibility()), SootToDexUtils.getDexClassName(at.getType()), elements); annotations.add(ann); } } paramTagIdx++; } return annotations; } private Annotation buildEnclosingMethodTag(EnclosingMethodTag t, Set<String> skipList) { if (!skipList.add("Ldalvik/annotation/EnclosingMethod;")) { return null; } if (t.getEnclosingMethod() == null) { return null; } String[] split1 = t.getEnclosingMethodSig().split("\\)"); String parametersS = split1[0].replaceAll("\\(", ""); String returnTypeS = split1[1]; List<String> typeList = new ArrayList<String>(); if (!parametersS.isEmpty()) { for (String p : Util.splitParameters(parametersS)) { if (!p.isEmpty()) { typeList.add(p); } } } ImmutableMethodReference mRef = new ImmutableMethodReference(SootToDexUtils.getDexClassName(t.getEnclosingClass()), t.getEnclosingMethod(), typeList, returnTypeS); ImmutableMethodEncodedValue methodRef = new ImmutableMethodEncodedValue(mRef); AnnotationElement methodElement = new ImmutableAnnotationElement("value", methodRef); return new ImmutableAnnotation(AnnotationVisibility.SYSTEM, "Ldalvik/annotation/EnclosingMethod;", Collections.singleton(methodElement)); } private List<Annotation> buildInnerClassAttribute(SootClass parentClass, InnerClassAttribute t, Set<String> skipList) { if (t.getSpecs() == null) { return null; } List<Annotation> anns = null; for (Tag t2 : t.getSpecs()) { InnerClassTag icTag = (InnerClassTag) t2; // In Dalvik, both the EnclosingMethod/EnclosingClass tag and the // InnerClass tag are written to the inner class which is different // to Java. We thus check whether this tag actually points to our // outer class. String outerClass = DexInnerClassParser.getOuterClassNameFromTag(icTag); String innerClass = icTag.getInnerClass().replace('/', '.'); // Only write the InnerClass tag to the inner class itself, not // the other one. If the outer class points to our parent, but // this is simply the wrong inner class, we also continue with the // next tag. if (!parentClass.hasOuterClass() || !innerClass.equals(parentClass.getName())) { continue; } // If the outer class points to the very same class, we null it if (parentClass.getName().equals(outerClass) && icTag.getOuterClass() == null) { outerClass = null; } // Do not write garbage. Never. if (parentClass.getName().equals(outerClass)) { continue; } // This is an actual inner class. Write the annotation if (skipList.add("Ldalvik/annotation/InnerClass;")) { // InnerClass annotation List<AnnotationElement> elements = new ArrayList<AnnotationElement>(); ImmutableAnnotationElement flagsElement = new ImmutableAnnotationElement("accessFlags", new ImmutableIntEncodedValue(icTag.getAccessFlags())); elements.add(flagsElement); ImmutableEncodedValue nameValue; if (icTag.getShortName() != null && !icTag.getShortName().isEmpty()) { nameValue = new ImmutableStringEncodedValue(icTag.getShortName()); } else { nameValue = ImmutableNullEncodedValue.INSTANCE; } elements.add(new ImmutableAnnotationElement("name", nameValue)); if (anns == null) { anns = new ArrayList<Annotation>(); } anns.add(new ImmutableAnnotation(AnnotationVisibility.SYSTEM, "Ldalvik/annotation/InnerClass;", elements)); } } return anns; } private List<Annotation> buildMemberClassesAttribute(SootClass parentClass, InnerClassAttribute t, Set<String> skipList) { List<Annotation> anns = null; Set<String> memberClasses = null; // Collect the inner classes for (Tag t2 : t.getSpecs()) { InnerClassTag icTag = (InnerClassTag) t2; String outerClass = DexInnerClassParser.getOuterClassNameFromTag(icTag); // Only classes with names are member classes if (icTag.getOuterClass() != null && parentClass.getName().equals(outerClass)) { if (memberClasses == null) { memberClasses = new HashSet<String>(); } memberClasses.add(SootToDexUtils.getDexClassName(icTag.getInnerClass())); } } // Write the member classes if (memberClasses != null && !memberClasses.isEmpty() && skipList.add("Ldalvik/annotation/MemberClasses;")) { List<EncodedValue> classes = new ArrayList<EncodedValue>(); for (String memberClass : memberClasses) { classes.add(new ImmutableTypeEncodedValue(memberClass)); } ImmutableArrayEncodedValue classesValue = new ImmutableArrayEncodedValue(classes); ImmutableAnnotationElement element = new ImmutableAnnotationElement("value", classesValue); ImmutableAnnotation memberAnnotation = new ImmutableAnnotation(AnnotationVisibility.SYSTEM, "Ldalvik/annotation/MemberClasses;", Collections.singletonList(element)); if (anns == null) { anns = new ArrayList<Annotation>(); } anns.add(memberAnnotation); } return anns; } protected Collection<Method> toMethods(SootClass clazz) { if (clazz.getMethods().isEmpty()) { return null; } String classType = SootToDexUtils.getDexTypeDescriptor(clazz.getType()); List<Method> methods = new ArrayList<Method>(); for (SootMethod sm : clazz.getMethods()) { if (isIgnored(sm)) { // Do not print method bodies for inherited methods continue; } MethodImplementation impl; try { impl = toMethodImplementation(sm); } catch (Exception e) { throw new DexPrinterException("Error while processing method " + sm, e); } ParamNamesTag pnt = (ParamNamesTag) sm.getTag(ParamNamesTag.NAME); List<String> parameterNames = pnt == null ? null : pnt.getNames(); int paramIdx = 0; List<MethodParameter> parameters = null; if (sm.getParameterCount() > 0) { parameters = new ArrayList<>(); for (Type tp : sm.getParameterTypes()) { String paramType = SootToDexUtils.getDexTypeDescriptor(tp); parameters.add(new ImmutableMethodParameter(paramType, buildMethodParameterAnnotations(sm, paramIdx), sm.isConcrete() && parameterNames != null ? parameterNames.get(paramIdx) : null)); paramIdx++; } } String returnType = SootToDexUtils.getDexTypeDescriptor(sm.getReturnType()); ImmutableMethod meth = new ImmutableMethod(classType, sm.getName(), parameters, returnType, SootToDexUtils.getDexAccessFlags(sm), buildMethodAnnotations(sm), null, impl); methods.add(meth); } return methods; } /** * Checks whether the given method shall be ignored, i.e., not written out to dex * * @param sm * The method to check * @return True to ignore the method while writing the dex file, false to write it out as normal */ protected boolean isIgnored(SootMethod sm) { return sm.isPhantom(); } /** * Checks whether the given field shall be ignored, i.e., not written out to dex * * @param sf * The field to check * @return True to ignore the field while writing the dex file, false to write it out as normal */ protected boolean isIgnored(SootField sf) { return sf.isPhantom(); } protected MethodImplementation toMethodImplementation(SootMethod m) { if (m.isAbstract() || m.isNative()) { return null; } Body activeBody = m.retrieveActiveBody(); final String mName = m.getName(); if (mName.isEmpty()) { throw new DexPrinterException("Invalid empty method name: " + m.getSignature()); } // check the method name to make sure that dexopt won't get into trouble // when installing the app. See function IsValidMemberName // https://android.googlesource.com/platform/art/+/refs/heads/master/libdexfile/dex/descriptors_names.cc#271 if (mName.indexOf('<') >= 0 || mName.indexOf('>') >= 0) { if (!"<init>".equals(mName) && !"<clinit>".equals(mName)) { throw new DexPrinterException("Invalid method name: " + m.getSignature()); } } // Switch statements may not be empty in dex, so we have to fix this first EmptySwitchEliminator.v().transform(activeBody); // Dalvik requires synchronized methods to have explicit monitor calls, // so we insert them here. See // http://milk.com/kodebase/dalvik-docs-mirror/docs/debugger.html // We cannot place this upon the developer since it is only required // for Dalvik, but not for other targets. SynchronizedMethodTransformer.v().transform(activeBody); // Tries may not start or end at units which have no corresponding // Dalvik // instructions such as IdentityStmts. We reduce the traps to start at // the // first "real" instruction. We could also use a TrapTigthener, but that // would be too expensive for what we need here. FastDexTrapTightener.v().transform(activeBody); // Look for sequences of array element assignments that we can collapse // into bulk initializations DexArrayInitDetector initDetector = new DexArrayInitDetector(); initDetector.constructArrayInitializations(activeBody); initDetector.fixTraps(activeBody); // Split the tries since Dalvik does not supported nested try/catch // blocks TrapSplitter.v().transform(activeBody); // word count of incoming parameters int inWords = SootToDexUtils.getDexWords(m.getParameterTypes()); if (!m.isStatic()) { inWords++; // extra word for "this" } // word count of max outgoing parameters Collection<Unit> units = activeBody.getUnits(); // register count = parameters + additional registers, depending on the // dex instructions generated (e.g. locals used and constants loaded) StmtVisitor stmtV = buildStmtVisitor(m, initDetector); Chain<Trap> traps = activeBody.getTraps(); Set<Unit> trapReferences = new HashSet<Unit>(traps.size() * 3); for (Trap t : traps) { trapReferences.add(t.getBeginUnit()); trapReferences.add(t.getEndUnit()); trapReferences.add(t.getHandlerUnit()); } toInstructions(units, stmtV, trapReferences); int registerCount = stmtV.getRegisterCount(); if (inWords > registerCount) { /* * as the Dalvik VM moves the parameters into the last registers, the "in" word count must be at least equal to the * register count. a smaller register count could occur if soot generated the method body, see e.g. the handling of * phantom refs in SootMethodRefImpl.resolve(StringBuffer): the body has no locals for the ParameterRefs, it just * throws an error. * * we satisfy the verifier by just increasing the register count, since calling phantom refs will lead to an error * anyway. */ registerCount = inWords; } MethodImplementationBuilder builder = new MethodImplementationBuilder(registerCount); LabelAssigner labelAssigner = new LabelAssigner(builder); List<BuilderInstruction> instructions = stmtV.getRealInsns(labelAssigner); Map<Local, Integer> seenRegisters = new HashMap<>(); Map<Instruction, LocalRegisterAssignmentInformation> instructionRegisterMap = stmtV.getInstructionRegisterMap(); if (Options.v().write_local_annotations()) { for (LocalRegisterAssignmentInformation assignment : stmtV.getParameterInstructionsList()) { // The "this" local gets added automatically, so we do not need // to add it explicitly // (at least not if it exists with exactly this name) if ("this".equals(assignment.getLocal().getName())) { continue; } addRegisterAssignmentDebugInfo(assignment, seenRegisters, builder); } } // Do not insert instructions into the instruction list after this step. // Otherwise the jump offsets again may exceed the maximum offset limit! fixLongJumps(instructions, labelAssigner, stmtV); for (BuilderInstruction ins : instructions) { Stmt origStmt = stmtV.getStmtForInstruction(ins); // If this is a switch payload, we need to place the label if (stmtV.getInstructionPayloadMap().containsKey(ins)) { builder.addLabel(labelAssigner.getLabelName(stmtV.getInstructionPayloadMap().get(ins))); } if (origStmt != null) { // Do we need a label here because this a trap handler? if (trapReferences.contains(origStmt)) { labelAssigner.getOrCreateLabel(origStmt); } // Add the label if the statement has one String labelName = labelAssigner.getLabelName(origStmt); if (labelName != null && !builder.getLabel(labelName).isPlaced()) { builder.addLabel(labelName); } // Add the tags if (stmtV.getStmtForInstruction(ins) != null) { writeTagsForStatement(builder, origStmt); } } builder.addInstruction(ins); LocalRegisterAssignmentInformation registerAssignmentTag = instructionRegisterMap.get(ins); if (registerAssignmentTag != null) { // Add start local debugging information: Register -> Local // assignment addRegisterAssignmentDebugInfo(registerAssignmentTag, seenRegisters, builder); } } for (int registersLeft : seenRegisters.values()) { builder.addEndLocal(registersLeft); } toTries(activeBody.getTraps(), builder, labelAssigner); // Make sure that all labels have been placed by now for (Label lbl : labelAssigner.getAllLabels()) { if (!lbl.isPlaced()) { throw new DexPrinterException("Label not placed: " + lbl); } } return builder.getMethodImplementation(); } /** * Creates a statement visitor to build code for each statement. * * Allows subclasses to use own implementations * * @param belongingMethod * the method * @param arrayInitDetector * auxilliary class for detecting array initializations * @return the statement visitor */ protected StmtVisitor buildStmtVisitor(SootMethod belongingMethod, DexArrayInitDetector arrayInitDetector) { return new StmtVisitor(belongingMethod, arrayInitDetector); } /** * Writes out the information stored in the tags associated with the given statement * * @param builder * The builder used to generate the Dalvik method implementation * @param stmt * The statement for which to write out the tags */ protected void writeTagsForStatement(MethodImplementationBuilder builder, Stmt stmt) { for (Tag t : stmt.getTags()) { if (t instanceof LineNumberTag) { LineNumberTag lnt = (LineNumberTag) t; builder.addLineNumber(lnt.getLineNumber()); } else if (t instanceof SourceFileTag) { SourceFileTag sft = (SourceFileTag) t; builder.addSetSourceFile(new ImmutableStringReference(sft.getSourceFile())); } } } /** * Fixes long jumps that exceed the maximum distance for the respective jump type * * @param instructions * The list of generated dalvik instructions * @param labelAssigner * The label assigner that maps statements to labels * @param stmtV * The statement visitor used to produce the dalvik instructions */ private void fixLongJumps(List<BuilderInstruction> instructions, LabelAssigner labelAssigner, StmtVisitor stmtV) { // Only construct the maps once and update them afterwards Map<Instruction, Integer> instructionsToIndex = new HashMap<>(); List<Integer> instructionsToOffsets = new ArrayList<>(); Map<Label, Integer> labelsToOffsets = new HashMap<>(); Map<Label, Integer> labelsToIndex = new HashMap<>(); boolean hasChanged; l0: do { // Look for changes anew every time hasChanged = false; instructionsToOffsets.clear(); // Build a mapping between instructions and offsets { int offset = 0; int idx = 0; for (BuilderInstruction bi : instructions) { instructionsToIndex.put(bi, idx); instructionsToOffsets.add(offset); Stmt origStmt = stmtV.getStmtForInstruction(bi); if (origStmt != null) { Label lbl = labelAssigner.getLabelUnsafe(origStmt); if (lbl != null) { labelsToOffsets.put(lbl, offset); labelsToIndex.put(lbl, idx); } } offset += (bi.getFormat().size / 2); idx++; } } // Look for references to labels for (int j = 0; j < instructions.size(); j++) { BuilderInstruction bj = instructions.get(j); if (bj instanceof BuilderOffsetInstruction) { BuilderOffsetInstruction boj = (BuilderOffsetInstruction) bj; // Compute the distance between the instructions Insn jumpInsn = stmtV.getInsnForInstruction(boj); if (jumpInsn instanceof InsnWithOffset) { InsnWithOffset offsetInsn = (InsnWithOffset) jumpInsn; Integer targetOffset = labelsToOffsets.get(boj.getTarget()); if (targetOffset == null) { continue; } int distance = Math.abs(targetOffset - instructionsToOffsets.get(j)); if (distance <= offsetInsn.getMaxJumpOffset()) { // Calculate how much the offset can change when CONST_STRING (4 byte) instructions are later converted to // CONST_STRING_JUMBO instructions (6 byte). This can happen if the app has more than 2^16 strings Integer targetIndex = labelsToIndex.get(boj.getTarget()); if (targetIndex != null) { int start = Math.min(targetIndex, j); int end = Math.max(targetIndex, j); /* * Assuming every instruction between this instruction and the jump target is a CONST_STRING instruction, how * much could the distance increase? * * Because we only spend the effort to count the number of CONST_STRING instructions if there is a real * chance that it changes the distance to overflow the allowed maximum. */ int theoreticalMaximumIncrease = (end - start) * 2; // maximum increase = number of instructions * 2 byte if (distance + theoreticalMaximumIncrease > offsetInsn.getMaxJumpOffset()) { // int countConstString = 0; for (int z = start; z <= end; z++) { if (instructions.get(z).getOpcode() == Opcode.CONST_STRING) { countConstString++; } } int maxOffsetChange = countConstString * 2; // each CONST_STRING may grow by 2 bytes distance += maxOffsetChange; } } } if (distance > offsetInsn.getMaxJumpOffset()) { // We need intermediate jumps insertIntermediateJump(labelsToIndex.get(boj.getTarget()), j, stmtV, instructions, labelAssigner); hasChanged = true; continue l0; } } } } } while (hasChanged); } /** * Creates an intermediate jump instruction between the original jump instruction and its target * * @param targetInsPos * The jump target index * @param jumpInsPos * The position of the jump instruction * @param stmtV * The statement visitor used for constructing the instructions * @param instructions * The list of Dalvik instructions * @param labelAssigner * The label assigner to be used for creating new labels */ private void insertIntermediateJump(int targetInsPos, int jumpInsPos, StmtVisitor stmtV, List<BuilderInstruction> instructions, LabelAssigner labelAssigner) { // Get the original jump instruction BuilderInstruction originalJumpInstruction = instructions.get(jumpInsPos); Insn originalJumpInsn = stmtV.getInsnForInstruction(originalJumpInstruction); if (originalJumpInsn == null) { return; } if (!(originalJumpInsn instanceof InsnWithOffset)) { throw new DexPrinterException("Unexpected jump instruction target"); } InsnWithOffset offsetInsn = (InsnWithOffset) originalJumpInsn; // If this is goto instruction, we can just replace it if (originalJumpInsn instanceof Insn10t) { if (originalJumpInsn.getOpcode() == Opcode.GOTO) { Insn30t newJump = new Insn30t(Opcode.GOTO_32); newJump.setTarget(((Insn10t) originalJumpInsn).getTarget()); BuilderInstruction newJumpInstruction = newJump.getRealInsn(labelAssigner); instructions.remove(jumpInsPos); instructions.add(jumpInsPos, newJumpInstruction); stmtV.fakeNewInsn(stmtV.getStmtForInstruction(originalJumpInstruction), newJump, newJumpInstruction); return; } } // Find a position where we can jump to int distance = Math.max(targetInsPos, jumpInsPos) - Math.min(targetInsPos, jumpInsPos); if (distance == 0) { return; } int newJumpIdx = Math.min(targetInsPos, jumpInsPos) + (distance / 2); int sign = (int) Math.signum(targetInsPos - jumpInsPos); // There must be a statement at the instruction after the jump target. // This statement must not appear at an earlier statement as the jump // label may otherwise be attached to the wrong statement do { Stmt newStmt = stmtV.getStmtForInstruction(instructions.get(newJumpIdx)); Stmt prevStmt = newJumpIdx > 0 ? stmtV.getStmtForInstruction(instructions.get(newJumpIdx - 1)) : null; if (newStmt == null || newStmt == prevStmt) { newJumpIdx -= sign; if (newJumpIdx < 0 || newJumpIdx >= instructions.size()) { throw new DexPrinterException("No position for inserting intermediate jump instruction found"); } } else { break; } } while (true); // Create a jump instruction from the middle to the end NopStmt nop = Jimple.v().newNopStmt(); Insn30t newJump = new Insn30t(Opcode.GOTO_32); newJump.setTarget(stmtV.getStmtForInstruction(instructions.get(targetInsPos))); BuilderInstruction newJumpInstruction = newJump.getRealInsn(labelAssigner); instructions.add(newJumpIdx, newJumpInstruction); stmtV.fakeNewInsn(nop, newJump, newJumpInstruction); // We have added something, so we need to fix indices if (newJumpIdx <= jumpInsPos) { jumpInsPos++; } if (newJumpIdx <= targetInsPos) { targetInsPos++; } // Jump from the original instruction to the new one in the middle offsetInsn.setTarget(nop); BuilderInstruction replacementJumpInstruction = offsetInsn.getRealInsn(labelAssigner); assert (instructions.get(jumpInsPos) == originalJumpInstruction); instructions.remove(jumpInsPos); instructions.add(jumpInsPos, replacementJumpInstruction); stmtV.fakeNewInsn(stmtV.getStmtForInstruction(originalJumpInstruction), originalJumpInsn, replacementJumpInstruction); // Our indices are still fine, because we just replaced something Stmt afterNewJump = stmtV.getStmtForInstruction(instructions.get(newJumpIdx + 1)); // Make the original control flow jump around the new artificial jump // instruction Insn10t jumpAround = new Insn10t(Opcode.GOTO); jumpAround.setTarget(afterNewJump); BuilderInstruction jumpAroundInstruction = jumpAround.getRealInsn(labelAssigner); instructions.add(newJumpIdx, jumpAroundInstruction); stmtV.fakeNewInsn(Jimple.v().newNopStmt(), jumpAround, jumpAroundInstruction); } private void addRegisterAssignmentDebugInfo(LocalRegisterAssignmentInformation registerAssignment, Map<Local, Integer> seenRegisters, MethodImplementationBuilder builder) { Local local = registerAssignment.getLocal(); String dexLocalType = SootToDexUtils.getDexTypeDescriptor(local.getType()); StringReference localName = new ImmutableStringReference(local.getName()); Register reg = registerAssignment.getRegister(); int register = reg.getNumber(); Integer beforeRegister = seenRegisters.get(local); if (beforeRegister != null) { if (beforeRegister == register) { // No change return; } builder.addEndLocal(beforeRegister); } builder.addStartLocal(register, localName, new ImmutableTypeReference(dexLocalType), new ImmutableStringReference("")); seenRegisters.put(local, register); } protected void toInstructions(Collection<Unit> units, StmtVisitor stmtV, Set<Unit> trapReferences) { // Collect all constant arguments to monitor instructions and // pre-alloocate their registers Set<ClassConstant> monitorConsts = new HashSet<>(); for (Unit u : units) { if (u instanceof MonitorStmt) { MonitorStmt monitorStmt = (MonitorStmt) u; if (monitorStmt.getOp() instanceof ClassConstant) { monitorConsts.add((ClassConstant) monitorStmt.getOp()); } } } boolean monitorAllocsMade = false; for (Unit u : units) { if (!monitorAllocsMade && !monitorConsts.isEmpty() && !(u instanceof IdentityStmt)) { stmtV.preAllocateMonitorConsts(monitorConsts); monitorAllocsMade = true; } stmtV.beginNewStmt((Stmt) u); u.apply(stmtV); } stmtV.finalizeInstructions(trapReferences); } protected void toTries(Collection<Trap> traps, MethodImplementationBuilder builder, LabelAssigner labelAssigner) { // Original code: assume that the mapping startCodeAddress -> TryItem is enough for // a "code range", ignore different end Units / try lengths // That's definitely not enough since we can have two handlers H1, H2 with // H1:240-322, H2:242-322. There is no valid ordering for such // overlapping traps // in dex. Current solution: If there is already a trap T' for a subrange of the // current trap T, merge T and T' on the fully range of T. This is not a 100% // correct since we extend traps over the requested range, but it's better than // the previous code that produced APKs which failed Dalvik's bytecode verification. // (Steven Arzt, 09.08.2013) // There are cases in which we need to split traps, e.g. in cases like // ( (t1) ... (t2) )<big catch all around it> where the all three handlers do // something different. That's why we run the TrapSplitter before we get here. // (Steven Arzt, 25.09.2013) Map<CodeRange, List<ExceptionHandler>> codeRangesToTryItem = new LinkedHashMap<>(); for (Trap t : traps) { // see if there is old handler info at this code range Stmt beginStmt = (Stmt) t.getBeginUnit(); Stmt endStmt = (Stmt) t.getEndUnit(); int startCodeAddress = labelAssigner.getLabel(beginStmt).getCodeAddress(); int endCodeAddress = labelAssigner.getLabel(endStmt).getCodeAddress(); CodeRange range = new CodeRange(startCodeAddress, endCodeAddress); String exceptionType = SootToDexUtils.getDexTypeDescriptor(t.getException().getType()); int codeAddress = labelAssigner.getLabel((Stmt) t.getHandlerUnit()).getCodeAddress(); ImmutableExceptionHandler exceptionHandler = new ImmutableExceptionHandler(exceptionType, codeAddress); List<ExceptionHandler> newHandlers = new ArrayList<>(); for (CodeRange r : codeRangesToTryItem.keySet()) { // Check whether this range is contained in some other range. We // then extend our // trap over the bigger range containing this range if (r.containsRange(range)) { range.startAddress = r.startAddress; range.endAddress = r.endAddress; // copy the old handlers to a bigger array (the old one // cannot be modified...) List<ExceptionHandler> oldHandlers = codeRangesToTryItem.get(r); if (oldHandlers != null) { newHandlers.addAll(oldHandlers); } break; } // Check whether the other range is contained in this range. In // this case, // a smaller range is already in the list. We merge the two over // the larger // range. else if (range.containsRange(r)) { range.startAddress = r.startAddress; range.endAddress = r.endAddress; // just use the newly found handler info List<ExceptionHandler> oldHandlers = codeRangesToTryItem.get(range); if (oldHandlers != null) { newHandlers.addAll(oldHandlers); } // remove the old range, the new one will be added anyway // and contain // the merged handlers codeRangesToTryItem.remove(r); break; } } if (!newHandlers.contains(exceptionHandler)) { newHandlers.add(exceptionHandler); } codeRangesToTryItem.put(range, newHandlers); } // Check for overlaps for (CodeRange r1 : codeRangesToTryItem.keySet()) { for (CodeRange r2 : codeRangesToTryItem.keySet()) { if (r1 != r2 && r1.overlaps(r2)) { LOGGER.warn("Trap region overlaps detected"); } } } for (CodeRange range : codeRangesToTryItem.keySet()) { boolean allCaughtForRange = false; for (ExceptionHandler handler : codeRangesToTryItem.get(range)) { // If we have a catchall directive for a range and then some // follow-up // exception handler, we can discard the latter as it will never // be used // anyway. if (allCaughtForRange) { continue; } // Normally, we would model catchall as real catchall directives. For // some reason, this however fails with an invalid handler index. We // therefore hack it using java.lang.Throwable. if ("Ljava/lang/Throwable;".equals(handler.getExceptionType())) { /* * builder.addCatch(labelAssigner.getLabelAtAddress(range. startAddress), * labelAssigner.getLabelAtAddress(range.endAddress), labelAssigner.getLabelAtAddress(handler. * getHandlerCodeAddress())); */ allCaughtForRange = true; } // else builder.addCatch(new ImmutableTypeReference(handler.getExceptionType()), labelAssigner.getLabelAtAddress(range.startAddress), labelAssigner.getLabelAtAddress(range.endAddress), labelAssigner.getLabelAtAddress(handler.getHandlerCodeAddress())); } } } public void add(SootClass c) { if (c.isPhantom()) { return; } addAsClassDefItem(c); // save original APK for this class, needed to copy all the other files // inside Map<String, File> dexClassIndex = SourceLocator.v().dexClassIndex(); if (dexClassIndex == null) { return; // no dex classes were loaded } File sourceForClass = dexClassIndex.get(c.getName()); if (sourceForClass == null || sourceForClass.getName().endsWith(".dex")) { return; // a class was written that was not a dex class or the class // originates from a .dex file, not an APK } if (originalApk != null && !originalApk.equals(sourceForClass)) { throw new CompilationDeathException("multiple APKs as source of an application are not supported"); } originalApk = sourceForClass; } public void print() { try { if (Options.v().output_jar() || (originalApk != null && Options.v().output_format() != Options.output_format_force_dex)) { printZip(); } else { final String outputDir = SourceLocator.v().getOutputDir(); LOGGER.info("Writing dex files to \"{}\" folder.", outputDir); dexBuilder.writeTo(outputDir); } } catch (IOException e) { throw new CompilationDeathException("I/O exception while printing dex", e); } } private static class CodeRange { int startAddress; int endAddress; public CodeRange(int startAddress, int endAddress) { this.startAddress = startAddress; this.endAddress = endAddress; } /** * Checks whether the given code range r is fully enclosed by this code range. * * @param r * The other code range * @return True if the given code range r is fully enclosed by this code range, otherwise false. */ public boolean containsRange(CodeRange r) { return (r.startAddress >= this.startAddress && r.endAddress <= this.endAddress); } /** * Checks whether this range overlaps with the given one * * @param r * The region to check for overlaps * @return True if this region has a non-empty overlap with the given one */ public boolean overlaps(CodeRange r) { return (r.startAddress >= this.startAddress && r.startAddress < this.endAddress) || (r.startAddress <= this.startAddress && r.endAddress > this.startAddress); } @Override public String toString() { return this.startAddress + "-" + this.endAddress; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (other == null || !(other instanceof CodeRange)) { return false; } CodeRange cr = (CodeRange) other; return (this.startAddress == cr.startAddress && this.endAddress == cr.endAddress); } @Override public int hashCode() { return 17 * startAddress + 13 * endAddress; } } }
71,171
39.119504
125
java
soot
soot-master/src/main/java/soot/toDex/DexPrinterException.java
package soot.toDex; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2021 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% */ public class DexPrinterException extends RuntimeException { public DexPrinterException(String message) { super(message); } public DexPrinterException(Throwable cause) { super(cause); } public DexPrinterException(String message, Throwable cause) { super(message, cause); } }
1,141
27.55
71
java
soot
soot-master/src/main/java/soot/toDex/ExprVisitor.java
package soot.toDex; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.iface.reference.MethodReference; import org.jf.dexlib2.iface.reference.TypeReference; import soot.ArrayType; import soot.DoubleType; import soot.FloatType; import soot.IntType; import soot.IntegerType; import soot.Local; import soot.LongType; import soot.NullType; import soot.PrimType; import soot.RefType; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.Value; import soot.jimple.AddExpr; import soot.jimple.AndExpr; import soot.jimple.CastExpr; import soot.jimple.CmpExpr; import soot.jimple.CmpgExpr; import soot.jimple.CmplExpr; import soot.jimple.DivExpr; import soot.jimple.DynamicInvokeExpr; import soot.jimple.EqExpr; import soot.jimple.Expr; import soot.jimple.ExprSwitch; import soot.jimple.GeExpr; import soot.jimple.GtExpr; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InstanceOfExpr; import soot.jimple.IntConstant; import soot.jimple.InterfaceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.LeExpr; import soot.jimple.LengthExpr; import soot.jimple.LongConstant; import soot.jimple.LtExpr; import soot.jimple.MulExpr; import soot.jimple.NeExpr; import soot.jimple.NegExpr; import soot.jimple.NewArrayExpr; import soot.jimple.NewExpr; import soot.jimple.NewMultiArrayExpr; import soot.jimple.NullConstant; import soot.jimple.OrExpr; import soot.jimple.RemExpr; import soot.jimple.ShlExpr; import soot.jimple.ShrExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.SubExpr; import soot.jimple.UshrExpr; import soot.jimple.VirtualInvokeExpr; import soot.jimple.XorExpr; import soot.toDex.instructions.Insn; import soot.toDex.instructions.Insn10x; import soot.toDex.instructions.Insn11x; import soot.toDex.instructions.Insn12x; import soot.toDex.instructions.Insn21c; import soot.toDex.instructions.Insn21t; import soot.toDex.instructions.Insn22b; import soot.toDex.instructions.Insn22c; import soot.toDex.instructions.Insn22s; import soot.toDex.instructions.Insn22t; import soot.toDex.instructions.Insn23x; import soot.toDex.instructions.Insn35c; import soot.toDex.instructions.Insn3rc; import soot.toDex.instructions.InsnWithOffset; import soot.util.Switchable; /** * A visitor that builds a list of instructions from the Jimple expressions it visits.<br> * <br> * Use {@link Switchable#apply(soot.util.Switch)} with this visitor to add statements. These are added to the instructions in * the {@link StmtVisitor}.<br> * If the expression is part of an assignment or an if statement, use {@link #setDestinationReg(Register)} and * {@link #setTargetForOffset(Stmt)}, respectively. * * @see StmtVisitor */ public class ExprVisitor implements ExprSwitch { protected StmtVisitor stmtV; protected ConstantVisitor constantV; protected RegisterAllocator regAlloc; protected Register destinationReg; protected Stmt targetForOffset; protected Stmt origStmt; private int lastInvokeInstructionPosition; public ExprVisitor(StmtVisitor stmtV, ConstantVisitor constantV, RegisterAllocator regAlloc) { this.stmtV = stmtV; this.constantV = constantV; this.regAlloc = regAlloc; } public void setDestinationReg(Register destinationReg) { this.destinationReg = destinationReg; } public void setOrigStmt(Stmt stmt) { this.origStmt = stmt; } public void setTargetForOffset(Stmt targetForOffset) { this.targetForOffset = targetForOffset; } @Override public void defaultCase(Object o) { // rsub-int and rsub-int/lit8 aren't generated, since we cannot detect // there usage in jimple throw new Error("unknown Object (" + o.getClass() + ") as Expression: " + o); } @Override public void caseDynamicInvokeExpr(DynamicInvokeExpr v) { throw new Error("DynamicInvokeExpr not supported: " + v); } @Override public void caseSpecialInvokeExpr(SpecialInvokeExpr sie) { MethodReference method = DexPrinter.toMethodReference(sie.getMethodRef()); List<Register> arguments = getInstanceInvokeArgumentRegs(sie); lastInvokeInstructionPosition = stmtV.getInstructionCount(); if (isCallToConstructor(sie) || isCallToPrivate(sie)) { stmtV.addInsn(buildInvokeInsn("INVOKE_DIRECT", method, arguments), origStmt); } else if (isCallToSuper(sie)) { stmtV.addInsn(buildInvokeInsn("INVOKE_SUPER", method, arguments), origStmt); } else { // This should normally never happen, but if we have such a // broken call (happens in malware for instance), we fix it. stmtV.addInsn(buildInvokeInsn("INVOKE_VIRTUAL", method, arguments), origStmt); } } private Insn buildInvokeInsn(String invokeOpcode, MethodReference method, List<Register> argumentRegs) { Insn invokeInsn; int regCountForArguments = SootToDexUtils.getRealRegCount(argumentRegs); if (regCountForArguments <= 5) { Register[] paddedArray = pad35cRegs(argumentRegs); Opcode opc = Opcode.valueOf(invokeOpcode); invokeInsn = new Insn35c(opc, regCountForArguments, paddedArray[0], paddedArray[1], paddedArray[2], paddedArray[3], paddedArray[4], method); } else if (regCountForArguments <= 255) { Opcode opc = Opcode.valueOf(invokeOpcode + "_RANGE"); invokeInsn = new Insn3rc(opc, argumentRegs, (short) regCountForArguments, method); } else { throw new Error( "too many parameter registers for invoke-* (> 255): " + regCountForArguments + " or registers too big (> 4 bits)"); } // save the return type for the move-result insn stmtV.setLastReturnTypeDescriptor(method.getReturnType()); return invokeInsn; } private boolean isCallToPrivate(SpecialInvokeExpr sie) { return sie.getMethod().isPrivate(); } private boolean isCallToConstructor(SpecialInvokeExpr sie) { return sie.getMethodRef().name().equals(SootMethod.constructorName); } private boolean isCallToSuper(SpecialInvokeExpr sie) { SootClass classWithInvokation = sie.getMethod().getDeclaringClass(); SootClass currentClass = stmtV.getBelongingClass(); while (currentClass != null) { currentClass = currentClass.getSuperclassUnsafe(); if (currentClass != null) { if (currentClass == classWithInvokation) { return true; } // If we're dealing with phantom classes, we might not actually // arrive at java.lang.Object. In this case, we should not fail // the check if (currentClass.isPhantom() && !currentClass.getName().equals("java.lang.Object")) { return true; } } } return false; // we arrived at java.lang.Object and did not find a // declaration } @Override public void caseVirtualInvokeExpr(VirtualInvokeExpr vie) { /* * for final methods we build an invoke-virtual opcode, too, although the dex spec says that a virtual method is not * final. An alternative would be the invoke-direct opcode, but this is inconsistent with dx's output... */ MethodReference method = DexPrinter.toMethodReference(vie.getMethodRef()); List<Register> argumentRegs = getInstanceInvokeArgumentRegs(vie); lastInvokeInstructionPosition = stmtV.getInstructionCount(); stmtV.addInsn(buildInvokeInsn("INVOKE_VIRTUAL", method, argumentRegs), origStmt); } private List<Register> getInvokeArgumentRegs(InvokeExpr ie) { constantV.setOrigStmt(origStmt); List<Register> argumentRegs = new ArrayList<Register>(); for (Value arg : ie.getArgs()) { Register currentReg = regAlloc.asImmediate(arg, constantV); argumentRegs.add(currentReg); } return argumentRegs; } private List<Register> getInstanceInvokeArgumentRegs(InstanceInvokeExpr iie) { constantV.setOrigStmt(origStmt); List<Register> argumentRegs = getInvokeArgumentRegs(iie); // always add reference to callee as first parameter (instance != // static) Local callee = (Local) iie.getBase(); Register calleeRegister = regAlloc.asLocal(callee); argumentRegs.add(0, calleeRegister); return argumentRegs; } private Register[] pad35cRegs(List<Register> realRegs) { // pad real registers to an array of five bytes, as required by the // instruction format "35c" Register[] paddedArray = new Register[5]; int nextReg = 0; for (Register realReg : realRegs) { paddedArray[nextReg] = realReg; /* * we include the second half of a wide with an empty reg for the "gap". this will be made explicit for dexlib later * on. */ if (realReg.isWide()) { nextReg++; paddedArray[nextReg] = Register.EMPTY_REGISTER; } nextReg++; } // do the real padding with empty regs for (; nextReg < 5; nextReg++) { paddedArray[nextReg] = Register.EMPTY_REGISTER; } return paddedArray; } @Override public void caseInterfaceInvokeExpr(InterfaceInvokeExpr iie) { MethodReference method = DexPrinter.toMethodReference(iie.getMethodRef()); List<Register> arguments = getInstanceInvokeArgumentRegs(iie); lastInvokeInstructionPosition = stmtV.getInstructionCount(); stmtV.addInsn(buildInvokeInsn("INVOKE_INTERFACE", method, arguments), origStmt); } @Override public void caseStaticInvokeExpr(StaticInvokeExpr sie) { MethodReference method = DexPrinter.toMethodReference(sie.getMethodRef()); List<Register> arguments = getInvokeArgumentRegs(sie); lastInvokeInstructionPosition = stmtV.getInstructionCount(); stmtV.addInsn(buildInvokeInsn("INVOKE_STATIC", method, arguments), origStmt); } private void buildCalculatingBinaryInsn(final String binaryOperation, Value firstOperand, Value secondOperand, Expr originalExpr) { constantV.setOrigStmt(origStmt); Register firstOpReg = regAlloc.asImmediate(firstOperand, constantV); // use special "/lit"-opcodes if int is the destination's type, the // second op is // an integer literal and the opc is not sub (no sub*/lit opc available) if (destinationReg.getType() instanceof IntType && secondOperand instanceof IntConstant && !binaryOperation.equals("SUB")) { int secondOpConstant = ((IntConstant) secondOperand).value; if (SootToDexUtils.fitsSigned8(secondOpConstant)) { stmtV.addInsn(buildLit8BinaryInsn(binaryOperation, firstOpReg, (byte) secondOpConstant), origStmt); return; } if (SootToDexUtils.fitsSigned16(secondOpConstant)) { if (!binaryOperation.equals("SHL") && !binaryOperation.equals("SHR") && !binaryOperation.equals("USHR")) { // no shift opc available for /lit16 stmtV.addInsn(buildLit16BinaryInsn(binaryOperation, firstOpReg, (short) secondOpConstant), origStmt); return; } } // constant is too big, so use it as second op and build normally } // Double-check that we are not carrying out any arithmetic operations // on non-primitive values if (!(secondOperand.getType() instanceof PrimType)) { throw new RuntimeException("Invalid value type for primitive operation"); } // For some data types, there are no calculating opcodes in Dalvik. In // this case, we need to use a bigger opcode and cast the result back. PrimitiveType destRegType = PrimitiveType.getByName(destinationReg.getType().toString()); Register secondOpReg = regAlloc.asImmediate(secondOperand, constantV); Register orgDestReg = destinationReg; if (isSmallerThan(destRegType, PrimitiveType.INT)) { destinationReg = regAlloc.asTmpReg(IntType.v()); } else { // If the second register is not of the precise target type, we need // to // cast. This can happen, because we cannot load BYTE values. We // instead // load INT constants and then need to typecast. if (isBiggerThan(PrimitiveType.getByName(secondOpReg.getType().toString()), destRegType)) { destinationReg = regAlloc.asTmpReg(secondOpReg.getType()); } else if (isBiggerThan(PrimitiveType.getByName(firstOpReg.getType().toString()), destRegType)) { destinationReg = regAlloc.asTmpReg(firstOpReg.getType()); } } // use special "/2addr"-opcodes if destination equals first op if (destinationReg.getNumber() == firstOpReg.getNumber()) { stmtV.addInsn(build2AddrBinaryInsn(binaryOperation, secondOpReg), origStmt); } else { // no optimized binary opcode possible stmtV.addInsn(buildNormalBinaryInsn(binaryOperation, firstOpReg, secondOpReg), origStmt); } // If we have used a temporary register, we must copy over the result if (orgDestReg != destinationReg) { Register tempReg = destinationReg.clone(); destinationReg = orgDestReg.clone(); castPrimitive(tempReg, originalExpr, destinationReg.getType()); } } private String fixIntTypeString(String typeString) { if (typeString.equals("boolean") || typeString.equals("byte") || typeString.equals("char") || typeString.equals("short")) { return "int"; } return typeString; } private Insn build2AddrBinaryInsn(final String binaryOperation, Register secondOpReg) { String localTypeString = destinationReg.getTypeString(); localTypeString = fixIntTypeString(localTypeString); Opcode opc = Opcode.valueOf(binaryOperation + "_" + localTypeString.toUpperCase() + "_2ADDR"); return new Insn12x(opc, destinationReg, secondOpReg); } private Insn buildNormalBinaryInsn(String binaryOperation, Register firstOpReg, Register secondOpReg) { String localTypeString = firstOpReg.getTypeString(); localTypeString = fixIntTypeString(localTypeString); Opcode opc = Opcode.valueOf(binaryOperation + "_" + localTypeString.toUpperCase()); return new Insn23x(opc, destinationReg, firstOpReg, secondOpReg); } private Insn buildLit16BinaryInsn(String binaryOperation, Register firstOpReg, short secondOpLieteral) { Opcode opc = Opcode.valueOf(binaryOperation + "_INT_LIT16"); return new Insn22s(opc, destinationReg, firstOpReg, secondOpLieteral); } private Insn buildLit8BinaryInsn(String binaryOperation, Register firstOpReg, byte secondOpLiteral) { Opcode opc = Opcode.valueOf(binaryOperation + "_INT_LIT8"); return new Insn22b(opc, destinationReg, firstOpReg, secondOpLiteral); } @Override public void caseAddExpr(AddExpr ae) { buildCalculatingBinaryInsn("ADD", ae.getOp1(), ae.getOp2(), ae); } @Override public void caseSubExpr(SubExpr se) { buildCalculatingBinaryInsn("SUB", se.getOp1(), se.getOp2(), se); } @Override public void caseMulExpr(MulExpr me) { buildCalculatingBinaryInsn("MUL", me.getOp1(), me.getOp2(), me); } @Override public void caseDivExpr(DivExpr de) { buildCalculatingBinaryInsn("DIV", de.getOp1(), de.getOp2(), de); } @Override public void caseRemExpr(RemExpr re) { buildCalculatingBinaryInsn("REM", re.getOp1(), re.getOp2(), re); } @Override public void caseAndExpr(AndExpr ae) { buildCalculatingBinaryInsn("AND", ae.getOp1(), ae.getOp2(), ae); } @Override public void caseOrExpr(OrExpr oe) { buildCalculatingBinaryInsn("OR", oe.getOp1(), oe.getOp2(), oe); } @Override public void caseXorExpr(XorExpr xe) { Value firstOperand = xe.getOp1(); Value secondOperand = xe.getOp2(); constantV.setOrigStmt(origStmt); // see for unary ones-complement shortcut, may be a result of Dexpler's // conversion if (secondOperand.equals(IntConstant.v(-1)) || secondOperand.equals(LongConstant.v(-1))) { PrimitiveType destRegType = PrimitiveType.getByName(destinationReg.getType().toString()); Register orgDestReg = destinationReg; // We may need a temporary register if we need a typecast if (isBiggerThan(PrimitiveType.getByName(secondOperand.getType().toString()), destRegType)) { destinationReg = regAlloc.asTmpReg(IntType.v()); } if (secondOperand.equals(IntConstant.v(-1))) { Register sourceReg = regAlloc.asImmediate(firstOperand, constantV); stmtV.addInsn(new Insn12x(Opcode.NOT_INT, destinationReg, sourceReg), origStmt); } else if (secondOperand.equals(LongConstant.v(-1))) { Register sourceReg = regAlloc.asImmediate(firstOperand, constantV); stmtV.addInsn(new Insn12x(Opcode.NOT_LONG, destinationReg, sourceReg), origStmt); } // If we have used a temporary register, we must copy over the // result if (orgDestReg != destinationReg) { Register tempReg = destinationReg.clone(); destinationReg = orgDestReg.clone(); castPrimitive(tempReg, secondOperand, destinationReg.getType()); } } else { // No shortcut, create normal binary operation buildCalculatingBinaryInsn("XOR", firstOperand, secondOperand, xe); } } @Override public void caseShlExpr(ShlExpr sle) { buildCalculatingBinaryInsn("SHL", sle.getOp1(), sle.getOp2(), sle); } @Override public void caseShrExpr(ShrExpr sre) { buildCalculatingBinaryInsn("SHR", sre.getOp1(), sre.getOp2(), sre); } @Override public void caseUshrExpr(UshrExpr usre) { buildCalculatingBinaryInsn("USHR", usre.getOp1(), usre.getOp2(), usre); } private Insn buildComparingBinaryInsn(String binaryOperation, Value firstOperand, Value secondOperand) { constantV.setOrigStmt(origStmt); Value realFirstOperand = fixNullConstant(firstOperand); Value realSecondOperand = fixNullConstant(secondOperand); Register firstOpReg = regAlloc.asImmediate(realFirstOperand, constantV); // select fitting opcode ("if" or "if-zero") InsnWithOffset comparingBinaryInsn; String opcodeName = "IF_" + binaryOperation; boolean secondOpIsInt = realSecondOperand instanceof IntConstant; boolean secondOpIsZero = secondOpIsInt && ((IntConstant) realSecondOperand).value == 0; if (secondOpIsZero) { Opcode opc = Opcode.valueOf(opcodeName.concat("Z")); comparingBinaryInsn = new Insn21t(opc, firstOpReg); comparingBinaryInsn.setTarget(targetForOffset); } else { Opcode opc = Opcode.valueOf(opcodeName); Register secondOpReg = regAlloc.asImmediate(realSecondOperand, constantV); comparingBinaryInsn = new Insn22t(opc, firstOpReg, secondOpReg); comparingBinaryInsn.setTarget(targetForOffset); } return comparingBinaryInsn; } private Value fixNullConstant(Value potentialNullConstant) { /* * The bytecode spec says: "In terms of bitwise representation, (Object) null == (int) 0." So use an IntConstant(0) for * null comparison in if-*z opcodes. */ if (potentialNullConstant instanceof NullConstant) { return IntConstant.v(0); } return potentialNullConstant; } @Override public void caseEqExpr(EqExpr ee) { stmtV.addInsn(buildComparingBinaryInsn("EQ", ee.getOp1(), ee.getOp2()), origStmt); } @Override public void caseGeExpr(GeExpr ge) { stmtV.addInsn(buildComparingBinaryInsn("GE", ge.getOp1(), ge.getOp2()), origStmt); } @Override public void caseGtExpr(GtExpr ge) { stmtV.addInsn(buildComparingBinaryInsn("GT", ge.getOp1(), ge.getOp2()), origStmt); } @Override public void caseLeExpr(LeExpr le) { stmtV.addInsn(buildComparingBinaryInsn("LE", le.getOp1(), le.getOp2()), origStmt); } @Override public void caseLtExpr(LtExpr le) { stmtV.addInsn(buildComparingBinaryInsn("LT", le.getOp1(), le.getOp2()), origStmt); } @Override public void caseNeExpr(NeExpr ne) { stmtV.addInsn(buildComparingBinaryInsn("NE", ne.getOp1(), ne.getOp2()), origStmt); } @Override public void caseCmpExpr(CmpExpr v) { stmtV.addInsn(buildCmpInsn("CMP_LONG", v.getOp1(), v.getOp2()), origStmt); } @Override public void caseCmpgExpr(CmpgExpr v) { stmtV.addInsn(buildCmpInsn("CMPG", v.getOp1(), v.getOp2()), origStmt); } @Override public void caseCmplExpr(CmplExpr v) { stmtV.addInsn(buildCmpInsn("CMPL", v.getOp1(), v.getOp2()), origStmt); } private Insn buildCmpInsn(String opcodePrefix, Value firstOperand, Value secondOperand) { constantV.setOrigStmt(origStmt); Register firstReg = regAlloc.asImmediate(firstOperand, constantV); Register secondReg = regAlloc.asImmediate(secondOperand, constantV); // select fitting opcode according to the prefix and the type of the // operands Opcode opc = null; // we assume that the type of the operands are equal and use only the // first one if (opcodePrefix.equals("CMP_LONG")) { opc = Opcode.CMP_LONG; } else if (firstReg.isFloat()) { opc = Opcode.valueOf(opcodePrefix + "_FLOAT"); } else if (firstReg.isDouble()) { opc = Opcode.valueOf(opcodePrefix + "_DOUBLE"); } else { throw new RuntimeException("unsupported type of operands for cmp* opcode: " + firstOperand.getType()); } return new Insn23x(opc, destinationReg, firstReg, secondReg); } @Override public void caseLengthExpr(LengthExpr le) { Value array = le.getOp(); constantV.setOrigStmt(origStmt); // In buggy code, the parameter could be a NullConstant. // This is why we use .asImmediate() and not .asLocal() Register arrayReg = regAlloc.asImmediate(array, constantV); stmtV.addInsn(new Insn12x(Opcode.ARRAY_LENGTH, destinationReg, arrayReg), origStmt); } @Override public void caseNegExpr(NegExpr ne) { Value source = ne.getOp(); constantV.setOrigStmt(origStmt); Register sourceReg = regAlloc.asImmediate(source, constantV); Opcode opc; Type type = source.getType(); if (type instanceof IntegerType) { opc = Opcode.NEG_INT; } else if (type instanceof FloatType) { opc = Opcode.NEG_FLOAT; } else if (type instanceof DoubleType) { opc = Opcode.NEG_DOUBLE; } else if (type instanceof LongType) { opc = Opcode.NEG_LONG; } else { throw new RuntimeException("unsupported value type for neg-* opcode: " + type); } stmtV.addInsn(new Insn12x(opc, destinationReg, sourceReg), origStmt); } @Override public void caseInstanceOfExpr(InstanceOfExpr ioe) { final Value referenceToCheck = ioe.getOp(); // There are some strange apps that use constants here constantV.setOrigStmt(origStmt); Register referenceToCheckReg = regAlloc.asImmediate(referenceToCheck, constantV); TypeReference checkType = DexPrinter.toTypeReference(ioe.getCheckType()); stmtV.addInsn(new Insn22c(Opcode.INSTANCE_OF, destinationReg, referenceToCheckReg, checkType), origStmt); } @Override public void caseCastExpr(CastExpr ce) { Type castType = ce.getCastType(); Value source = ce.getOp(); constantV.setOrigStmt(origStmt); Register sourceReg = regAlloc.asImmediate(source, constantV); if (SootToDexUtils.isObject(castType)) { castObject(sourceReg, castType); } else { castPrimitive(sourceReg, source, castType); } } protected void castObject(Register sourceReg, Type castType) { /* * No real "cast" is done: move the object to a tmp reg, check the cast with check-cast and finally move to the "cast" * object location. This way a) the old reg is not touched by check-cast, and b) the new reg does change its type only * after a successful check-cast. * * a) is relevant e.g. for "r1 = (String) r0" if r0 contains null, since the internal type of r0 would change from Null * to String after the check-cast opcode, which alerts the verifier in future uses of r0 although nothing should change * during execution. * * b) is relevant for exceptional control flow: if we move to the new reg and do the check-cast there, an exception * between the end of the move's execution and the end of the check-cast execution leaves the new reg with the type of * the old reg. */ TypeReference castTypeItem = DexPrinter.toTypeReference(castType); if (sourceReg.getNumber() == destinationReg.getNumber()) { // simplyfied case if reg numbers do not differ stmtV.addInsn(new Insn21c(Opcode.CHECK_CAST, destinationReg, castTypeItem), origStmt); } else { // move to tmp reg, check cast, move to destination Register tmp = regAlloc.asTmpReg(sourceReg.getType()); stmtV.addInsn(StmtVisitor.buildMoveInsn(tmp, sourceReg), origStmt); stmtV.addInsn(new Insn21c(Opcode.CHECK_CAST, tmp.clone(), castTypeItem), origStmt); stmtV.addInsn(StmtVisitor.buildMoveInsn(destinationReg, tmp.clone()), origStmt); } } private void castPrimitive(Register sourceReg, Value source, Type castSootType) { PrimitiveType castType = PrimitiveType.getByName(castSootType.toString()); // Fix null_types on the fly. This should not be necessary, but better // be safe // than sorry and it's easy to fix it here. if (castType == PrimitiveType.INT && source.getType() instanceof NullType) { source = IntConstant.v(0); } // select fitting conversion opcode, depending on the source and cast // type Type srcType = source.getType(); if (srcType instanceof RefType) { throw new RuntimeException("Trying to cast reference type " + srcType + " to a primitive"); } PrimitiveType sourceType = PrimitiveType.getByName(srcType.toString()); if (castType == PrimitiveType.BOOLEAN) { // there is no "-to-boolean" opcode, so just pretend to move an int // to an int castType = PrimitiveType.INT; sourceType = PrimitiveType.INT; } if (shouldCastFromInt(sourceType, castType)) { // pretend to cast from int since that is OK sourceType = PrimitiveType.INT; Opcode opc = getCastOpc(sourceType, castType); stmtV.addInsn(new Insn12x(opc, destinationReg, sourceReg), origStmt); } else if (isMoveCompatible(sourceType, castType)) { /* * no actual cast needed, just move the reg content if regs differ */ if (destinationReg.getNumber() != sourceReg.getNumber()) { stmtV.addInsn(StmtVisitor.buildMoveInsn(destinationReg, sourceReg), origStmt); } // Make sure that we have at least some statement in case we need // one for jumps else if (!origStmt.getBoxesPointingToThis().isEmpty()) { stmtV.addInsn(new Insn10x(Opcode.NOP), origStmt); } } else if (needsCastThroughInt(sourceType, castType)) { /* * an unsupported "dest = (cast) src" is broken down to "tmp = (int) src" and "dest = (cast) tmp", using a tmp reg to * not mess with the original reg types */ Opcode castToIntOpc = getCastOpc(sourceType, PrimitiveType.INT); Opcode castFromIntOpc = getCastOpc(PrimitiveType.INT, castType); Register tmp = regAlloc.asTmpReg(IntType.v()); stmtV.addInsn(new Insn12x(castToIntOpc, tmp, sourceReg), origStmt); stmtV.addInsn(new Insn12x(castFromIntOpc, destinationReg, tmp.clone()), origStmt); } else { // the leftover simple cases, where we just cast as stated Opcode opc = getCastOpc(sourceType, castType); stmtV.addInsn(new Insn12x(opc, destinationReg, sourceReg), origStmt); } } private boolean needsCastThroughInt(PrimitiveType sourceType, PrimitiveType castType) { // source >= long && cast < int -> too far away to cast directly return isEqualOrBigger(sourceType, PrimitiveType.LONG) && !isEqualOrBigger(castType, PrimitiveType.INT); } private boolean isMoveCompatible(PrimitiveType sourceType, PrimitiveType castType) { if (sourceType == castType) { // at this point, the types are "bigger" or equal to int, so no // "should cast from int" is needed return true; } if (castType == PrimitiveType.INT && !isBiggerThan(sourceType, PrimitiveType.INT)) { // there is no "upgrade" cast from "smaller than int" to int, so // move it return true; } return false; } private boolean shouldCastFromInt(PrimitiveType sourceType, PrimitiveType castType) { if (isEqualOrBigger(sourceType, PrimitiveType.INT)) { // source is already "big" enough return false; } if (castType == PrimitiveType.INT) { // would lead to an int-to-int cast, so leave it as it is return false; } return true; } private boolean isEqualOrBigger(PrimitiveType type, PrimitiveType relativeTo) { return type.compareTo(relativeTo) >= 0; } private boolean isBiggerThan(PrimitiveType type, PrimitiveType relativeTo) { return type.compareTo(relativeTo) > 0; } private boolean isSmallerThan(PrimitiveType type, PrimitiveType relativeTo) { return type.compareTo(relativeTo) < 0; } private Opcode getCastOpc(PrimitiveType sourceType, PrimitiveType castType) { Opcode opc = Opcode.valueOf(sourceType.getName().toUpperCase() + "_TO_" + castType.getName().toUpperCase()); if (opc == null) { throw new RuntimeException("unsupported cast from " + sourceType + " to " + castType); } return opc; } @Override public void caseNewArrayExpr(NewArrayExpr nae) { Value size = nae.getSize(); constantV.setOrigStmt(origStmt); Register sizeReg = regAlloc.asImmediate(size, constantV); // Create the array type Type baseType = nae.getBaseType(); int numDimensions = 1; while (baseType instanceof ArrayType) { ArrayType at = (ArrayType) baseType; baseType = at.getElementType(); numDimensions++; } ArrayType arrayType = ArrayType.v(baseType, numDimensions); TypeReference arrayTypeItem = DexPrinter.toTypeReference(arrayType); stmtV.addInsn(new Insn22c(Opcode.NEW_ARRAY, destinationReg, sizeReg, arrayTypeItem), origStmt); } @Override public void caseNewMultiArrayExpr(NewMultiArrayExpr nmae) { constantV.setOrigStmt(origStmt); // get array dimensions if (nmae.getSizeCount() > 255) { throw new RuntimeException( "number of dimensions is too high (> 255) for the filled-new-array* opcodes: " + nmae.getSizeCount()); } short dimensions = (short) nmae.getSizeCount(); // get array base type ArrayType arrayType = ArrayType.v(nmae.getBaseType().baseType, dimensions); TypeReference arrayTypeItem = DexPrinter.toTypeReference(arrayType); // get the dimension size registers List<Register> dimensionSizeRegs = new ArrayList<Register>(); for (int i = 0; i < dimensions; i++) { Value currentDimensionSize = nmae.getSize(i); Register currentReg = regAlloc.asImmediate(currentDimensionSize, constantV); dimensionSizeRegs.add(currentReg); } // create filled-new-array instruction, depending on the dimension sizes if (dimensions <= 5) { Register[] paddedRegs = pad35cRegs(dimensionSizeRegs); stmtV.addInsn(new Insn35c(Opcode.FILLED_NEW_ARRAY, dimensions, paddedRegs[0], paddedRegs[1], paddedRegs[2], paddedRegs[3], paddedRegs[4], arrayTypeItem), null); } else { stmtV.addInsn(new Insn3rc(Opcode.FILLED_NEW_ARRAY_RANGE, dimensionSizeRegs, dimensions, arrayTypeItem), null); } // check for > 255 is done already // move the resulting array into the destination register stmtV.addInsn(new Insn11x(Opcode.MOVE_RESULT_OBJECT, destinationReg), origStmt); } @Override public void caseNewExpr(NewExpr ne) { TypeReference baseType = DexPrinter.toTypeReference(ne.getBaseType()); stmtV.addInsn(new Insn21c(Opcode.NEW_INSTANCE, destinationReg, baseType), origStmt); } public int getLastInvokeInstructionPosition() { return lastInvokeInstructionPosition; } }
32,458
37.687723
125
java
soot
soot-master/src/main/java/soot/toDex/FastDexTrapTightener.java
package soot.toDex; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.Singletons; import soot.Trap; import soot.Unit; import soot.jimple.IdentityStmt; import soot.jimple.ParameterRef; import soot.jimple.ThisRef; /** * Tries may not start or end at units which have no corresponding Dalvik instructions such as IdentityStmts. We reduce the * traps to start at the first "real" instruction. We could also use a TrapTigthener, but that would be too expensive for * just producing working Dex code. * * @author Steven Arzt */ public class FastDexTrapTightener extends BodyTransformer { public FastDexTrapTightener(Singletons.Global g) { } public static FastDexTrapTightener v() { return soot.G.v().soot_toDex_FastDexTrapTightener(); } @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { for (Iterator<Trap> trapIt = b.getTraps().snapshotIterator(); trapIt.hasNext();) { Trap t = trapIt.next(); Unit beginUnit; while (!isDexInstruction(beginUnit = t.getBeginUnit()) && t.getBeginUnit() != t.getEndUnit()) { t.setBeginUnit(b.getUnits().getSuccOf(beginUnit)); } // If the trap is empty, we remove it if (t.getBeginUnit() == t.getEndUnit()) { trapIt.remove(); } } } private boolean isDexInstruction(Unit unit) { if (unit instanceof IdentityStmt) { IdentityStmt is = (IdentityStmt) unit; return !(is.getRightOp() instanceof ThisRef || is.getRightOp() instanceof ParameterRef); } return true; } }
2,439
29.886076
123
java
soot
soot-master/src/main/java/soot/toDex/LabelAssigner.java
package soot.toDex; /*- * #%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.Collection; import java.util.HashMap; import java.util.Map; import org.jf.dexlib2.builder.Label; import org.jf.dexlib2.builder.MethodImplementationBuilder; import soot.jimple.Stmt; import soot.toDex.instructions.AbstractPayload; import soot.toDex.instructions.SwitchPayload; public class LabelAssigner { private final MethodImplementationBuilder builder; private int lastLabelId = 0; private Map<Stmt, Label> stmtToLabel = new HashMap<>(); private Map<Stmt, String> stmtToLabelName = new HashMap<>(); private Map<AbstractPayload, Label> payloadToLabel = new HashMap<>(); private Map<AbstractPayload, String> payloadToLabelName = new HashMap<>(); public LabelAssigner(MethodImplementationBuilder builder) { this.builder = builder; } public Label getOrCreateLabel(Stmt stmt) { if (stmt == null) { throw new RuntimeException("Cannot create label for NULL statement"); } Label lbl = stmtToLabel.get(stmt); if (lbl == null) { String labelName = "l" + lastLabelId++; lbl = builder.getLabel(labelName); stmtToLabel.put(stmt, lbl); stmtToLabelName.put(stmt, labelName); } return lbl; } public Label getOrCreateLabel(AbstractPayload payload) { if (payload == null) { throw new RuntimeException("Cannot create label for NULL payload"); } Label lbl = payloadToLabel.get(payload); if (lbl == null) { String labelName = "l" + lastLabelId++; lbl = builder.getLabel(labelName); payloadToLabel.put(payload, lbl); payloadToLabelName.put(payload, labelName); } return lbl; } public Label getLabel(Stmt stmt) { Label lbl = getLabelUnsafe(stmt); if (lbl == null) { throw new RuntimeException("Statement has no label: " + stmt); } return lbl; } public Label getLabelUnsafe(Stmt stmt) { return stmtToLabel.get(stmt); } public Label getLabel(SwitchPayload payload) { Label lbl = payloadToLabel.get(payload); if (lbl == null) { throw new RuntimeException("Switch payload has no label: " + payload); } return lbl; } public String getLabelName(Stmt stmt) { return stmtToLabelName.get(stmt); } public String getLabelName(AbstractPayload payload) { return payloadToLabelName.get(payload); } public Label getLabelAtAddress(int address) { for (Label lb : stmtToLabel.values()) { if (lb.isPlaced() && lb.getCodeAddress() == address) { return lb; } } return null; } public Collection<Label> getAllLabels() { return stmtToLabel.values(); } }
3,441
26.758065
76
java
soot
soot-master/src/main/java/soot/toDex/LocalRegisterAssignmentInformation.java
package soot.toDex; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Local; /** * Contains information about which register maps to which local */ public class LocalRegisterAssignmentInformation { private Local local; private Register register; public LocalRegisterAssignmentInformation(Register register, Local local) { this.register = register; this.local = local; } public static LocalRegisterAssignmentInformation v(Register register, Local l) { return new LocalRegisterAssignmentInformation(register, l); } public Local getLocal() { return local; } public Register getRegister() { return register; } }
1,438
26.150943
82
java
soot
soot-master/src/main/java/soot/toDex/MultiDexBuilder.java
package soot.toDex; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.jf.dexlib2.Opcodes; import org.jf.dexlib2.iface.ClassDef; import org.jf.dexlib2.writer.io.FileDataStore; import org.jf.dexlib2.writer.pool.DexPool; /** * @author Manuel Benz created on 26.09.17 */ public class MultiDexBuilder { protected final Opcodes opcodes; protected final List<DexPool> dexPools = new LinkedList<>(); protected DexPool curPool; public MultiDexBuilder(Opcodes opcodes) { this.opcodes = opcodes; newDexPool(); } protected void newDexPool() { curPool = new DexPool(opcodes); dexPools.add(curPool); } public void internClass(final ClassDef clz) { curPool.mark(); curPool.internClass(clz); if (hasOverflowed()) { // reset to state before overflow occurred curPool.reset(); // we need a new dexpool newDexPool(); // re-execute on new pool since the last execution was dropped // NOTE: We do not want to call internClass recursively here, this // might end in an endless loop // if the class is to large for a single dex file! curPool.internClass(clz); // If a single class causes an overflow, we're really out of luck if (curPool.hasOverflowed()) { throw new RuntimeException("Class is bigger than a single dex file can be"); } } } protected boolean hasOverflowed() { if (!curPool.hasOverflowed()) { return false; } // We only support splitting for api versions since Lollipop (22). // Since Api 22, Art runtime is used which needs to extract all dex // files anyway. Thus, // we can pack classes arbitrarily and do not need to care about which // classes need to go together in // the same dex file. // For Dalvik (pre 22), it is important that at least the main dex file // (classes.dex) contains all needed // dependencies of the Main activity, which means that one would have to // determine necessary dependencies and // pack those explicitly in the first dex file. // (https://developer.android.com/studio/build/multidex.html, // http://www.fasteque.com/deep-dive-into-android-multidex/) if (!opcodes.isArt()) { throw new RuntimeException("Dex file overflow. Splitting not support for pre Lollipop Android (Api 22)."); } return true; } /** * Writes all built dex files to the given folder. * * @param folder * the output folder * @return File handles to all written dex files * @throws IOException * when failed to create {@link FileDataStore} */ public List<File> writeTo(String folder) throws IOException { final List<File> result = new ArrayList<>(dexPools.size()); for (DexPool dexPool : dexPools) { int count = result.size(); // name dex files: classes.dex, classes2.dex, classes3.dex, etc. File file = new File(folder, "classes" + (count == 0 ? "" : count + 1) + ".dex"); result.add(file); FileDataStore fds = new FileDataStore(file); dexPool.writeTo(fds); fds.close(); } return result; } }
4,036
31.296
112
java