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/toolkits/graph/MutableEdgeLabelledDirectedGraph.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2007 Richard L. Halpert * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Defines a DirectedGraph which is modifiable and associates a label object with every edge. Provides an interface to * add/delete nodes and edges. * * @param <N> * @param <L> */ public interface MutableEdgeLabelledDirectedGraph<N, L> extends EdgeLabelledDirectedGraph<N, L> { /** * Adds an edge to the graph between 2 nodes. If the edge is already present no change is made. * * @param from * out node for the edge. * @param to * in node for the edge. * @param label * label for the edge. */ public void addEdge(N from, N to, L label); /** * Removes an edge between 2 nodes in the graph. If the edge is not present no change is made. * * @param from * out node for the edges to remove. * @param to * in node for the edges to remove. * @param label * label for the edge to remove. */ public void removeEdge(N from, N to, L label); /** * Removes all edges between 2 nodes in the graph. If no edges are present, no change is made. * * @param from * out node for the edges to remove. * @param to * in node for the edges to remove. */ public void removeAllEdges(N from, N to); /** * Removes all edges with the given label in the graph. If no edges are present, no change is made. * * @param label * label for the edge to remove. */ public void removeAllEdges(L label); /** * Adds a node to the graph. Initially the added node has no successors or predecessors. ; as a consequence it is * considered both a head and tail for the graph. * * @param node * a node to add to the graph. * * @see #getHeads * @see #getTails */ public void addNode(N node); /** * Removes a node from the graph. If the node is not found in the graph, no change is made. * * @param node * the node to be removed. */ public void removeNode(N node); }
2,823
28.416667
118
java
soot
soot-master/src/main/java/soot/toolkits/graph/Orderer.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2006 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.List; /** * An orderer builds an order on a directed, not necessarily acyclic, graph. * * @author Eric Bodden */ public interface Orderer<N> { /** * Builds an order for a directed graph. The order is represented by the returned list, i.e. is a node was assigned number * <i>i</i> in the order, it will be in the <i>i</i>th position of the returned list. * * @param g * a DirectedGraph instance whose nodes we wish to order * @param reverse * <code>true</code> to compute the reverse order * @return a somehow ordered list of the graph's nodes */ public abstract List<N> newList(DirectedGraph<N> g, boolean reverse); }
1,517
31.297872
124
java
soot
soot-master/src/main/java/soot/toolkits/graph/PostDominatorAnalysis.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.List; import soot.Unit; import soot.jimple.Stmt; import soot.toolkits.scalar.ArraySparseSet; import soot.toolkits.scalar.BackwardFlowAnalysis; import soot.toolkits.scalar.FlowSet; // STEP 1: What are we computing? // SETS OF Units that are post-dominators => Use ArraySparseSet. // // STEP 2: Precisely define what we are computing. // For each statement compute the set of stmts that post-dominate it // // STEP 3: Decide whether it is a backwards or forwards analysis. // FORWARDS // // /** * @deprecated use {@link MHGPostDominatorsFinder} instead */ @Deprecated public class PostDominatorAnalysis extends BackwardFlowAnalysis<Unit, FlowSet<Unit>> { private UnitGraph g; private FlowSet<Unit> allNodes; public PostDominatorAnalysis(UnitGraph g) { super(g); this.g = g; initAllNodes(); doAnalysis(); } private void initAllNodes() { allNodes = new ArraySparseSet<Unit>(); Iterator<Unit> it = g.iterator(); while (it.hasNext()) { allNodes.add(it.next()); } } // STEP 4: Is the merge operator union or intersection? // INTERSECTION @Override protected void merge(FlowSet<Unit> in1, FlowSet<Unit> in2, FlowSet<Unit> out) { in1.intersection(in2, out); } @Override protected void copy(FlowSet<Unit> source, FlowSet<Unit> dest) { source.copy(dest); } // STEP 5: Define flow equations. // dom(s) = s U ( ForAll Y in pred(s): Intersection (dom(y))) // ie: dom(s) = s and whoever dominates all the predeccessors of s // @Override protected void flowThrough(FlowSet<Unit> in, Unit s, FlowSet<Unit> out) { if (isUnitEndNode(s)) { // System.out.println("s: "+s+" is end node"); out.clear(); out.add(s); // System.out.println("in: "+in+" out: "+out); } else { // System.out.println("s: "+s+" is not start node"); // FlowSet domsOfSuccs = (FlowSet) allNodes.clone(); // for each pred of s Iterator<Unit> succsIt = g.getSuccsOf(s).iterator(); while (succsIt.hasNext()) { Unit succ = succsIt.next(); // get the unitToBeforeFlow and find the intersection // System.out.println("succ: "+succ); FlowSet<Unit> next = getFlowBefore(succ); // System.out.println("next: "+next); // System.out.println("in before intersect: "+in); in.intersection(next, in); // System.out.println("in after intersect: "+in); } // intersected with in // System.out.println("out init: "+out); out.intersection(in, out); out.add(s); // System.out.println("out after: "+out); } } private boolean isUnitEndNode(Unit s) { // System.out.println("head: "+g.getHeads().get(0)); if (g.getTails().contains(s)) { return true; } return false; } // STEP 6: Determine value for start/end node, and // initial approximation. // dom(startNode) = startNode // dom(node) = allNodes // @Override protected FlowSet<Unit> entryInitialFlow() { FlowSet<Unit> fs = new ArraySparseSet<Unit>(); List<Unit> tails = g.getTails(); // if (tails.size() != 1) { // throw new RuntimeException("Expect one end node only."); // } fs.add(tails.get(0)); return fs; } @Override protected FlowSet<Unit> newInitialFlow() { return allNodes.clone(); } /** * Returns true if s post-dominates t. */ public boolean postDominates(Stmt s, Stmt t) { return getFlowBefore(t).contains(s); } }
4,353
26.043478
86
java
soot
soot-master/src/main/java/soot/toolkits/graph/PseudoTopologicalOrderer.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai, Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Arrays; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; /** * Orders in pseudo-topological order, the nodes of a DirectedGraph instance. * * @author Steven Lambeth * @author Marc Berndl */ public class PseudoTopologicalOrderer<N> implements Orderer<N> { public static final boolean REVERSE = true; private static class ReverseOrderBuilder<N> { private final DirectedGraph<N> graph; private final int graphSize; private final int[] indexStack; private final N[] stmtStack; private final Set<N> visited; private final N[] order; private int orderLength; /** * @param g * a DirectedGraph instance we want to order the nodes for. */ public ReverseOrderBuilder(DirectedGraph<N> g) { this.graph = g; final int n = g.size(); this.graphSize = n; this.visited = Collections.newSetFromMap(new IdentityHashMap<N, Boolean>(n * 2 + 1)); this.indexStack = new int[n]; @SuppressWarnings("unchecked") N[] tempStmtStack = (N[]) new Object[n]; this.stmtStack = tempStmtStack; @SuppressWarnings("unchecked") N[] tempOrder = (N[]) new Object[n]; this.order = tempOrder; this.orderLength = 0; } /** * Orders in pseudo-topological order. * * @param reverse * specify if we want reverse pseudo-topological ordering, or not. * @return an ordered list of the graph's nodes. */ public List<N> computeOrder(boolean reverse) { // Visit each node for (N s : graph) { if (visited.add(s)) { visitNode(s); } if (orderLength == graphSize) { break; } } if (reverse) { reverseArray(order); } return Arrays.asList(order); } // Unfortunately, the nice recursive solution fails // because of stack overflows // Fill in the 'order' list with a pseudo topological order // list of statements starting at s. Simulates recursion with a stack. private void visitNode(N startStmt) { int last = 0; stmtStack[last] = startStmt; indexStack[last++] = -1; while (last > 0) { int toVisitIndex = ++indexStack[last - 1]; N toVisitNode = stmtStack[last - 1]; List<N> succs = graph.getSuccsOf(toVisitNode); if (toVisitIndex >= succs.size()) { // Visit this node now that we ran out of children order[orderLength++] = toVisitNode; last--; } else { N childNode = succs.get(toVisitIndex); if (visited.add(childNode)) { stmtStack[last] = childNode; indexStack[last++] = -1; } } } } /** * Reverses the order of the elements in the specified array. * * @param array */ private static <T> void reverseArray(T[] array) { final int max = array.length >> 1; for (int i = 0, j = array.length - 1; i < max; i++, j--) { T temp = array[i]; array[i] = array[j]; array[j] = temp; } } } private boolean mIsReversed = false; public PseudoTopologicalOrderer() { } /** * {@inheritDoc} */ @Override public List<N> newList(DirectedGraph<N> g, boolean reverse) { this.mIsReversed = reverse; return (new ReverseOrderBuilder<N>(g)).computeOrder(!reverse); } // deprecated methods and constructors follow /** * @deprecated use {@link #PseudoTopologicalOrderer()} instead */ @Deprecated public PseudoTopologicalOrderer(boolean isReversed) { this.mIsReversed = isReversed; } /** * @param g * a DirectedGraph instance whose nodes we wish to order. * @return a pseudo-topologically ordered list of the graph's nodes. * @deprecated use {@link #newList(DirectedGraph, boolean))} instead */ @Deprecated public List<N> newList(DirectedGraph<N> g) { return (new ReverseOrderBuilder<N>(g)).computeOrder(!mIsReversed); } /** * Set the ordering for the orderer. * * @param isReversed * specify if we want reverse pseudo-topological ordering, or not. * @deprecated use {@link #newList(DirectedGraph, boolean))} instead */ @Deprecated public void setReverseOrder(boolean isReversed) { mIsReversed = isReversed; } /** * Check the ordering for the orderer. * * @return true if we have reverse pseudo-topological ordering, false otherwise. * @deprecated use {@link #newList(DirectedGraph, boolean))} instead */ @Deprecated public boolean isReverseOrder() { return mIsReversed; } }
5,541
27.13198
91
java
soot
soot-master/src/main/java/soot/toolkits/graph/ReversePseudoTopologicalOrderer.java
package soot.toolkits.graph; /*- * #%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% */ /** * Convenience class which returns a PseudoTopologicalOrderer with the mReversed flag set by default. * * @deprecated use {@link PseudoTopologicalOrderer#newList(DirectedGraph, boolean)} instead */ @Deprecated public class ReversePseudoTopologicalOrderer<N> extends PseudoTopologicalOrderer<N> { /** * Constructs a PseudoTopologicalOrderer with the mReversed flag set. * * @deprecated use {@link PseudoTopologicalOrderer#newList(DirectedGraph, boolean)} instead */ public ReversePseudoTopologicalOrderer() { super(); setReverseOrder(true); } }
1,416
32.738095
101
java
soot
soot-master/src/main/java/soot/toolkits/graph/ReversibleGraph.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 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% */ /** * DirectedGraph which can be reversed and re-reversed. * * @author Navindra Umanee * * @param <N> **/ public interface ReversibleGraph<N> extends MutableDirectedGraph<N> { /** * Returns true if the graph is now reversed from its original state at creation. **/ public boolean isReversed(); /** * Reverse the edges of the current graph and swap head and tail nodes. Returns self. **/ public ReversibleGraph<N> reverse(); }
1,308
29.44186
87
java
soot
soot-master/src/main/java/soot/toolkits/graph/SimpleDominatorsFinder.java
package soot.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.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.toolkits.scalar.ArrayPackedSet; import soot.toolkits.scalar.BoundedFlowSet; import soot.toolkits.scalar.CollectionFlowUniverse; import soot.toolkits.scalar.FlowSet; import soot.toolkits.scalar.ForwardFlowAnalysis; /** * Wrapper class for a simple dominators analysis based on a simple flow analysis algorithm. Works with any DirectedGraph * with a single head. * * @author Navindra Umanee **/ public class SimpleDominatorsFinder<N> implements DominatorsFinder<N> { private static final Logger logger = LoggerFactory.getLogger(SimpleDominatorsFinder.class); protected final DirectedGraph<N> graph; protected final Map<N, FlowSet<N>> nodeToDominators; /** * Compute dominators for provided singled-headed directed graph. **/ public SimpleDominatorsFinder(DirectedGraph<N> graph) { // if(Options.v().verbose()) // logger.debug("[" + graph.getBody().getMethod().getName() + // "] Finding Dominators..."); this.graph = graph; this.nodeToDominators = new HashMap<N, FlowSet<N>>(graph.size() * 2 + 1, 0.7f); // build node to dominators map SimpleDominatorsAnalysis<N> analysis = new SimpleDominatorsAnalysis<N>(graph); for (N node : graph) { this.nodeToDominators.put(node, analysis.getFlowAfter(node)); } } @Override public DirectedGraph<N> getGraph() { return graph; } @Override public List<N> getDominators(N node) { // non-backed list since FlowSet is an ArrayPackedFlowSet return nodeToDominators.get(node).toList(); } @Override public N getImmediateDominator(N node) { // root node if (getGraph().getHeads().contains(node)) { return null; } // avoid the creation of temp-lists FlowSet<N> head = nodeToDominators.get(node).clone(); head.remove(node); for (N dominator : head) { if (nodeToDominators.get(dominator).isSubSet(head)) { return dominator; } } return null; } @Override public boolean isDominatedBy(N node, N dominator) { // avoid the creation of temp-lists return nodeToDominators.get(node).contains(dominator); } @Override public boolean isDominatedByAll(N node, Collection<N> dominators) { FlowSet<N> f = nodeToDominators.get(node); for (N n : dominators) { if (!f.contains(n)) { return false; } } return true; } } /** * Calculate dominators for basic blocks. * <p> * Uses the algorithm contained in Dragon book, pg. 670-1. * * <pre> * D(n0) := { n0 } * for n in N - { n0 } do D(n) := N; * while changes to any D(n) occur do * for n in N - {n0} do * D(n) := {n} U (intersect of D(p) over all predecessors p of n) * </pre> **/ class SimpleDominatorsAnalysis<N> extends ForwardFlowAnalysis<N, FlowSet<N>> { private final BoundedFlowSet<N> emptySet; private final BoundedFlowSet<N> fullSet; SimpleDominatorsAnalysis(DirectedGraph<N> graph) { super(graph); // define empty set, with proper universe for complementation List<N> nodes = new ArrayList<N>(graph.size()); for (N n : graph) { nodes.add(n); } this.emptySet = new ArrayPackedSet<N>(new CollectionFlowUniverse<N>(nodes)); this.fullSet = (BoundedFlowSet<N>) emptySet.clone(); this.fullSet.complement(); doAnalysis(); } /** * All OUTs are initialized to the full set of definitions OUT(Start) is tweaked in customizeInitialFlowGraph. **/ @Override protected FlowSet<N> newInitialFlow() { return fullSet.clone(); } /** * OUT(Start) contains all head nodes at initialization time. **/ @Override protected FlowSet<N> entryInitialFlow() { FlowSet<N> initSet = emptySet.clone(); for (N h : graph.getHeads()) { initSet.add(h); } return initSet; } /** * We compute out straightforwardly. **/ @Override protected void flowThrough(FlowSet<N> in, N block, FlowSet<N> out) { // Perform generation in.copy(out); out.add(block); } /** * All paths == Intersection. **/ @Override protected void merge(FlowSet<N> in1, FlowSet<N> in2, FlowSet<N> out) { in1.intersection(in2, out); } @Override protected void mergeInto(N block, FlowSet<N> inout, FlowSet<N> in) { inout.intersection(in); } @Override protected void copy(FlowSet<N> source, FlowSet<N> dest) { source.copy(dest); } }
5,432
26.165
121
java
soot
soot-master/src/main/java/soot/toolkits/graph/SlowPseudoTopologicalOrderer.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai, Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import soot.G; import soot.Singletons; /** * Provide the pseudo topological order of a graph's nodes. It has same functionality as PseudoTopologicalOrderer; however, * this class considers the order of successors. It runs slower but more precise. Currently it was only used by * ArrayBoundsCheckerAnalysis to reduce the iteration numbers. * * @see: PseudoTopologicalOrderer */ public class SlowPseudoTopologicalOrderer<N> implements Orderer<N> { public SlowPseudoTopologicalOrderer(Singletons.Global g) { } public static SlowPseudoTopologicalOrderer v() { return G.v().soot_toolkits_graph_SlowPseudoTopologicalOrderer(); } private static abstract class AbstractOrderBuilder<N> { protected static enum Color { WHITE, GRAY, BLACK }; protected final Map<N, Color> stmtToColor = new HashMap<N, Color>(); protected final LinkedList<N> order = new LinkedList<N>(); protected final DirectedGraph<N> graph; protected final boolean reverse; protected AbstractOrderBuilder(DirectedGraph<N> g, boolean reverse) { this.graph = g; this.reverse = reverse; } protected abstract void visitNode(N startStmt); /** * Orders in pseudo-topological order. * * @return an ordered list of the graph's nodes. */ public LinkedList<N> computeOrder() { // Color all nodes white for (N s : graph) { stmtToColor.put(s, Color.WHITE); } // Visit each node for (N s : graph) { if (stmtToColor.get(s) == Color.WHITE) { visitNode(s); } } return order; } } private static class ForwardOrderBuilder<N> extends AbstractOrderBuilder<N> { private final HashMap<N, List<N>> succsMap = new HashMap<N, List<N>>(); private List<N> reverseOrder; /** * @param graph * a DirectedGraph instance we want to order the nodes for. */ public ForwardOrderBuilder(DirectedGraph<N> graph, boolean reverse) { super(graph, reverse); } /** * Orders in pseudo-topological order. * * @return an ordered list of the graph's nodes. */ public LinkedList<N> computeOrder() { reverseOrder = (new ReverseOrderBuilder<N>(graph)).computeOrder(); return super.computeOrder(); } // Unfortunately, the nice recursive solution fails because of stack // overflows. Fill in the 'order' list with a pseudo topological order // (possibly reversed) list of statements starting at s. // Simulates recursion with a stack. @Override protected void visitNode(N startStmt) { LinkedList<N> stmtStack = new LinkedList<N>(); LinkedList<Integer> indexStack = new LinkedList<Integer>(); stmtToColor.put(startStmt, Color.GRAY); stmtStack.addLast(startStmt); indexStack.addLast(-1); while (!stmtStack.isEmpty()) { int toVisitIndex = indexStack.removeLast(); N toVisitNode = stmtStack.getLast(); toVisitIndex++; indexStack.addLast(toVisitIndex); if (toVisitIndex >= graph.getSuccsOf(toVisitNode).size()) { // Visit this node now that we ran out of children if (reverse) { order.addLast(toVisitNode); } else { order.addFirst(toVisitNode); } stmtToColor.put(toVisitNode, Color.BLACK); // Pop this node off stmtStack.removeLast(); indexStack.removeLast(); } else { List<N> orderedSuccs = succsMap.get(toVisitNode); if (orderedSuccs == null) { orderedSuccs = new LinkedList<N>(); succsMap.put(toVisitNode, orderedSuccs); /* make ordered succs */ List<N> allsuccs = graph.getSuccsOf(toVisitNode); for (int i = 0; i < allsuccs.size(); i++) { N cur = allsuccs.get(i); int j = 0; for (; j < orderedSuccs.size(); j++) { N comp = orderedSuccs.get(j); if (reverseOrder.indexOf(cur) < reverseOrder.indexOf(comp)) { break; } } orderedSuccs.add(j, cur); } } N childNode = orderedSuccs.get(toVisitIndex); // Visit this child next if not already visited (or on stack) if (stmtToColor.get(childNode) == Color.WHITE) { stmtToColor.put(childNode, Color.GRAY); stmtStack.addLast(childNode); indexStack.addLast(-1); } } } } } private static class ReverseOrderBuilder<N> extends AbstractOrderBuilder<N> { /** * @param graph * a DirectedGraph instance we want to order the nodes for. */ public ReverseOrderBuilder(DirectedGraph<N> graph) { super(graph, false); } @Override protected void visitNode(N startStmt) { LinkedList<N> stmtStack = new LinkedList<N>(); LinkedList<Integer> indexStack = new LinkedList<Integer>(); stmtToColor.put(startStmt, Color.GRAY); stmtStack.addLast(startStmt); indexStack.addLast(-1); while (!stmtStack.isEmpty()) { int toVisitIndex = indexStack.removeLast(); N toVisitNode = stmtStack.getLast(); toVisitIndex++; indexStack.addLast(toVisitIndex); if (toVisitIndex >= graph.getPredsOf(toVisitNode).size()) { // Visit this node now that we ran out of children if (reverse) { order.addLast(toVisitNode); } else { order.addFirst(toVisitNode); } stmtToColor.put(toVisitNode, Color.BLACK); // Pop this node off stmtStack.removeLast(); indexStack.removeLast(); } else { N childNode = graph.getPredsOf(toVisitNode).get(toVisitIndex); // Visit this child next if not already visited (or on stack) if (stmtToColor.get(childNode) == Color.WHITE) { stmtToColor.put(childNode, Color.GRAY); stmtStack.addLast(childNode); indexStack.addLast(-1); } } } } } private boolean mIsReversed = false; public SlowPseudoTopologicalOrderer() { } /** * {@inheritDoc} */ @Override public List<N> newList(DirectedGraph<N> g, boolean reverse) { this.mIsReversed = reverse; return (new ForwardOrderBuilder<>(g, reverse)).computeOrder(); } // deprecated methods follow /** * @deprecated use {@link #SlowPseudoTopologicalOrderer()} instead */ public SlowPseudoTopologicalOrderer(boolean isReversed) { this.mIsReversed = isReversed; } /** * @param g * a DirectedGraph instance whose nodes we wish to order. * @return a pseudo-topologically ordered list of the graph's nodes. * @deprecated use {@link #newList(DirectedGraph, boolean))} instead */ @Deprecated public List<N> newList(DirectedGraph<N> g) { return (new ForwardOrderBuilder<>(g, mIsReversed)).computeOrder(); } /** * Set the ordering for the orderer. * * @param isReversed * specify if we want reverse pseudo-topological ordering, or not. * @deprecated use {@link #newList(DirectedGraph, boolean))} instead */ @Deprecated public void setReverseOrder(boolean isReversed) { mIsReversed = isReversed; } /** * Check the ordering for the orderer. * * @return true if we have reverse pseudo-topological ordering, false otherwise. * @deprecated use {@link #newList(DirectedGraph, boolean))} instead */ @Deprecated public boolean isReverseOrder() { return mIsReversed; } }
8,609
28.385666
123
java
soot
soot-master/src/main/java/soot/toolkits/graph/StronglyConnectedComponents.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam, Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.options.Options; import soot.util.StationaryArrayList; /** * Identifies and provides an interface to query the strongly-connected components of DirectedGraph instances. * * @see DirectedGraph * @deprecated implementation is inefficient; use {@link StronglyConnectedComponentsFast} instead */ @Deprecated public class StronglyConnectedComponents { private static final Logger logger = LoggerFactory.getLogger(StronglyConnectedComponents.class); private HashMap<Object, Object> nodeToColor; private static final Object Visited = new Object(); private static final Object Black = new Object(); private final LinkedList<Object> finishingOrder; private List<List> componentList = new ArrayList<List>(); private final HashMap<Object, List<Object>> nodeToComponent = new HashMap<Object, List<Object>>(); MutableDirectedGraph sccGraph = new HashMutableDirectedGraph(); private final int[] indexStack; private final Object[] nodeStack; private int last; /** * @param g * a graph for which we want to compute the strongly connected components. * @see DirectedGraph */ public StronglyConnectedComponents(DirectedGraph g) { nodeToColor = new HashMap<Object, Object>((3 * g.size()) / 2, 0.7f); indexStack = new int[g.size()]; nodeStack = new Object[g.size()]; finishingOrder = new LinkedList<Object>(); // Visit each node { Iterator nodeIt = g.iterator(); while (nodeIt.hasNext()) { Object s = nodeIt.next(); if (nodeToColor.get(s) == null) { visitNode(g, s); } } } // Re-color all nodes white nodeToColor = new HashMap<Object, Object>((3 * g.size()), 0.7f); // Visit each node via transpose edges { Iterator<Object> revNodeIt = finishingOrder.iterator(); while (revNodeIt.hasNext()) { Object s = revNodeIt.next(); if (nodeToColor.get(s) == null) { List<Object> currentComponent = null; currentComponent = new StationaryArrayList(); nodeToComponent.put(s, currentComponent); sccGraph.addNode(currentComponent); componentList.add(currentComponent); visitRevNode(g, s, currentComponent); } } } componentList = Collections.unmodifiableList(componentList); if (Options.v().verbose()) { logger.debug("Done computing scc components"); logger.debug("number of nodes in underlying graph: " + g.size()); logger.debug("number of components: " + sccGraph.size()); } } private void visitNode(DirectedGraph graph, Object startNode) { last = 0; nodeToColor.put(startNode, Visited); nodeStack[last] = startNode; indexStack[last++] = -1; while (last > 0) { int toVisitIndex = ++indexStack[last - 1]; Object toVisitNode = nodeStack[last - 1]; if (toVisitIndex >= graph.getSuccsOf(toVisitNode).size()) { // Visit this node now that we ran out of children finishingOrder.addFirst(toVisitNode); // Pop this node off last--; } else { Object childNode = graph.getSuccsOf(toVisitNode).get(toVisitIndex); // Visit this child next if not already visited (or on stack) if (nodeToColor.get(childNode) == null) { nodeToColor.put(childNode, Visited); nodeStack[last] = childNode; indexStack[last++] = -1; } } } } private void visitRevNode(DirectedGraph graph, Object startNode, List<Object> currentComponent) { last = 0; nodeToColor.put(startNode, Visited); nodeStack[last] = startNode; indexStack[last++] = -1; while (last > 0) { int toVisitIndex = ++indexStack[last - 1]; Object toVisitNode = nodeStack[last - 1]; if (toVisitIndex >= graph.getPredsOf(toVisitNode).size()) { // No more nodes. Add toVisitNode to current component. currentComponent.add(toVisitNode); nodeToComponent.put(toVisitNode, currentComponent); nodeToColor.put(toVisitNode, Black); // Pop this node off last--; } else { Object childNode = graph.getPredsOf(toVisitNode).get(toVisitIndex); // Visit this child next if not already visited (or on stack) if (nodeToColor.get(childNode) == null) { nodeToColor.put(childNode, Visited); nodeStack[last] = childNode; indexStack[last++] = -1; } else if (nodeToColor.get(childNode) == Black) { /* we may be visiting a node in another component. if so, add edge to sccGraph. */ if (nodeToComponent.get(childNode) != currentComponent) { sccGraph.addEdge(nodeToComponent.get(childNode), currentComponent); } } } } } /** * Checks if 2 nodes are in the same strongly-connnected component. * * @param a * some graph node. * @param b * some graph node * @return true if both nodes are in the same strongly-connnected component. false otherwise. */ public boolean equivalent(Object a, Object b) { return nodeToComponent.get(a) == nodeToComponent.get(b); } /** * @return a list of the strongly-connnected components that make up the computed strongly-connnect component graph. */ public List<List> getComponents() { return componentList; } /** * @param a * a node of the original graph. * @return the strongly-connnected component node to which the parameter node belongs. */ public List getComponentOf(Object a) { return nodeToComponent.get(a); } /** * @return the computed strongly-connnected component graph. * @see DirectedGraph */ public DirectedGraph getSuperGraph() { /* we should make this unmodifiable at some point. */ return sccGraph; } }
6,908
30.121622
118
java
soot
soot-master/src/main/java/soot/toolkits/graph/StronglyConnectedComponentsFast.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2008 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.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import soot.util.FastStack; /** * Identifies and provides an interface to query the strongly-connected components of DirectedGraph instances. * * Uses Tarjan's algorithm. * * @see DirectedGraph * @author Eric Bodden * * Changes: 2015/08/23 Steven Arzt, added an iterative version of Tarjan's algorithm for large graphs */ public class StronglyConnectedComponentsFast<N> { protected final List<List<N>> componentList = new ArrayList<List<N>>(); protected final List<List<N>> trueComponentList = new ArrayList<List<N>>(); protected int index = 0; protected Map<N, Integer> indexForNode, lowlinkForNode; protected FastStack<N> s; protected DirectedGraph<N> g; /** * @param g * a graph for which we want to compute the strongly connected components. * @see DirectedGraph */ public StronglyConnectedComponentsFast(DirectedGraph<N> g) { this.g = g; this.s = new FastStack<N>(); this.indexForNode = new HashMap<N, Integer>(); this.lowlinkForNode = new HashMap<N, Integer>(); for (N node : g) { if (!indexForNode.containsKey(node)) { // If the graph is too big, we cannot use a recursive algorithm // because it will blow up our stack space. The cut-off value when // to switch is more or less random, though. if (g.size() > 1000) { iterate(node); } else { recurse(node); } } } // free memory this.indexForNode = null; this.lowlinkForNode = null; this.s = null; this.g = null; } protected void recurse(N v) { int lowLinkForNodeV; indexForNode.put(v, index); lowlinkForNode.put(v, lowLinkForNodeV = index); index++; s.push(v); for (N succ : g.getSuccsOf(v)) { Integer indexForNodeSucc = indexForNode.get(succ); if (indexForNodeSucc == null) { recurse(succ); lowlinkForNode.put(v, lowLinkForNodeV = Math.min(lowLinkForNodeV, lowlinkForNode.get(succ))); } else if (s.contains(succ)) { lowlinkForNode.put(v, lowLinkForNodeV = Math.min(lowLinkForNodeV, indexForNodeSucc)); } } if (lowLinkForNodeV == indexForNode.get(v)) { List<N> scc = new ArrayList<N>(); N v2; do { v2 = s.pop(); scc.add(v2); } while (v != v2); componentList.add(scc); if (scc.size() > 1) { trueComponentList.add(scc); } else { N n = scc.get(0); if (g.getSuccsOf(n).contains(n)) { trueComponentList.add(scc); } } } } protected void iterate(N x) { List<N> workList = new ArrayList<N>(); List<N> backtrackList = new ArrayList<N>(); workList.add(x); while (!workList.isEmpty()) { N v = workList.remove(0); boolean hasChildren = false; boolean isForward = false; if (!indexForNode.containsKey(v)) { indexForNode.put(v, index); lowlinkForNode.put(v, index); index++; s.push(v); isForward = true; } for (N succ : g.getSuccsOf(v)) { Integer indexForNodeSucc = indexForNode.get(succ); if (indexForNodeSucc == null) { // Recursive call workList.add(0, succ); hasChildren = true; break; } else if (!isForward) { // Returned from recursive call int lowLinkForNodeV = lowlinkForNode.get(v); lowlinkForNode.put(v, Math.min(lowLinkForNodeV, lowlinkForNode.get(succ))); } else if (isForward && s.contains(succ)) { int lowLinkForNodeV = lowlinkForNode.get(v); lowlinkForNode.put(v, Math.min(lowLinkForNodeV, indexForNodeSucc)); } } if (hasChildren) { backtrackList.add(0, v); } else { if (!backtrackList.isEmpty()) { workList.add(0, backtrackList.remove(0)); } int lowLinkForNodeV = lowlinkForNode.get(v); if (lowLinkForNodeV == indexForNode.get(v)) { List<N> scc = new ArrayList<N>(); N v2; do { v2 = s.pop(); scc.add(v2); } while (v != v2); componentList.add(scc); if (scc.size() > 1) { trueComponentList.add(scc); } else { N n = scc.get(0); if (g.getSuccsOf(n).contains(n)) { trueComponentList.add(scc); } } } } } } /** * @return the list of the strongly-connected components */ public List<List<N>> getComponents() { return componentList; } /** * @return the list of the strongly-connected components, but only those that are true components, i.e. components which * have more than one element or consists of one node that has itself as a successor */ public List<List<N>> getTrueComponents() { return trueComponentList; } }
5,805
28.622449
122
java
soot
soot-master/src/main/java/soot/toolkits/graph/TrapUnitGraph.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrice Pominville, 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.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.Body; import soot.Timers; import soot.Trap; import soot.Unit; import soot.options.Options; /** * <p> * Represents a CFG for a {@link Body} instance where the nodes are {@link Unit} instances, and where, in additional to * unexceptional control flow edges, edges are added from every trapped {@link Unit} to the {@link Trap}'s handler * <code>Unit</code>, regardless of whether the trapped <code>Unit</code>s may actually throw the exception caught by the * <code>Trap</code>. * </p> * * <p> * There are three distinctions between the exceptional edges added in <code>TrapUnitGraph</code> and the exceptional edges * added in {@link ExceptionalUnitGraph}: * <ol> * <li>In <code>ExceptionalUnitGraph</code>, the edges to <code>Trap</code>s are associated with <code>Unit</code>s which may * actually throw an exception which the <code>Trap</code> catches (according to the * {@link soot.toolkits.exceptions.ThrowAnalysis ThrowAnalysis} used in the construction of the graph). In * <code>TrapUnitGraph</code>, there are edges from every trapped <code>Unit</code> to the <code>Trap</code>, regardless of * whether it can throw an exception caught by the <code>Trap</code>.</li> * <li>In <code>ExceptionalUnitGraph</code>, when a <code>Unit</code> may throw an exception that is caught by a * <code>Trap</code> there are edges from every predecessor of the excepting <code>Unit</code> to the <code>Trap</code>'s * handler. In <code>TrapUnitGraph</code>, edges are not added from the predecessors of excepting <code>Unit</code>s.</li> * <li>In <code>ExceptionalUnitGraph</code>, when a <code>Unit</code> may throw an exception that is caught by a * <code>Trap</code>, there may be no edge from the excepting <code>Unit</code> itself to the <code>Trap</code> (depending on * the possibility of side effects and the setting of the <code>omitExceptingUnitEdges</code> parameter). In * <code>TrapUnitGraph</code>, there is always an edge from the excepting <code>Unit</code> to the <code>Trap</code>.</li> * </ol> */ public class TrapUnitGraph extends UnitGraph { /** * Constructs the graph from a given Body instance. * * @param body * the Body instance from which the graph is built. */ public TrapUnitGraph(Body body) { super(body); int size = unitChain.size(); if (Options.v().time()) { Timers.v().graphTimer.start(); } unitToSuccs = new HashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f); unitToPreds = new HashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f); buildUnexceptionalEdges(unitToSuccs, unitToPreds); buildExceptionalEdges(unitToSuccs, unitToPreds); buildHeadsAndTails(); if (Options.v().time()) { Timers.v().graphTimer.end(); } soot.util.PhaseDumper.v().dumpGraph(this, body); } /** * Method to compute the edges corresponding to exceptional control flow. * * @param unitToSuccs * A <code>Map</code> from {@link Unit}s to {@link List}s of <code>Unit</code>s. This is an &ldquo;out * parameter&rdquo;; <code>buildExceptionalEdges</code> will add a mapping for every <code>Unit</code> within the * scope of one or more {@link Trap}s to a <code>List</code> of the handler units of those <code>Trap</code>s. * * @param unitToPreds * A <code>Map</code> from <code>Unit</code>s to <code>List</code>s of <code>Unit</code>s. This is an &ldquo;out * parameter&rdquo;; <code>buildExceptionalEdges</code> will add a mapping for every <code>Trap</code> handler to * all the <code>Unit</code>s within the scope of that <code>Trap</code>. */ protected void buildExceptionalEdges(Map<Unit, List<Unit>> unitToSuccs, Map<Unit, List<Unit>> unitToPreds) { for (Trap trap : body.getTraps()) { Unit catcher = trap.getHandlerUnit(); Unit first = trap.getBeginUnit(); Unit last = unitChain.getPredOf(trap.getEndUnit()); for (Iterator<Unit> unitIt = unitChain.iterator(first, last); unitIt.hasNext();) { Unit trapped = unitIt.next(); addEdge(unitToSuccs, unitToPreds, trapped, catcher); } } } }
5,099
42.965517
125
java
soot
soot-master/src/main/java/soot/toolkits/graph/UnitGraph.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrice Pominville, 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.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.SootMethod; import soot.Unit; import soot.UnitBox; import soot.options.Options; import soot.util.Chain; /** * <p> * Represents a CFG where the nodes are {@link Unit} instances and edges represent unexceptional and (possibly) exceptional * control flow between <tt>Unit</tt>s. * </p> * * <p> * This is an abstract class, providing the facilities used to build CFGs for specific purposes. * </p> */ public abstract class UnitGraph implements DirectedBodyGraph<Unit> { private static final Logger logger = LoggerFactory.getLogger(UnitGraph.class); protected final Body body; protected final Chain<Unit> unitChain; protected final SootMethod method; protected List<Unit> heads; protected List<Unit> tails; protected Map<Unit, List<Unit>> unitToSuccs; protected Map<Unit, List<Unit>> unitToPreds; /** * Performs the work that is required to construct any sort of <tt>UnitGraph</tt>. * * @param body * The body of the method for which to construct a control flow graph. */ protected UnitGraph(Body body) { this.body = body; this.unitChain = body.getUnits(); this.method = body.getMethod(); if (Options.v().verbose()) { logger.debug("[" + method.getName() + "] Constructing " + this.getClass().getName() + "..."); } } /** * Utility method for <tt>UnitGraph</tt> constructors. It computes the edges corresponding to unexceptional control flow. * * @param unitToSuccs * A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is an ``out parameter''; callers must * pass an empty {@link Map}. <tt>buildUnexceptionalEdges</tt> will add a mapping for every <tt>Unit</tt> in the * body to a list of its unexceptional successors. * * @param unitToPreds * A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is an ``out parameter''; callers must * pass an empty {@link Map}. <tt>buildUnexceptionalEdges</tt> will add a mapping for every <tt>Unit</tt> in the * body to a list of its unexceptional predecessors. */ protected void buildUnexceptionalEdges(Map<Unit, List<Unit>> unitToSuccs, Map<Unit, List<Unit>> unitToPreds) { Iterator<Unit> unitIt = unitChain.iterator(); Unit nextUnit = unitIt.hasNext() ? unitIt.next() : null; while (nextUnit != null) { Unit currentUnit = nextUnit; nextUnit = unitIt.hasNext() ? unitIt.next() : null; ArrayList<Unit> successors = new ArrayList<Unit>(); if (currentUnit.fallsThrough()) { // Add the next unit as the successor if (nextUnit != null) { successors.add(nextUnit); List<Unit> preds = unitToPreds.get(nextUnit); if (preds == null) { preds = new ArrayList<Unit>(); unitToPreds.put(nextUnit, preds); } preds.add(currentUnit); } } if (currentUnit.branches()) { for (UnitBox targetBox : currentUnit.getUnitBoxes()) { Unit target = targetBox.getUnit(); // Arbitrary bytecode can branch to the same // target it falls through to, so we screen for duplicates: if (!successors.contains(target)) { successors.add(target); List<Unit> preds = unitToPreds.get(target); if (preds == null) { preds = new ArrayList<Unit>(); unitToPreds.put(target, preds); } preds.add(currentUnit); } } } // Store away successors if (!successors.isEmpty()) { successors.trimToSize(); unitToSuccs.put(currentUnit, successors); } } } /** * <p> * Utility method used in the construction of {@link UnitGraph}s, to be called only after the unitToPreds and unitToSuccs * maps have been built. * </p> * * <p> * <code>UnitGraph</code> provides an implementation of <code>buildHeadsAndTails()</code> which defines the graph's set of * heads to include the first {@link Unit} in the graph's body, together with any other <tt>Unit</tt> which has no * predecessors. It defines the graph's set of tails to include all <tt>Unit</tt>s with no successors. Subclasses of * <code>UnitGraph</code> may override this method to change the criteria for classifying a node as a head or tail. * </p> */ protected void buildHeadsAndTails() { tails = new ArrayList<Unit>(); heads = new ArrayList<Unit>(); Unit entryPoint = null; if (!unitChain.isEmpty()) { entryPoint = unitChain.getFirst(); } boolean hasEntryPoint = false; for (Unit s : unitChain) { List<Unit> succs = unitToSuccs.get(s); if (succs == null || succs.isEmpty()) { tails.add(s); } List<Unit> preds = unitToPreds.get(s); if (preds == null || preds.isEmpty()) { if (s == entryPoint) { hasEntryPoint = true; } heads.add(s); } } // Add the first Unit, even if it is the target of a branch. if (entryPoint != null) { if (!hasEntryPoint) { heads.add(entryPoint); } } } /** * Utility method that produces a new map from the {@link Unit}s of this graph's body to the union of the values stored in * the two argument {@link Map}s, used to combine the maps of exceptional and unexceptional predecessors and successors * into maps of all predecessors and successors. The values stored in both argument maps must be {@link List}s of * {@link Unit}s, which are assumed not to contain any duplicate <tt>Unit</tt>s. * * @param mapA * The first map to be combined. * * @param mapB * The second map to be combined. */ protected Map<Unit, List<Unit>> combineMapValues(Map<Unit, List<Unit>> mapA, Map<Unit, List<Unit>> mapB) { // The duplicate screen Map<Unit, List<Unit>> result = new LinkedHashMap<Unit, List<Unit>>(mapA.size() * 2 + 1, 0.7f); for (Unit unit : unitChain) { List<Unit> listA = mapA.get(unit); if (listA == null) { listA = Collections.emptyList(); } List<Unit> listB = mapB.get(unit); if (listB == null) { listB = Collections.emptyList(); } int resultSize = listA.size() + listB.size(); if (resultSize == 0) { result.put(unit, Collections.<Unit>emptyList()); } else { List<Unit> resultList = new ArrayList<Unit>(resultSize); List<Unit> list; // As a minor optimization of the duplicate screening, // copy the longer list first. if (listA.size() >= listB.size()) { resultList.addAll(listA); list = listB; } else { resultList.addAll(listB); list = listA; } for (Unit element : list) { // It is possible for there to be both an exceptional // and an unexceptional edge connecting two Units // (though probably not in a class generated by // javac), so we need to screen for duplicates. On the // other hand, we expect most of these lists to have // only one or two elements, so it doesn't seem worth // the cost to build a Set to do the screening. if (!resultList.contains(element)) { resultList.add(element); } } result.put(unit, resultList); } } return result; } /** * Utility method for adding an edge to maps representing the CFG. * * @param unitToSuccs * The {@link Map} from {@link Unit}s to {@link List}s of their successors. * * @param unitToPreds * The {@link Map} from {@link Unit}s to {@link List}s of their successors. * * @param head * The {@link Unit} from which the edge starts. * * @param tail * The {@link Unit} to which the edge flows. */ protected void addEdge(Map<Unit, List<Unit>> unitToSuccs, Map<Unit, List<Unit>> unitToPreds, Unit head, Unit tail) { List<Unit> headsSuccs = unitToSuccs.get(head); if (headsSuccs == null) { headsSuccs = new ArrayList<Unit>(3); // We expect this list to remain short. unitToSuccs.put(head, headsSuccs); } if (!headsSuccs.contains(tail)) { headsSuccs.add(tail); List<Unit> tailsPreds = unitToPreds.get(tail); if (tailsPreds == null) { tailsPreds = new ArrayList<Unit>(); unitToPreds.put(tail, tailsPreds); } tailsPreds.add(head); } } /** * @return The body from which this UnitGraph was built. * * @see Body */ @Override public Body getBody() { return body; } /** * Look for a path in graph, from def to use. This path has to lie inside an extended basic block (and this property * implies uniqueness.). The path returned includes from and to. * * @param from * start point for the path. * @param to * end point for the path. * @return null if there is no such path. */ public List<Unit> getExtendedBasicBlockPathBetween(Unit from, Unit to) { // if this holds, we're doomed to failure!!! if (this.getPredsOf(to).size() > 1) { return null; } // pathStack := list of succs lists // pathStackIndex := last visited index in pathStack LinkedList<Unit> pathStack = new LinkedList<Unit>(); LinkedList<Integer> pathStackIndex = new LinkedList<Integer>(); pathStack.add(from); pathStackIndex.add(0); final int psiMax = this.getSuccsOf(from).size(); int level = 0; while (pathStackIndex.get(0) != psiMax) { int p = pathStackIndex.get(level); List<Unit> succs = this.getSuccsOf(pathStack.get(level)); if (p >= succs.size()) { // no more succs - backtrack to previous level. pathStack.remove(level); pathStackIndex.remove(level); level--; int q = pathStackIndex.get(level); pathStackIndex.set(level, q + 1); continue; } Unit betweenUnit = succs.get(p); // we win! if (betweenUnit == to) { pathStack.add(to); return pathStack; } // check preds of betweenUnit to see if we should visit its kids. if (this.getPredsOf(betweenUnit).size() > 1) { pathStackIndex.set(level, p + 1); continue; } // visit kids of betweenUnit. level++; pathStackIndex.add(0); pathStack.add(betweenUnit); } return null; } /* DirectedGraph implementation */ @Override public List<Unit> getHeads() { return heads; } @Override public List<Unit> getTails() { return tails; } @Override public List<Unit> getPredsOf(Unit u) { List<Unit> l = unitToPreds.get(u); return l == null ? Collections.emptyList() : l; } @Override public List<Unit> getSuccsOf(Unit u) { List<Unit> l = unitToSuccs.get(u); return l == null ? Collections.emptyList() : l; } @Override public int size() { return unitChain.size(); } @Override public Iterator<Unit> iterator() { return unitChain.iterator(); } @Override public String toString() { StringBuilder buf = new StringBuilder(); for (Unit u : unitChain) { buf.append("// preds: ").append(getPredsOf(u)).append('\n'); buf.append(u).append('\n'); buf.append("// succs ").append(getSuccsOf(u)).append('\n'); } return buf.toString(); } }
12,593
30.80303
124
java
soot
soot-master/src/main/java/soot/toolkits/graph/ZonedBlockGraph.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrice Pominville, 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.Set; import soot.Body; import soot.Trap; import soot.Unit; /** * A CFG where the nodes are {@link Block} instances, and where exception boundaries are taken into account when finding the * <tt>Block</tt>s for the provided Body. Any {@link Unit} which is the first <tt>Unit</tt> to be convered by some exception * handler will start a new Block, and any <tt>Unit</tt> which is the last <tt>Unit</tt> to be covered a some exception * handler, will end the block it is part of. These ``zones'', however, are not split up to indicate the possibility that an * exception will lead to control exiting the zone before it is completed. */ public class ZonedBlockGraph extends BlockGraph { /** * <p> * Constructs a <tt>ZonedBlockGraph</tt> for the <tt>Unit</tt>s comprising the passed {@link Body}. * </p> * * <p> * Note that this constructor builds a {@link BriefUnitGraph} internally when splitting <tt>body</tt>'s {@link Unit}s into * {@link Block}s. Callers who need both a {@link BriefUnitGraph} and a {@link ZonedBlockGraph} can use the constructor * taking the <tt>BriefUnitGraph</tt> as a parameter, as a minor optimization. * </p> * * @param body * The <tt>Body</tt> for which to produce a <tt>ZonedBlockGraph</tt>. */ public ZonedBlockGraph(Body body) { this(new BriefUnitGraph(body)); } /** * Constructs a <tt>ZonedBlockGraph</tt> corresponding to the <tt>Unit</tt>-level control flow represented by the passed * {@link BriefUnitGraph}. * * @param unitGraph * The <tt>BriefUnitGraph</tt> for which to produce a <tt>ZonedBlockGraph</tt>. */ public ZonedBlockGraph(BriefUnitGraph unitGraph) { super(unitGraph); soot.util.PhaseDumper.v().dumpGraph(this, mBody); } /** * <p> * Utility method for computing the basic block leaders for a {@link Body}, given its {@link UnitGraph} (i.e., the * instructions which begin new basic blocks). * </p> * * <p> * This implementation chooses as block leaders all the <tt>Unit</tt>s that {@link BlockGraph.computerLeaders()}, and adds: * * <ul> * * <li>The first <tt>Unit</tt> covered by each {@link Trap} (i.e., the <tt>Unit</tt> returned by * {@link Trap.getBeginUnit()}.</li> * * <li>The first <tt>Unit</tt> not covered by each {@link Trap} (i.e., the <tt>Unit</tt> returned by * {@link Trap.getEndUnit()}.</li> * * </ul> * </p> * * @param unitGraph * is the <tt>Unit</tt>-level CFG which is to be split into basic blocks. * * @return the {@link Set} of {@link Unit}s in <tt>unitGraph</tt> which are block leaders. */ @Override protected Set<Unit> computeLeaders(UnitGraph unitGraph) { Body body = unitGraph.getBody(); if (body != mBody) { throw new RuntimeException("ZonedBlockGraph.computeLeaders() called with a UnitGraph that doesn't match its mBody."); } Set<Unit> leaders = super.computeLeaders(unitGraph); for (Trap trap : body.getTraps()) { leaders.add(trap.getBeginUnit()); leaders.add(trap.getEndUnit()); } return leaders; } }
3,987
35.587156
125
java
soot
soot-master/src/main/java/soot/toolkits/graph/interaction/FlowInfo.java
package soot.toolkits.graph.interaction; /*- * #%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 FlowInfo<I, U> { private I info; private U unit; private boolean before; public FlowInfo(I info, U unit, boolean b) { info(info); unit(unit); setBefore(b); } public U unit() { return unit; } public void unit(U u) { unit = u; } public I info() { return info; } public void info(I i) { info = i; } public boolean isBefore() { return before; } public void setBefore(boolean b) { before = b; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("unit: " + unit); sb.append(" info: " + info); sb.append(" before: " + before); return sb.toString(); } }
1,529
21.173913
71
java
soot
soot-master/src/main/java/soot/toolkits/graph/interaction/IInteractionConstants.java
package soot.toolkits.graph.interaction; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public interface IInteractionConstants { public static final int NEW_ANALYSIS = 0; public static final int WANT_ANALYSIS = 1; public static final int NEW_CFG = 2; public static final int CONTINUE = 3; public static final int NEW_BEFORE_ANALYSIS_INFO = 4; public static final int NEW_AFTER_ANALYSIS_INFO = 5; public static final int DONE = 6; public static final int FORWARDS = 7; public static final int BACKWARDS = 8; public static final int CLEARTO = 9; public static final int REPLACE = 10; public static final int NEW_BEFORE_ANALYSIS_INFO_AUTO = 11; public static final int NEW_AFTER_ANALYSIS_INFO_AUTO = 12; public static final int STOP_AT_NODE = 13; public static final int CALL_GRAPH_START = 50; public static final int CALL_GRAPH_NEXT_METHOD = 51; public static final int CALL_GRAPH_PART = 52; public static final int CALL_GRAPH_DONE = 53; }
1,730
35.829787
71
java
soot
soot-master/src/main/java/soot/toolkits/graph/interaction/IInteractionController.java
package soot.toolkits.graph.interaction; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public interface IInteractionController { // public void fireInteractionEvent(InteractionEvent event); public void addListener(IInteractionListener listener); public void removeListener(IInteractionListener listener); }
1,070
32.46875
71
java
soot
soot-master/src/main/java/soot/toolkits/graph/interaction/IInteractionListener.java
package soot.toolkits.graph.interaction; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public interface IInteractionListener { public void setEvent(InteractionEvent event); // public void setAvailable(boolean available); // public void setAvailable(); public void handleEvent(); }
1,046
30.727273
71
java
soot
soot-master/src/main/java/soot/toolkits/graph/interaction/InteractionEvent.java
package soot.toolkits.graph.interaction; /*- * #%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 InteractionEvent { private int type; private Object info; public InteractionEvent(int type) { type(type); } public InteractionEvent(int type, Object info) { type(type); info(info); } private void type(int t) { type = t; } private void info(Object i) { info = i; } public int type() { return type; } public Object info() { return info; } }
1,257
21.872727
71
java
soot
soot-master/src/main/java/soot/toolkits/graph/interaction/InteractionHandler.java
package soot.toolkits.graph.interaction; /*- * #%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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.G; import soot.PhaseOptions; import soot.Singletons; import soot.SootMethod; import soot.Transform; import soot.jimple.toolkits.annotation.callgraph.CallGraphGrapher; import soot.options.Options; import soot.toolkits.graph.DirectedGraph; public class InteractionHandler { private static final Logger logger = LoggerFactory.getLogger(InteractionHandler.class); public InteractionHandler(Singletons.Global g) { } public static InteractionHandler v() { return G.v().soot_toolkits_graph_interaction_InteractionHandler(); } private ArrayList<Object> stopUnitList; public ArrayList<Object> getStopUnitList() { return stopUnitList; } public void addToStopUnitList(Object elem) { if (stopUnitList == null) { stopUnitList = new ArrayList<Object>(); } stopUnitList.add(elem); } public void removeFromStopUnitList(Object elem) { if (stopUnitList.contains(elem)) { stopUnitList.remove(elem); } } public void handleNewAnalysis(Transform t, Body b) { // here save current phase name and only send if actual data flow analysis exists if (PhaseOptions.getBoolean(PhaseOptions.v().getPhaseOptions(t.getPhaseName()), "enabled")) { String name = t.getPhaseName() + " for method: " + b.getMethod().getName(); currentPhaseName(name); currentPhaseEnabled(true); doneCurrent(false); } else { currentPhaseEnabled(false); setInteractThisAnalysis(false); } } public void handleCfgEvent(DirectedGraph<?> g) { if (currentPhaseEnabled()) { logger.debug("Analyzing: " + currentPhaseName()); doInteraction(new InteractionEvent(IInteractionConstants.NEW_ANALYSIS, currentPhaseName())); } if (isInteractThisAnalysis()) { doInteraction(new InteractionEvent(IInteractionConstants.NEW_CFG, g)); } } public void handleStopAtNodeEvent(Object u) { if (isInteractThisAnalysis()) { doInteraction(new InteractionEvent(IInteractionConstants.STOP_AT_NODE, u)); } } public void handleBeforeAnalysisEvent(Object beforeFlow) { if (isInteractThisAnalysis()) { if (autoCon()) { doInteraction(new InteractionEvent(IInteractionConstants.NEW_BEFORE_ANALYSIS_INFO_AUTO, beforeFlow)); } else { doInteraction(new InteractionEvent(IInteractionConstants.NEW_BEFORE_ANALYSIS_INFO, beforeFlow)); } } } public void handleAfterAnalysisEvent(Object afterFlow) { if (isInteractThisAnalysis()) { if (autoCon()) { doInteraction(new InteractionEvent(IInteractionConstants.NEW_AFTER_ANALYSIS_INFO_AUTO, afterFlow)); } else { doInteraction(new InteractionEvent(IInteractionConstants.NEW_AFTER_ANALYSIS_INFO, afterFlow)); } } } public void handleTransformDone(Transform t, Body b) { doneCurrent(true); if (isInteractThisAnalysis()) { doInteraction(new InteractionEvent(IInteractionConstants.DONE, null)); } } public void handleCallGraphStart(Object info, CallGraphGrapher grapher) { setGrapher(grapher); doInteraction(new InteractionEvent(IInteractionConstants.CALL_GRAPH_START, info)); if (!isCgReset()) { handleCallGraphNextMethod(); } else { setCgReset(false); handleReset(); } } public void handleCallGraphNextMethod() { if (!cgDone()) { getGrapher().setNextMethod(getNextMethod()); getGrapher().handleNextMethod(); } } private boolean cgReset = false; public void setCgReset(boolean v) { cgReset = v; } public boolean isCgReset() { return cgReset; } public void handleReset() { if (!cgDone()) { getGrapher().reset(); } } public void handleCallGraphPart(Object info) { doInteraction(new InteractionEvent(IInteractionConstants.CALL_GRAPH_PART, info)); if (!isCgReset()) { handleCallGraphNextMethod(); } else { setCgReset(false); handleReset(); } } private CallGraphGrapher grapher; private void setGrapher(CallGraphGrapher g) { grapher = g; } private CallGraphGrapher getGrapher() { return grapher; } private SootMethod nextMethod; public void setNextMethod(SootMethod m) { nextMethod = m; } private SootMethod getNextMethod() { return nextMethod; } private synchronized void doInteraction(InteractionEvent event) { getInteractionListener().setEvent(event); getInteractionListener().handleEvent(); } public synchronized void waitForContinue() { try { this.wait(); } catch (InterruptedException e) { logger.debug("" + e.getMessage()); } } private boolean interactThisAnalysis; public void setInteractThisAnalysis(boolean b) { interactThisAnalysis = b; } public boolean isInteractThisAnalysis() { return interactThisAnalysis; } private boolean interactionCon; public synchronized void setInteractionCon() { this.notify(); } public boolean isInteractionCon() { return interactionCon; } private IInteractionListener interactionListener; public void setInteractionListener(IInteractionListener listener) { interactionListener = listener; } public IInteractionListener getInteractionListener() { return interactionListener; } private String currentPhaseName; public void currentPhaseName(String name) { currentPhaseName = name; } public String currentPhaseName() { return currentPhaseName; } private boolean currentPhaseEnabled; public void currentPhaseEnabled(boolean b) { currentPhaseEnabled = b; } public boolean currentPhaseEnabled() { return currentPhaseEnabled; } private boolean cgDone = false; public void cgDone(boolean b) { cgDone = b; } public boolean cgDone() { return cgDone; } private boolean doneCurrent; public void doneCurrent(boolean b) { doneCurrent = b; } public boolean doneCurrent() { return doneCurrent; } private boolean autoCon; public void autoCon(boolean b) { autoCon = b; } public boolean autoCon() { return autoCon; } public void stopInteraction(boolean b) { Options.v().set_interactive_mode(false); } }
7,134
23.688581
109
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/ConditionalPDGNode.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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 represents a PDGNode that has more than 1 dependent but is not a loop header. This includes a conditional node, or a * potentially exceptional node. * */ public class ConditionalPDGNode extends PDGNode { public ConditionalPDGNode(Object obj, Type t) { super(obj, t); } public ConditionalPDGNode(PDGNode node) { this(node.getNode(), node.getType()); this.m_dependents.addAll(node.m_dependents); this.m_backDependents.addAll(node.m_backDependents); this.m_next = node.m_next; this.m_prev = node.m_prev; } }
1,408
28.978723
124
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/EnhancedBlockGraph.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.Body; import soot.toolkits.graph.BlockGraph; public class EnhancedBlockGraph extends BlockGraph { public EnhancedBlockGraph(Body body) { this(new EnhancedUnitGraph(body)); } public EnhancedBlockGraph(EnhancedUnitGraph unitGraph) { super(unitGraph); soot.util.PhaseDumper.v().dumpGraph(this, mBody); } }
1,188
28.725
71
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/EnhancedUnitGraph.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.Hashtable; import java.util.List; import soot.Body; import soot.Trap; import soot.Unit; import soot.jimple.ThrowStmt; import soot.jimple.internal.JNopStmt; import soot.toolkits.graph.DominatorNode; import soot.toolkits.graph.MHGDominatorsFinder; import soot.toolkits.graph.MHGPostDominatorsFinder; import soot.toolkits.graph.UnitGraph; import soot.util.Chain; /** * This class represents a control flow graph which behaves like an ExceptionalUnitGraph and BriefUnitGraph when there are no * exception handling construct in the method; at the presence of such constructs, the CFG is constructed from a brief graph * by adding a concise representation of the exceptional flow as well as START/STOP auxiliary nodes. In a nutshell, the * exceptional flow is represented at the level of try-catch-finally blocks instead of the Unit level to allow a more useful * region analysis. * * @author Hossein Sadat-Mohtasham */ public class EnhancedUnitGraph extends UnitGraph { // This keeps a map from the beginning of each guarded block // to the corresponding special EHNopStmt. protected final Hashtable<Unit, Unit> try2nop = new Hashtable<Unit, Unit>(); // Keep the real header of the handler block protected final Hashtable<Unit, Unit> handler2header = new Hashtable<Unit, Unit>(); public EnhancedUnitGraph(Body body) { super(body); // there could be a maximum of traps.size() of nop // units added to the CFG plus potentially START/STOP nodes. int size = (unitChain.size() + body.getTraps().size() + 2); unitToSuccs = new HashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f); unitToPreds = new HashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f); // Initialize all units in the unitToSuccs and unitsToPreds for (Unit u : body.getUnits()) { unitToSuccs.put(u, new ArrayList<>()); unitToPreds.put(u, new ArrayList<>()); } /* * Compute the head and tails at each phase because other phases might rely on them. */ buildUnexceptionalEdges(unitToSuccs, unitToPreds); addAuxiliaryExceptionalEdges(); buildHeadsAndTails(); handleExplicitThrowEdges(); buildHeadsAndTails(); handleMultipleReturns(); buildHeadsAndTails(); /** * Remove bogus heads (these are useless goto's) */ removeBogusHeads(); buildHeadsAndTails(); } /** * This method adds a STOP node to the graph, if necessary, to make the CFG single-tailed. */ protected void handleMultipleReturns() { if (this.getTails().size() > 1) { Unit stop = new ExitStmt(); List<Unit> predsOfstop = new ArrayList<Unit>(); for (Unit tail : this.getTails()) { predsOfstop.add(tail); List<Unit> tailSuccs = this.unitToSuccs.get(tail); if (tailSuccs == null) { tailSuccs = new ArrayList<Unit>(); this.unitToSuccs.put(tail, tailSuccs); } tailSuccs.add(stop); } this.unitToPreds.put(stop, predsOfstop); this.unitToSuccs.put(stop, new ArrayList<Unit>()); Chain<Unit> units = body.getUnits().getNonPatchingChain(); if (!units.contains(stop)) { units.addLast(stop); } } } /** * This method removes all the heads in the CFG except the one that corresponds to the first unit in the method. */ protected void removeBogusHeads() { Chain<Unit> units = body.getUnits(); Unit trueHead = units.getFirst(); while (this.getHeads().size() > 1) { for (Unit head : this.getHeads()) { if (trueHead == head) { continue; } this.unitToPreds.remove(head); for (Unit succ : this.unitToSuccs.get(head)) { List<Unit> tobeRemoved = new ArrayList<Unit>(); List<Unit> predOfSuccs = this.unitToPreds.get(succ); if (predOfSuccs != null) { for (Unit pred : predOfSuccs) { if (pred == head) { tobeRemoved.add(pred); } } predOfSuccs.removeAll(tobeRemoved); } } this.unitToSuccs.remove(head); if (units.contains(head)) { units.remove(head); } } this.buildHeadsAndTails(); } } protected void handleExplicitThrowEdges() { MHGDominatorTree<Unit> dom = new MHGDominatorTree<Unit>(new MHGDominatorsFinder<Unit>(this)); MHGDominatorTree<Unit> pdom = new MHGDominatorTree<Unit>(new MHGPostDominatorsFinder<Unit>(this)); // this keeps a map from the entry of a try-catch-block to a selected merge point Hashtable<Unit, Unit> x2mergePoint = new Hashtable<Unit, Unit>(); TailsLoop: for (Unit tail : this.getTails()) { if (!(tail instanceof ThrowStmt)) { continue; } DominatorNode<Unit> x = dom.getDode(tail); DominatorNode<Unit> parentOfX = dom.getParentOf(x); Unit xgode = x.getGode(); DominatorNode<Unit> xpdomDode = pdom.getDode(xgode); Unit parentXGode = parentOfX.getGode(); DominatorNode<Unit> parentpdomDode = pdom.getDode(parentXGode); // while x post-dominates its dominator (parent in dom) while (pdom.isDominatorOf(xpdomDode, parentpdomDode)) { x = parentOfX; parentOfX = dom.getParentOf(x); // If parent is null we must be at the head of the graph if (parentOfX == null) { // throw new // RuntimeException("This should never have happened!"); break; } xgode = x.getGode(); xpdomDode = pdom.getDode(xgode); parentXGode = parentOfX.getGode(); parentpdomDode = pdom.getDode(parentXGode); } if (parentOfX != null) { x = parentOfX; } xgode = x.getGode(); xpdomDode = pdom.getDode(xgode); Unit mergePoint = null; if (x2mergePoint.containsKey(xgode)) { mergePoint = x2mergePoint.get(xgode); } else { // Now get all the children of x in the dom List<DominatorNode<Unit>> domChilds = dom.getChildrenOf(x); Unit child1god = null; Unit child2god = null; for (DominatorNode<Unit> child : domChilds) { Unit childGode = child.getGode(); DominatorNode<Unit> childpdomDode = pdom.getDode(childGode); // we don't want to make a loop! List<Unit> path = this.getExtendedBasicBlockPathBetween(childGode, tail); // if(dom.isDominatorOf(child, dom.getDode(tail))) if (!(path == null || path.isEmpty())) { continue; } if (pdom.isDominatorOf(childpdomDode, xpdomDode)) { mergePoint = child.getGode(); break; } // gather two eligible childs if (child1god == null) { child1god = childGode; } else if (child2god == null) { child2god = childGode; } } if (mergePoint == null) { if (child1god != null && child2god != null) { DominatorNode<Unit> child1 = pdom.getDode(child1god); DominatorNode<Unit> child2 = pdom.getDode(child2god); // go up the pdom tree and find the common parent of // child1 and child2 DominatorNode<Unit> comParent = child1.getParent(); while (comParent != null) { if (pdom.isDominatorOf(comParent, child2)) { mergePoint = comParent.getGode(); break; } comParent = comParent.getParent(); } } else if (child1god != null || child2god != null) { DominatorNode<Unit> y = null; if (child1god != null) { y = pdom.getDode(child1god); } else { assert (child2god != null); y = pdom.getDode(child2god); } DominatorNode<Unit> initialY = dom.getDode(y.getGode()); DominatorNode<Unit> yDodeInDom = initialY; while (dom.isDominatorOf(x, yDodeInDom)) { y = y.getParent(); // If this is a case where the childs of a // conditional // are all throws, or returns, just forget it! if (y == null) { break; } yDodeInDom = dom.getDode(y.getGode()); } mergePoint = y == null ? initialY.getGode() : y.getGode(); } } // This means no (dom) child of x post-dominates x, so just use // the child that is // immediately /* * if(mergePoint == null) { //throw new RuntimeException("No child post-dominates x."); mergePoint = * potentialMergePoint; * * } */ // This means no (dom) child of x post-dominates x, so just use // the child that is // immediately. this means there is no good reliable merge // point. So we just fetch the succ // of x in CFg so that the succ does not dominate the throw, and // find the first // post-dom of the succ so that x does not dom it. // if (mergePoint == null) { List<Unit> xSucc = this.unitToSuccs.get(x.getGode()); if (xSucc != null) { for (Unit u : xSucc) { if (dom.isDominatorOf(dom.getDode(u), dom.getDode(tail))) { continue; } DominatorNode<Unit> y = pdom.getDode(u); while (dom.isDominatorOf(x, y)) { y = y.getParent(); // If this is a case where the childs of a // conditional // are all throws, or returns, just forget it! if (y == null) { continue TailsLoop; } } mergePoint = y.getGode(); break; } } } // the following happens if the throw is the only exit in the // method (even if return stmt is present.) else if (dom.isDominatorOf(dom.getDode(mergePoint), dom.getDode(tail))) { continue TailsLoop; } // turns out that when the method ends with a throw, the control // get here. if (mergePoint == null) { continue TailsLoop; } x2mergePoint.put(xgode, mergePoint); } // add an edge from the tail (throw) to the merge point List<Unit> throwSuccs = this.unitToSuccs.get(tail); if (throwSuccs == null) { throwSuccs = new ArrayList<Unit>(); this.unitToSuccs.put(tail, throwSuccs); } throwSuccs.add(mergePoint); List<Unit> mergePreds = this.unitToPreds.get(mergePoint); if (mergePreds == null) { mergePreds = new ArrayList<Unit>(); this.unitToPreds.put(mergePoint, mergePreds); } mergePreds.add(tail); } } /** * Add an exceptional flow edge for each handler from the corresponding auxiliary nop node to the beginning of the handler. */ protected void addAuxiliaryExceptionalEdges() { // Do some preparation for each trap in the method for (Trap trap : body.getTraps()) { // Find the real header of this handler block final Unit handler = trap.getHandlerUnit(); Unit pred = handler; { List<Unit> preds; while (!(preds = this.unitToPreds.get(pred)).isEmpty()) { pred = preds.get(0); } } handler2header.put(handler, pred); /***********/ /* * Keep this here for possible future changes. */ /* * GuardedBlock gb = new GuardedBlock(trap.getBeginUnit(), trap.getEndUnit()); Unit ehnop; if(try2nop.containsKey(gb)) * ehnop = try2nop.get(gb); else { ehnop = new EHNopStmt(); try2nop.put(gb, ehnop); } */ Unit trapBegin = trap.getBeginUnit(); if (!try2nop.containsKey(trapBegin)) { try2nop.put(trapBegin, new EHNopStmt()); } } // Only add a nop once Hashtable<Unit, Boolean> nop2added = new Hashtable<Unit, Boolean>(); // Now actually add the edge AddExceptionalEdge: for (Trap trap : body.getTraps()) { Unit b = trap.getBeginUnit(); Unit handler = trap.getHandlerUnit(); handler = handler2header.get(handler); /** * Check if this trap is a finally trap that handles exceptions of an adjacent catch block; what differentiates such * trap is that it's guarded region has the same parent as the handler of the trap itself, in the dom tree. * * The problem is that we don't have a complete DOM tree at this transient state. * * The work-around is to not process a trap that has already an edge pointing to it. * */ if (this.unitToPreds.containsKey(handler)) { for (Unit u : this.unitToPreds.get(handler)) { if (try2nop.containsValue(u)) { continue AddExceptionalEdge; } } } else { continue; } // GuardedBlock gb = new GuardedBlock(b, e); Unit ehnop = try2nop.get(b); if (!nop2added.containsKey(ehnop)) { List<Unit> predsOfB = getPredsOf(b); List<Unit> predsOfehnop = new ArrayList<Unit>(predsOfB); for (Unit a : predsOfB) { List<Unit> succsOfA = this.unitToSuccs.get(a); if (succsOfA == null) { succsOfA = new ArrayList<Unit>(); this.unitToSuccs.put(a, succsOfA); } else { succsOfA.remove(b); } succsOfA.add((Unit) ehnop); } predsOfB.clear(); predsOfB.add(ehnop); this.unitToPreds.put(ehnop, predsOfehnop); } List<Unit> succsOfehnop = this.unitToSuccs.get(ehnop); if (succsOfehnop == null) { succsOfehnop = new ArrayList<Unit>(); this.unitToSuccs.put(ehnop, succsOfehnop); } if (!succsOfehnop.contains(b)) { succsOfehnop.add(b); } succsOfehnop.add(handler); List<Unit> predsOfhandler = this.unitToPreds.get(handler); if (predsOfhandler == null) { predsOfhandler = new ArrayList<Unit>(); this.unitToPreds.put(handler, predsOfhandler); } predsOfhandler.add(ehnop); Chain<Unit> units = body.getUnits().getNonPatchingChain(); if (!units.contains(ehnop)) { units.insertBefore(ehnop, b); } nop2added.put(ehnop, Boolean.TRUE); } } } /** * This class represents a block of code guarded by a trap. Currently, this is not used but it might well be put to use in * later updates. * * @author Hossein Sadat-Mohtasham */ class GuardedBlock { Unit start, end; public GuardedBlock(Unit s, Unit e) { this.start = s; this.end = e; } @Override public int hashCode() { // Following Joshua Bloch's recipe in "Effective Java", Item 8: int result = 17; result = 37 * result + this.start.hashCode(); result = 37 * result + this.end.hashCode(); return result; } @Override public boolean equals(Object rhs) { if (rhs == this) { return true; } if (!(rhs instanceof GuardedBlock)) { return false; } GuardedBlock rhsGB = (GuardedBlock) rhs; return (this.start == rhsGB.start) && (this.end == rhsGB.end); } } /** * This class represents a special nop statement that marks the beginning of a try block at the Jimple level. This is going * to be used in the CFG enhancement. * * @author Hossein Sadat-Mohtasham Feb 2010 */ @SuppressWarnings("serial") class EHNopStmt extends JNopStmt { public EHNopStmt() { } @Override public Object clone() { return new EHNopStmt(); } @Override public boolean fallsThrough() { return true; } @Override public boolean branches() { return false; } } /** * This class represents a special nop statement that marks the beginning of method body at the Jimple level. This is going * to be used in the CFG enhancement. * * @author Hossein Sadat-Mohtasham Feb 2010 */ @SuppressWarnings("serial") class EntryStmt extends JNopStmt { public EntryStmt() { } @Override public Object clone() { return new EntryStmt(); } @Override public boolean fallsThrough() { return true; } @Override public boolean branches() { return false; } } /** * This class represents a special nop statement that marks the exit of method body at the Jimple level. This is going to be * used in the CFG enhancement. * * @author Hossein Sadat-Mohtasham Feb 2010 */ @SuppressWarnings("serial") class ExitStmt extends JNopStmt { public ExitStmt() { } @Override public Object clone() { return new ExitStmt(); } @Override public boolean fallsThrough() { return true; } @Override public boolean branches() { return false; } }
17,727
29.460481
125
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/HashMutablePDG.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; import soot.Body; import soot.SootClass; import soot.toolkits.graph.Block; import soot.toolkits.graph.BlockGraph; import soot.toolkits.graph.DominatorNode; import soot.toolkits.graph.DominatorTree; import soot.toolkits.graph.HashMutableEdgeLabelledDirectedGraph; import soot.toolkits.graph.UnitGraph; /** * This class implements a Program Dependence Graph as defined in * * Ferrante, J., Ottenstein, K. J., and Warren, J. D. 1987. The program dependence graph and its use in optimization. ACM * Trans. Program. Lang. Syst. 9, 3 (Jul. 1987), 319-349. DOI= http://doi.acm.org/10.1145/24039.24041 * * Note: the implementation is not exactly as in the above paper. It first finds the regions of control dependence then uses * part of the algorithm given in the above paper to build the graph. * * The constructor accepts a UnitGraph, which can be a BriefUnitGraph, an ExceptionalUnitGraph, or an EnhancedUnitGraph. At * the absence of exception handling constructs in a method, all of these work the same. However, at the presence of * exception handling constructs, BriefUnitGraph is multi-headed and potentially multi-tailed which makes the results of * RegionAnalysis and PDG construction unreliable (It's not clear if it would be useful anyway); Also, ExceptionalGraph's * usefulness when exception handling is present is not so clear since almost every unit can throw exception hence the * dependency is affected. Currently, the PDG is based on a UnitGraph (BlockGraph) and does not care whether flow is * exceptional or not. * * The nodes in a PDG are of type PDGNode and the edges can have three labels: "dependency", "dependency-back", and * "controlflow"; however, the "controlflow" edges are auxiliary and the dependencies are represented by the labels beginning * with "dependency". Other labels can be added later for application or domain-specific cases. * * * To support methods that contain exception-handling and multiple-heads or tails, use EnhancedUnitGraph. It does not * represent exceptional flow in the way ExceptionalUnitGraph does, but it integrates them in a concise way. Also, it adds * START/STOP nodes to graph if necessary to make the graph single entry single exit. * * @author Hossein Sadat-Mohtasham Sep 2009 */ public class HashMutablePDG extends HashMutableEdgeLabelledDirectedGraph<PDGNode, String> implements ProgramDependenceGraph { protected Body m_body = null; protected SootClass m_class = null; protected UnitGraph m_cfg = null; protected BlockGraph m_blockCFG = null; protected Hashtable<Object, PDGNode> m_obj2pdgNode = new Hashtable<Object, PDGNode>(); protected List<Region> m_weakRegions = null; protected List<Region> m_strongRegions = null; protected PDGNode m_startNode = null; protected List<PDGRegion> m_pdgRegions = null; private RegionAnalysis m_regionAnalysis = null; private int m_strongRegionStartID; public HashMutablePDG(UnitGraph cfg) { this.m_body = cfg.getBody(); this.m_class = this.m_body.getMethod().getDeclaringClass(); this.m_cfg = cfg; this.m_regionAnalysis = new RegionAnalysis(this.m_cfg, this.m_body.getMethod(), this.m_class); /* * Get the weak regions and save a copy. Note that the strong regions list is initially cloned from the weak region to be * later modified. */ this.m_strongRegions = this.m_regionAnalysis.getRegions(); this.m_weakRegions = this.cloneRegions(this.m_strongRegions); this.m_blockCFG = this.m_regionAnalysis.getBlockCFG(); // Construct the PDG this.constructPDG(); this.m_pdgRegions = HashMutablePDG.computePDGRegions(this.m_startNode); /* * This is needed to convert the initially Region-typed inner node of the PDG's head to a PDGRegion-typed one after the * whole graph is computed. The root PDGRegion is the one with no parent. */ IRegion r = this.m_pdgRegions.get(0); while (r.getParent() != null) { r = r.getParent(); } this.m_startNode.setNode(r); } @Override public BlockGraph getBlockGraph() { return m_blockCFG; } /** * This is the heart of the PDG construction. It is huge and definitely needs some refactorings, but since it's been * evolving to cover some boundary cases it has become hard to refactor. * * It uses the list of weak regions, along with the dominator and post-dominator trees to construct the PDG nodes. */ protected void constructPDG() { Hashtable<Block, Region> block2region = this.m_regionAnalysis.getBlock2RegionMap(); DominatorTree<Block> pdom = this.m_regionAnalysis.getPostDominatorTree(); DominatorTree<Block> dom = this.m_regionAnalysis.getDominatorTree(); List<Region> regions2process = new LinkedList<Region>(); Region topLevelRegion = this.m_regionAnalysis.getTopLevelRegion(); m_strongRegionStartID = m_weakRegions.size(); // This becomes the top-level region (or ENTRY region node) PDGNode pdgnode = new PDGNode(topLevelRegion, PDGNode.Type.REGION); this.addNode(pdgnode); this.m_obj2pdgNode.put(topLevelRegion, pdgnode); this.m_startNode = pdgnode; topLevelRegion.setParent(null); Set<Region> processedRegions = new HashSet<Region>(); regions2process.add(topLevelRegion); // while there's a (weak) region to process while (!regions2process.isEmpty()) { Region r = regions2process.remove(0); processedRegions.add(r); // get the corresponding pdgnode pdgnode = this.m_obj2pdgNode.get(r); // For all the CFG nodes in the region, create the corresponding PDG node and edges, and process // them if they are in the dependence set of other regions, i.e. other regions depend on them. List<Block> blocks = r.getBlocks(); Hashtable<Region, List<Block>> toBeRemoved = new Hashtable<Region, List<Block>>(); PDGNode prevPDGNodeInRegion = null; PDGNode curNodeInRegion; for (Block a : blocks) { // Add the PDG node corresponding to the CFG block node. PDGNode pdgNodeOfA; if (!this.m_obj2pdgNode.containsKey(a)) { pdgNodeOfA = new PDGNode(a, PDGNode.Type.CFGNODE); this.addNode(pdgNodeOfA); this.m_obj2pdgNode.put(a, pdgNodeOfA); } else { pdgNodeOfA = this.m_obj2pdgNode.get(a); } this.addEdge(pdgnode, pdgNodeOfA, "dependency"); pdgnode.addDependent(pdgNodeOfA); // curNodeInRegion = pdgNodeOfA; // For each successor B of A, if B does not post-dominate A, add all the // nodes on the path from B to the L in the post-dominator tree, where // L is the least common ancestor of A and B in the post-dominator tree // (L will be either A itself or the parent of A.). for (Block b : this.m_blockCFG.getSuccsOf(a)) { if (b.equals(a)) { // throw new RuntimeException("PDG construction: A and B are not supposed to be the same node!"); continue; } DominatorNode<Block> aDode = pdom.getDode(a); DominatorNode<Block> bDode = pdom.getDode(b); // If B post-dominates A, go to the next successor. if (pdom.isDominatorOf(bDode, aDode)) { continue; } List<Block> dependents = new ArrayList<Block>(); // FIXME: what if the parent is null?!! DominatorNode<Block> aParentDode = aDode.getParent(); DominatorNode<Block> dode = bDode; while (dode != aParentDode) { dependents.add(dode.getGode()); // This occurs if the CFG is multi-tailed and therefore the pdom is a forest. if (dode.getParent() == null) { // throw new RuntimeException("parent dode in pdom is null: dode is " + aDode); break; } dode = dode.getParent(); } // If node A is in the dependent list of A, then A is the header of a loop. // Otherwise, A could still be the header of a loop or just a simple predicate. // // first make A's pdg node be a conditional (predicate) pdgnode, if it's not already. if (pdgNodeOfA.getAttrib() != PDGNode.Attribute.CONDHEADER) { PDGNode oldA = pdgNodeOfA; pdgNodeOfA = new ConditionalPDGNode(pdgNodeOfA); this.replaceInGraph(pdgNodeOfA, oldA); pdgnode.removeDependent(oldA); this.m_obj2pdgNode.put(a, pdgNodeOfA); pdgnode.addDependent(pdgNodeOfA); pdgNodeOfA.setAttrib(PDGNode.Attribute.CONDHEADER); curNodeInRegion = pdgNodeOfA; } List<Block> copyOfDependents = new ArrayList<Block>(dependents); // First, add the dependency for B and its corresponding region. Region regionOfB = block2region.get(b); PDGNode pdgnodeOfBRegion; if (this.m_obj2pdgNode.containsKey(regionOfB)) { pdgnodeOfBRegion = this.m_obj2pdgNode.get(regionOfB); } else { pdgnodeOfBRegion = new PDGNode(regionOfB, PDGNode.Type.REGION); this.addNode(pdgnodeOfBRegion); this.m_obj2pdgNode.put(regionOfB, pdgnodeOfBRegion); } // set the region hierarchy regionOfB.setParent(r); r.addChildRegion(regionOfB); // add the dependency edges this.addEdge(pdgNodeOfA, pdgnodeOfBRegion, "dependency"); pdgNodeOfA.addDependent(pdgnodeOfBRegion); if (!processedRegions.contains(regionOfB)) { regions2process.add(regionOfB); } // now remove b and all the nodes in the same weak region from the list of dependents copyOfDependents.remove(b); copyOfDependents.removeAll(regionOfB.getBlocks()); /* * What remains here in the dependence set needs to be processed separately. For each node X remained in the * dependency set, find the corresponding PDG region node and add a dependency edge from the region of B to the * region of X. If X's weak region contains other nodes not in the dependency set of A, create a new region for X * and add the proper dependency edges (this actually happens if X is the header of a loop and B is a predicate * guarding a break/continue.) * * Note: it seems the only case that there is a node remained in the dependents is when there is a path from b to * the header of a loop. */ while (!copyOfDependents.isEmpty()) { Block depB = copyOfDependents.remove(0); Region rdepB = block2region.get(depB); // Actually, there are cases when depB is not the header of a loop // and therefore would not dominate the current node (A) and therefore // might not have been created yet. This has happened when an inner // loop breaks out of the outer loop but could have other cases too. PDGNode depBPDGNode = this.m_obj2pdgNode.get(depB); if (depBPDGNode == null) { // First, add the dependency for depB and its corresponding region. PDGNode pdgnodeOfdepBRegion; if (this.m_obj2pdgNode.containsKey(rdepB)) { pdgnodeOfdepBRegion = this.m_obj2pdgNode.get(rdepB); } else { pdgnodeOfdepBRegion = new PDGNode(rdepB, PDGNode.Type.REGION); this.addNode(pdgnodeOfdepBRegion); this.m_obj2pdgNode.put(rdepB, pdgnodeOfdepBRegion); } // set the region hierarchy rdepB.setParent(regionOfB); regionOfB.addChildRegion(rdepB); // add the dependency edges this.addEdge(pdgnodeOfBRegion, pdgnodeOfdepBRegion, "dependency"); pdgnodeOfBRegion.addDependent(pdgnodeOfdepBRegion); if (!processedRegions.contains(rdepB)) { regions2process.add(rdepB); } // now remove all the nodes in the same weak region from the list of dependents copyOfDependents.removeAll(rdepB.getBlocks()); } else if (dependents.containsAll(rdepB.getBlocks())) { /* * If all the nodes in the weak region of depB are dependent on A, then add an edge from the region of B to the * region of depB. Else, a new region has to be created to contain the dependences of depB, if not already * created. */ // Just add an edge to the pdg node of the existing depB region. // // add the dependency edges // First, add the dependency for depB and its corresponding region. PDGNode pdgnodeOfdepBRegion; if (this.m_obj2pdgNode.containsKey(rdepB)) { pdgnodeOfdepBRegion = this.m_obj2pdgNode.get(rdepB); } else { pdgnodeOfdepBRegion = new PDGNode(rdepB, PDGNode.Type.REGION); this.addNode(pdgnodeOfdepBRegion); this.m_obj2pdgNode.put(rdepB, pdgnodeOfdepBRegion); } // set the region hierarchy // Do not set this because the region was created before so must have the // proper parent already. // rdepB.setParent(regionOfB); // regionOfB.addChildRegion(rdepB); this.addEdge(pdgnodeOfBRegion, pdgnodeOfdepBRegion, "dependency"); pdgnodeOfBRegion.addDependent(pdgnodeOfdepBRegion); if (!processedRegions.contains(rdepB)) { regions2process.add(rdepB); } // now remove all the nodes in the same weak region from the list of dependents copyOfDependents.removeAll(rdepB.getBlocks()); } else { PDGNode predPDGofdepB = this.getPredsOf(depBPDGNode).get(0); assert (this.m_obj2pdgNode.containsKey(rdepB)); PDGNode pdgnodeOfdepBRegion = this.m_obj2pdgNode.get(rdepB); // If the loop header has not been separated from its weak region yet if (predPDGofdepB == pdgnodeOfdepBRegion) { // Create a new region to represent the whole loop. In fact, this is a strong region as opposed to the weak // regions that were created in the RegionAnalysis. This strong region only contains the header of the loop, // A, and is dependent on it. Also, A is dependent on this strong region as well. Region newRegion = new Region(this.m_strongRegionStartID++, topLevelRegion.getSootMethod(), topLevelRegion.getSootClass(), this.m_cfg); newRegion.add(depB); this.m_strongRegions.add(newRegion); // toBeRemoved.add(depB); List<Block> blocks2BRemoved; if (toBeRemoved.contains(predPDGofdepB)) { blocks2BRemoved = toBeRemoved.get(predPDGofdepB); } else { blocks2BRemoved = new ArrayList<Block>(); toBeRemoved.put(rdepB, blocks2BRemoved); } blocks2BRemoved.add(depB); PDGNode newpdgnode = new LoopedPDGNode(newRegion, PDGNode.Type.REGION, depBPDGNode); this.addNode(newpdgnode); this.m_obj2pdgNode.put(newRegion, newpdgnode); newpdgnode.setAttrib(PDGNode.Attribute.LOOPHEADER); depBPDGNode.setAttrib(PDGNode.Attribute.LOOPHEADER); this.removeEdge(pdgnodeOfdepBRegion, depBPDGNode, "dependency"); pdgnodeOfdepBRegion.removeDependent(depBPDGNode); this.addEdge(pdgnodeOfdepBRegion, newpdgnode, "dependency"); this.addEdge(newpdgnode, depBPDGNode, "dependency"); pdgnodeOfdepBRegion.addDependent(newpdgnode); newpdgnode.addDependent(depBPDGNode); // If a is dependent on itself (simple loop) if (depB == a) { PDGNode loopBodyPDGNode = this.getSuccsOf(depBPDGNode).get(0); this.addEdge(depBPDGNode, newpdgnode, "dependency-back"); ((LoopedPDGNode) newpdgnode).setBody(loopBodyPDGNode); depBPDGNode.addBackDependent(newpdgnode); // This is needed to correctly adjust the prev/next pointers for the new loop node. We should not need // to adjust the old loop header node because the prev/next should not have been set previously for it. curNodeInRegion = newpdgnode; } else { // this is a back-dependency pdgnodeOfBRegion.addBackDependent(newpdgnode); this.addEdge(pdgnodeOfBRegion, newpdgnode, "dependency-back"); // Determine which dependent of the loop header is actually the loop body region PDGNode loopBodyPDGNode = null; for (PDGNode succRPDGNode : this.getSuccsOf(depBPDGNode)) { if (succRPDGNode.getType() == PDGNode.Type.REGION) { Region succR = (Region) succRPDGNode.getNode(); Block h = succR.getBlocks().get(0); if (dom.isDominatorOf(dom.getDode(h), dom.getDode(a))) { loopBodyPDGNode = succRPDGNode; break; } } } assert (loopBodyPDGNode != null); ((LoopedPDGNode) newpdgnode).setBody(loopBodyPDGNode); PDGNode prev = depBPDGNode.getPrev(); if (prev != null) { this.removeEdge(prev, depBPDGNode, "controlflow"); this.addEdge(prev, newpdgnode, "controlflow"); prev.setNext(newpdgnode); newpdgnode.setPrev(prev); depBPDGNode.setPrev(null); } PDGNode next = depBPDGNode.getNext(); if (next != null) { this.removeEdge(depBPDGNode, next, "controlflow"); this.addEdge(newpdgnode, next, "controlflow"); newpdgnode.setNext(next); next.setPrev(newpdgnode); depBPDGNode.setNext(null); } } } else { // The strong region for the header has already been created and // its corresponding PDGNode exist. Just add the dependency edge. this.addEdge(pdgnodeOfBRegion, predPDGofdepB, "dependency-back"); // this is a back-dependency pdgnodeOfBRegion.addBackDependent(predPDGofdepB); } } } } // If there is a previous node in this region, add a control flow edge // to indicate the correct direction of control flow in the region. if (prevPDGNodeInRegion != null) { this.addEdge(prevPDGNodeInRegion, curNodeInRegion, "controlflow"); prevPDGNodeInRegion.setNext(curNodeInRegion); curNodeInRegion.setPrev(prevPDGNodeInRegion); } prevPDGNodeInRegion = curNodeInRegion; } // remove all the blocks marked to be removed from the region (to change a weak region // to a strong region.) for (Enumeration<Region> itr = toBeRemoved.keys(); itr.hasMoreElements();) { Region region = itr.nextElement(); for (Block next : toBeRemoved.get(region)) { region.remove(next); } } } } private List<Region> cloneRegions(List<Region> weak) { List<Region> strong = new ArrayList<Region>(); for (Region r : weak) { strong.add((Region) r.clone()); } return strong; } /** * * @return The Corresponding UnitGraph */ public UnitGraph getCFG() { return this.m_cfg; } /** * {@inheritDoc} */ @Override public List<Region> getWeakRegions() { return this.m_weakRegions; } /** * {@inheritDoc} */ @Override public List<Region> getStrongRegions() { return this.m_strongRegions; } /** * {@inheritDoc} */ @Override public IRegion GetStartRegion() { return (IRegion) GetStartNode().getNode(); } /** * {@inheritDoc} */ @Override public PDGNode GetStartNode() { return this.m_startNode; } public static List<IRegion> getPreorderRegionList(IRegion r) { List<IRegion> list = new ArrayList<IRegion>(); Queue<IRegion> toProcess = new LinkedList<IRegion>(); toProcess.add(r); while (!toProcess.isEmpty()) { IRegion reg = toProcess.poll(); list.add(reg); for (IRegion next : reg.getChildRegions()) { toProcess.add((Region) next); } } return list; } public static List<IRegion> getPostorderRegionList(IRegion r) { List<IRegion> list = new ArrayList<IRegion>(); postorder(r, list); return list; } private static List<IRegion> postorder(IRegion r, List<IRegion> list) { // If there are children, push the children to the stack for (IRegion next : r.getChildRegions()) { postorder(next, list); } list.add(r); return list; } /** * {@inheritDoc} */ @Override public List<PDGRegion> getPDGRegions() { return this.m_pdgRegions; } /** * This method returns a list of regions obtained by post-order traversal of the region hierarchy. This takes advantage of * the hierarchical (parent/child) information encoded within the PDGNodes at construction time; it should be noted that, * we have not counted the strong regions that represent the loop header as a separate region; instead, a PDGRegion that * represents both the loop header and its body are counted. * * @param root * The root node from which the traversal should begin. * * @return The list of regions obtained thru post-order traversal of the region hierarchy. */ public static List<PDGRegion> getPostorderPDGRegionList(PDGNode root) { return computePDGRegions(root); } private static Hashtable<PDGNode, PDGRegion> node2Region = new Hashtable<PDGNode, PDGRegion>(); // compute the pdg region list with in post order private static List<PDGRegion> computePDGRegions(PDGNode root) { List<PDGRegion> regions = new ArrayList<PDGRegion>(); node2Region.clear(); pdgpostorder(root, regions); return regions; } private static PDGRegion pdgpostorder(PDGNode node, List<PDGRegion> list) { if (node.getVisited()) { return null; } node.setVisited(true); PDGRegion region; if (!node2Region.containsKey(node)) { region = new PDGRegion(node); node2Region.put(node, region); } else { region = node2Region.get(node); } // If there are children, push the children to the stack for (PDGNode curNode : node.getDependents()) { if (curNode.getVisited()) { continue; } region.addPDGNode(curNode); if (curNode instanceof LoopedPDGNode) { PDGNode body = ((LoopedPDGNode) curNode).getBody(); PDGRegion kid = pdgpostorder(body, list); if (kid != null) { kid.setParent(region); region.addChildRegion(kid); // This sets the node from the old Region into a PDGRegion body.setNode(kid); } } else if (curNode instanceof ConditionalPDGNode) { for (PDGNode child : curNode.getDependents()) { PDGRegion kid = pdgpostorder(child, list); if (kid != null) { kid.setParent(region); region.addChildRegion(kid); // This sets the node from the old Region into a PDGRegion child.setNode(kid); } } } } list.add(region); return region; } /** * {@inheritDoc} */ @Override public boolean dependentOn(PDGNode node1, PDGNode node2) { return node2.getDependents().contains(node1); } /** * {@inheritDoc} */ @Override public List<PDGNode> getDependents(PDGNode node) { List<PDGNode> toReturn = new ArrayList<PDGNode>(); for (PDGNode succ : this.getSuccsOf(node)) { if (this.dependentOn(succ, node)) { toReturn.add(succ); } } return toReturn; } /** * {@inheritDoc} */ @Override public PDGNode getPDGNode(Object cfgNode) { if (cfgNode != null && cfgNode instanceof Block) { if (this.m_obj2pdgNode.containsKey(cfgNode)) { return this.m_obj2pdgNode.get(cfgNode); } } return null; } private void replaceInGraph(PDGNode newnode, PDGNode oldnode) { this.addNode(newnode); HashMutableEdgeLabelledDirectedGraph<PDGNode, String> graph = clone(); for (PDGNode succ : graph.getSuccsOf(oldnode)) { for (Object label : graph.getLabelsForEdges(oldnode, succ)) { this.addEdge(newnode, succ, label.toString()); } } for (PDGNode pred : graph.getPredsOf(oldnode)) { for (Object label : graph.getLabelsForEdges(pred, oldnode)) { this.addEdge(pred, newnode, label.toString()); } } this.removeNode(oldnode); } /** * The existing removeAllEdges in the parent class seems to be throwing concurrentmodification exception most of the time. * Here is a version that doesn't throw that exception. * */ @Override public void removeAllEdges(PDGNode from, PDGNode to) { if (containsAnyEdge(from, to)) { for (String label : new ArrayList<String>(this.getLabelsForEdges(from, to))) { this.removeEdge(from, to, label); } } } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\nProgram Dependence Graph for Method ").append(this.m_body.getMethod().getName()) .append("\n*********CFG******** \n").append(RegionAnalysis.CFGtoString(this.m_blockCFG, true)) .append("\n*********PDG******** \n"); List<PDGNode> processed = new ArrayList<PDGNode>(); Queue<PDGNode> nodes = new LinkedList<PDGNode>(); nodes.offer(this.m_startNode); while (nodes.peek() != null) { PDGNode node = nodes.remove(); processed.add(node); sb.append("\n Begin PDGNode: ").append(node); List<PDGNode> succs = this.getSuccsOf(node); sb.append("\n has ").append(succs.size()).append(" successors:\n"); int i = 0; for (PDGNode succ : succs) { List<String> labels = this.getLabelsForEdges(node, succ); sb.append(i++); sb.append(": Edge's label: ").append(labels).append(" \n"); sb.append(" Target: ").append(succ.toShortString()); sb.append('\n'); if ("dependency".equals(labels.get(0))) { if (!processed.contains(succ)) { nodes.offer(succ); } } } sb.append("\n End PDGNode."); } return sb.toString(); } }
28,182
38.088766
125
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/IRegion.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.toolkits.graph.Block; import soot.toolkits.graph.UnitGraph; /** * This interface represents a region of control dependence in the control flow graph. There are different kinds of region * representations that may slightly differ in definition or implementation; here is an interface that is expected to be * supported by all these different regions. * * * @author Hossein Sadat-Mohtasham Jan 2009 */ public interface IRegion { public SootMethod getSootMethod(); public SootClass getSootClass(); public UnitGraph getUnitGraph(); public List<Unit> getUnits(); public List<Unit> getUnits(Unit from, Unit to); public List<Block> getBlocks(); public Unit getLast(); public Unit getFirst(); public int getID(); public boolean occursBefore(Unit u1, Unit u2); public void setParent(IRegion pr); public IRegion getParent(); public void addChildRegion(IRegion chr); public List<IRegion> getChildRegions(); }
1,900
25.041096
122
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/LoopedPDGNode.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy 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 represents a loop in the PDG. * */ public class LoopedPDGNode extends PDGNode { protected PDGNode m_header = null; protected PDGNode m_body = null; public LoopedPDGNode(Region obj, Type t, PDGNode c) { super(obj, t); this.m_header = c; } public PDGNode getHeader() { return this.m_header; } public void setBody(PDGNode b) { this.m_body = b; } public PDGNode getBody() { return this.m_body; } }
1,307
23.679245
71
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/MHGDominatorTree.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.toolkits.graph.DominatorTree; import soot.toolkits.graph.DominatorsFinder; /** * Constructs a multi-headed dominator tree. This is mostly the same as the DominatorTree but the buildTree method is changed * to allow multiple heads. This can be used for graphs that are multi-headed and cannot be augmented to become * single-headed. * * March 2014: Pulled this code into the original {@link DominatorTree}. This class now became a stub (Steven Arzt). * * @author Hossein Sadat-Mohtasham March 2009 */ @Deprecated public class MHGDominatorTree<N> extends DominatorTree<N> { public MHGDominatorTree(DominatorsFinder<N> dominators) { super(dominators); } }
1,532
33.840909
125
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/PDGNode.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import soot.toolkits.graph.Block; /** * * This class defines a Node in the Program Dependence Graph. There might be a need to store additional information in the * PDG nodes. In essence, the PDG nodes represent (within them) either CFG nodes or Region nodes. * * * * @author Hossein Sadat-Mohtasham June 2009 */ public class PDGNode { public enum Type { REGION, CFGNODE }; public enum Attribute { NORMAL, ENTRY, CONDHEADER, LOOPHEADER }; protected Type m_type; protected Object m_node = null; protected List<PDGNode> m_dependents = new ArrayList<PDGNode>(); protected List<PDGNode> m_backDependents = new ArrayList<PDGNode>(); // This is used to keep an ordered list of the nodes in a region, based on the control-flow // between them (if any). protected PDGNode m_next = null; protected PDGNode m_prev = null; protected Attribute m_attrib = Attribute.NORMAL; public PDGNode(Object obj, Type t) { this.m_node = obj; this.m_type = t; } public Type getType() { return this.m_type; } public void setType(Type t) { this.m_type = t; } public Object getNode() { return this.m_node; } public void setNext(PDGNode n) { this.m_next = n; } public PDGNode getNext() { return this.m_next; } public void setPrev(PDGNode n) { this.m_prev = n; } public PDGNode getPrev() { return this.m_prev; } // The following is used to keep track of the nodes that are visited in post-order traversal. This should // probably be moved into an aspect. protected boolean m_visited = false; public void setVisited(boolean v) { this.m_visited = v; } public boolean getVisited() { return this.m_visited; } public void setNode(Object obj) { this.m_node = obj; } public Attribute getAttrib() { return this.m_attrib; } public void setAttrib(Attribute a) { this.m_attrib = a; } public void addDependent(PDGNode node) { if (!this.m_dependents.contains(node)) { this.m_dependents.add(node); } } public void addBackDependent(PDGNode node) { this.m_backDependents.add(node); } public void removeDependent(PDGNode node) { this.m_dependents.remove(node); } public List<PDGNode> getDependents() { return this.m_dependents; } public List<PDGNode> getBackDependets() { return this.m_backDependents; } public String toString() { String s = new String(); s = "Type: " + ((this.m_type == Type.REGION) ? "REGION: " : "CFGNODE: "); s += this.m_node; return s; } public String toShortString() { String s = new String(); s = "Type: " + ((this.m_type == Type.REGION) ? "REGION: " : "CFGNODE: "); if (this.m_type == Type.REGION) { s += ((IRegion) this.m_node).getID(); } else { s += ((Block) this.m_node).toShortString(); } return s; } }
3,780
22.484472
122
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/PDGRegion.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.options.Options; import soot.toolkits.graph.Block; import soot.toolkits.graph.UnitGraph; /** * This represents a region of control dependence obtained by constructing a program dependence graph. A PDGRegion is * slightly different than a weak or strong region; the loops and conditional relations between regions are explicitly * represented in the PDGRegion. * * @author Hossein Sadat-Mohtasham Sep 2009 */ public class PDGRegion implements IRegion, Iterable<PDGNode> { private static final Logger logger = LoggerFactory.getLogger(PDGRegion.class); private SootClass m_class = null; private SootMethod m_method = null; private List<PDGNode> m_nodes = null; private List<Unit> m_units = null; private LinkedHashMap<Unit, PDGNode> m_unit2pdgnode = null; private int m_id = -1; private UnitGraph m_unitGraph = null; private PDGNode m_corrspondingPDGNode = null; // The following are needed to create a tree of regions based on the containment (dependency) // relation between regions. private IRegion m_parent = null; // The following keeps the child regions private List<IRegion> m_children = new ArrayList<IRegion>(); public PDGRegion(int id, SootMethod m, SootClass c, UnitGraph ug, PDGNode node) { this(id, new ArrayList<PDGNode>(), m, c, ug, node); } public PDGRegion(int id, List<PDGNode> nodes, SootMethod m, SootClass c, UnitGraph ug, PDGNode node) { this.m_nodes = nodes; this.m_id = id; this.m_method = m; this.m_class = c; this.m_unitGraph = ug; this.m_units = null; this.m_corrspondingPDGNode = node; if (Options.v().verbose()) { logger.debug("New pdg region create: " + id); } } public PDGRegion(PDGNode node) { this(((IRegion) node.getNode()).getID(), (List<PDGNode>) new ArrayList<PDGNode>(), ((IRegion) node.getNode()).getSootMethod(), ((IRegion) node.getNode()).getSootClass(), ((IRegion) node.getNode()).getUnitGraph(), node); } public PDGNode getCorrespondingPDGNode() { return this.m_corrspondingPDGNode; } @SuppressWarnings("unchecked") public Object clone() { PDGRegion r = new PDGRegion(this.m_id, this.m_method, this.m_class, this.m_unitGraph, m_corrspondingPDGNode); r.m_nodes = (List<PDGNode>) ((ArrayList<PDGNode>) this.m_nodes).clone(); return r; } public SootMethod getSootMethod() { return this.m_method; } public SootClass getSootClass() { return this.m_class; } public List<PDGNode> getNodes() { return this.m_nodes; } public UnitGraph getUnitGraph() { return this.m_unitGraph; } /** * This is an iterator that knows how to follow the control flow in a region. It only iterates through the dependent nodes * that contribute to the list of units in a region as defined by a weak region. * */ class ChildPDGFlowIterator implements Iterator<PDGNode> { List<PDGNode> m_list = null; PDGNode m_current = null; boolean beginning = true; public ChildPDGFlowIterator(List<PDGNode> list) { m_list = list; } public boolean hasNext() { if (beginning) { if (m_list.size() > 0) { return true; } } return (m_current != null && m_current.getNext() != null); } public PDGNode next() { if (beginning) { beginning = false; m_current = m_list.get(0); // Find the first node in the control flow /* * There cannot be more than one CFG node in a region unless there is a control flow edge between them. However, * there could be a CFG node and other region nodes (back dependency, or other.) In such cases, the one CFG node * should be found and returned, and other region nodes should be ignored. Unless it's a LoopedPDGNode (in which case * control flow edge should still exist if there are other sibling Looped PDGNodes or CFG nodes.) * */ while (m_current.getPrev() != null) { m_current = m_current.getPrev(); } if (m_current.getType() != PDGNode.Type.CFGNODE && m_current.getAttrib() != PDGNode.Attribute.LOOPHEADER) { /* * Look for useful dependence whose units are considered to be part of this region (loop header or CFG block * nodes.) * */ for (Iterator<PDGNode> depItr = m_list.iterator(); depItr.hasNext();) { PDGNode dep = depItr.next(); if (dep.getType() == PDGNode.Type.CFGNODE || dep.getAttrib() == PDGNode.Attribute.LOOPHEADER) { m_current = dep; // go to the beginning of the flow while (m_current.getPrev() != null) { m_current = m_current.getPrev(); } break; } } } return m_current; } if (!hasNext()) { throw new RuntimeException("No more nodes!"); } m_current = m_current.getNext(); return m_current; } public void remove() { } } /** * return an iterator that know how to follow the control flow in a region. This actually returns a ChildPDGFlowIterator * that only iterates through the dependent nodes that contribute to the units that belong to a region as defined by a weak * region. * */ public Iterator<PDGNode> iterator() { return new ChildPDGFlowIterator(this.m_nodes); } public List<Unit> getUnits() { if (this.m_units == null) { this.m_units = new LinkedList<Unit>(); this.m_unit2pdgnode = new LinkedHashMap<Unit, PDGNode>(); for (Iterator<PDGNode> itr = this.iterator(); itr.hasNext();) { PDGNode node = itr.next(); if (node.getType() == PDGNode.Type.REGION) { // Actually, we should only get here if a loop header region is in this region's children list. // Or if the PDG is based on an ExceptionalUnitGraph, then this could be the region corresponding // to a handler, in which case it's ignored. // if(node.getAttrib() == PDGNode.Attribute.LOOPHEADER) if (node instanceof LoopedPDGNode) { LoopedPDGNode n = (LoopedPDGNode) node; PDGNode header = n.getHeader(); Block headerBlock = (Block) header.getNode(); for (Iterator<Unit> itr1 = headerBlock.iterator(); itr1.hasNext();) { Unit u = itr1.next(); ((LinkedList<Unit>) this.m_units).addLast(u); this.m_unit2pdgnode.put(u, header); } } } else if (node.getType() == PDGNode.Type.CFGNODE) { Block b = (Block) node.getNode(); for (Iterator<Unit> itr1 = b.iterator(); itr1.hasNext();) { Unit u = itr1.next(); ((LinkedList<Unit>) this.m_units).addLast(u); this.m_unit2pdgnode.put(u, node); } } else { throw new RuntimeException("Exception in PDGRegion.getUnits: PDGNode's type is undefined!"); } } } return this.m_units; } /** * * @param a * Statement within the region * * @return The PDGNode that contains that unit, if this unit is in this region. */ public PDGNode unit2PDGNode(Unit u) { if (this.m_unit2pdgnode.containsKey(u)) { return this.m_unit2pdgnode.get(u); } else { return null; } } public List<Unit> getUnits(Unit from, Unit to) { return m_units.subList(m_units.indexOf(from), m_units.indexOf(to)); } public Unit getLast() { if (this.m_units != null) { if (this.m_units.size() > 0) { return ((LinkedList<Unit>) this.m_units).getLast(); } } return null; } public Unit getFirst() { if (this.m_units != null) { if (this.m_units.size() > 0) { return ((LinkedList<Unit>) this.m_units).getFirst(); } } return null; } // FIXME: return the real list of blocks public List<Block> getBlocks() { return new ArrayList<Block>(); } public void addPDGNode(PDGNode node) { this.m_nodes.add(node); } public int getID() { return this.m_id; } public boolean occursBefore(Unit u1, Unit u2) { int i = this.m_units.lastIndexOf(u1); int j = this.m_units.lastIndexOf(u2); if (i == -1 || j == -1) { throw new RuntimeException("These units don't exist in the region!"); } return i < j; } public void setParent(IRegion pr) { this.m_parent = pr; } public IRegion getParent() { return this.m_parent; } public void addChildRegion(IRegion chr) { if (!this.m_children.contains(chr)) { this.m_children.add(chr); } } public List<IRegion> getChildRegions() { return this.m_children; } public String toString() { String str = new String(); str += "Begin-----------PDGRegion: " + this.m_id + "-------------\n"; if (this.m_parent != null) { str += "Parent is: " + this.m_parent.getID() + "----\n"; } str += "Children Regions are: "; for (Iterator<IRegion> ritr = this.m_children.iterator(); ritr.hasNext();) { str += ((IRegion) ritr.next()).getID() + ", "; } str += "\nUnits are: \n"; List<Unit> regionUnits = this.getUnits(); for (Iterator<Unit> itr = regionUnits.iterator(); itr.hasNext();) { Unit u = itr.next(); str += u + "\n"; } str += "End of PDG Region " + this.m_id + " -----------------------------\n"; return str; } }
10,599
28.120879
125
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/ProgramDependenceGraph.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.toolkits.graph.BlockGraph; import soot.toolkits.graph.MutableEdgeLabelledDirectedGraph; /** * * This defines the interface to a Program Dependence Graph as defined in * * Ferrante, J., Ottenstein, K. J., and Warren, J. D. 1987. The program dependence graph and its use in optimization. ACM * Trans. Program. Lang. Syst. 9, 3 (Jul. 1987), 319-349. DOI= http://doi.acm.org/10.1145/24039.24041 * * Note that this interface should evolve based on the need. * * @author Hossein Sadat-Mohtasham May 2009 */ public interface ProgramDependenceGraph extends MutableEdgeLabelledDirectedGraph<PDGNode, String> { /** * @return A List of weak regions, generated by RegionAnalysis for the corresponding control flow graph (These are Regions * and not PDGRegions.) */ public List<Region> getWeakRegions(); /** * @return A List of strong regions, generated when constructing the program dependence graph (These are Regions and not * PDGRegions.) */ public List<Region> getStrongRegions(); /** * This method returns the list of PDGRegions computed by the construction method. * * @return The list of PDGRegions */ public List<PDGRegion> getPDGRegions(); /** * @return The root region of the PDG. */ public IRegion GetStartRegion(); public BlockGraph getBlockGraph(); /** * @return The root node of the PDG, which is essentially the same as the start region but packaged in its PDGNode, which * can be used to traverse the graph, etc. */ public PDGNode GetStartNode(); /** * This method determines if node1 is control-dependent on node2 in this PDG. * * @param node1 * @param node2 * @return returns true if node1 is dependent on node2 */ public boolean dependentOn(PDGNode node1, PDGNode node2); /** * This method returns the list of all dependents of a node in the PDG. * * @param node * is the PDG node whose dependents are desired. * @return a list of dependent nodes */ public List<PDGNode> getDependents(PDGNode node); /** * This method returns the PDGNode in the PDG corresponding to the given CFG node. Note that currently the CFG node has to * be a Block. * * @param cfgNode * is expected to be a node in CFG (currently only Block). * @return The node in PDG corresponding to cfgNode. */ public PDGNode getPDGNode(Object cfgNode); /** * * @return A human readable description of the PDG. */ @Override public String toString(); }
3,420
29.81982
124
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/Region.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.toolkits.graph.Block; import soot.toolkits.graph.UnitGraph; /** * This class was originally designed to represent a weak region. Later, PDGRegion was designed to represent a richer region * representation but since there were cases that we wanted to enforce the use of Region instead of PDGRegion, and for some * other compatibility issues, we chose not to eliminate this class and even not to factor it into a common abstract class. * * One major contributing factor to the above is that, a Region can exist independent from a PDG since they are generated by * RegionAnalysis, whereas a PDGRegion is generated by a PDG. * * @author Hossein Sadat-Mohtasham Jan 2009 */ public class Region implements IRegion { private SootClass m_class = null; private SootMethod m_method = null; private List<Block> m_blocks = null; private List<Unit> m_units = null; private int m_id = -1; private UnitGraph m_unitGraph = null; // The following are needed to create a tree of regions based on the containment (dependency) // relation between regions. private IRegion m_parent = null; private List<IRegion> m_children = new ArrayList<IRegion>(); public Region(int id, SootMethod m, SootClass c, UnitGraph ug) { this(id, new ArrayList<Block>(), m, c, ug); } public Region(int id, List<Block> blocks, SootMethod m, SootClass c, UnitGraph ug) { this.m_blocks = blocks; this.m_id = id; this.m_method = m; this.m_class = c; this.m_unitGraph = ug; this.m_units = null; } @SuppressWarnings("unchecked") public Object clone() { Region r = new Region(this.m_id, this.m_method, this.m_class, this.m_unitGraph); r.m_blocks = (List<Block>) ((ArrayList<Block>) this.m_blocks).clone(); return r; } public SootMethod getSootMethod() { return this.m_method; } public SootClass getSootClass() { return this.m_class; } public List<Block> getBlocks() { return this.m_blocks; } public UnitGraph getUnitGraph() { return this.m_unitGraph; } public List<Unit> getUnits() { if (this.m_units == null) { this.m_units = new LinkedList<Unit>(); for (Iterator<Block> itr = this.m_blocks.iterator(); itr.hasNext();) { Block b = itr.next(); for (Iterator<Unit> itr1 = b.iterator(); itr1.hasNext();) { Unit u = itr1.next(); ((LinkedList<Unit>) this.m_units).addLast(u); } } } return this.m_units; } public List<Unit> getUnits(Unit from, Unit to) { return m_units.subList(m_units.indexOf(from), m_units.indexOf(to)); } public Unit getLast() { if (this.m_units != null) { if (this.m_units.size() > 0) { return ((LinkedList<Unit>) this.m_units).getLast(); } } return null; } public Unit getFirst() { if (this.m_units != null) { if (this.m_units.size() > 0) { return ((LinkedList<Unit>) this.m_units).getFirst(); } } return null; } public void add(Block b) { // Add to the front this.m_blocks.add(0, b); } public void add2Back(Block b) { // Add to the last this.m_blocks.add(this.m_blocks.size(), b); } public void remove(Block b) { this.m_blocks.remove(b); // make the units be recalculated. this.m_units = null; } public int getID() { return this.m_id; } public boolean occursBefore(Unit u1, Unit u2) { int i = this.m_units.lastIndexOf(u1); int j = this.m_units.lastIndexOf(u2); if (i == -1 || j == -1) { throw new RuntimeException("These units don't exist in the region!"); } return i < j; } public void setParent(IRegion pr) { this.m_parent = pr; } public IRegion getParent() { return this.m_parent; } public void addChildRegion(IRegion chr) { if (!this.m_children.contains(chr)) { this.m_children.add(chr); } } public List<IRegion> getChildRegions() { return this.m_children; } public String toString() { String str = new String(); str += "Begin-----------Region: " + this.m_id + "-------------\n"; List<Unit> regionUnits = this.getUnits(); for (Iterator<Unit> itr = regionUnits.iterator(); itr.hasNext();) { Unit u = itr.next(); str += u + "\n"; } str += "End Region " + this.m_id + " -----------------------------\n"; return str; } }
5,407
24.389671
124
java
soot
soot-master/src/main/java/soot/toolkits/graph/pdg/RegionAnalysis.java
package soot.toolkits.graph.pdg; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 - 2010 Hossein Sadat-Mohtasham * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.G; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.options.Options; import soot.toolkits.graph.Block; import soot.toolkits.graph.BlockGraph; import soot.toolkits.graph.BriefBlockGraph; import soot.toolkits.graph.BriefUnitGraph; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.DominatorNode; import soot.toolkits.graph.DominatorTree; import soot.toolkits.graph.ExceptionalBlockGraph; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.MHGDominatorsFinder; import soot.toolkits.graph.MHGPostDominatorsFinder; import soot.toolkits.graph.UnitGraph; /** * This class computes the set of weak regions for a given method. It is based on the algorithm given in the following paper: * * Ball, T. 1993. What's in a region?: or computing control dependence regions in near-linear time for reducible control * flow. ACM Lett. Program. Lang. Syst. 2, 1-4 (Mar. 1993), 1-16. DOI= http://doi.acm.org/10.1145/176454.176456 * * @author Hossein Sadat-Mohtasham Jan 2009 */ public class RegionAnalysis { private static final Logger logger = LoggerFactory.getLogger(RegionAnalysis.class); protected SootClass m_class = null; protected SootMethod m_method = null; protected Body m_methodBody; protected UnitGraph m_cfg; protected UnitGraph m_reverseCFG; protected BlockGraph m_blockCFG; protected BlockGraph m_reverseBlockCFG; protected Hashtable<Integer, Region> m_regions = new Hashtable<Integer, Region>(); protected List<Region> m_regionsList = null; private int m_regCount = 0; private MHGDominatorTree<Block> m_dom; // this would actually be the postdominator tree in the original CFG private MHGDominatorTree<Block> m_pdom; protected Region m_topLevelRegion = null; protected Hashtable<Block, Region> m_block2region = null; public RegionAnalysis(UnitGraph cfg, SootMethod m, SootClass c) { this.m_methodBody = cfg.getBody(); this.m_cfg = cfg; this.m_method = m; this.m_class = c; if (Options.v().verbose()) { logger.debug( "[RegionAnalysis]~~~~~~~~~~~~~~~ Begin Region Analsis for method: " + m.getName() + " ~~~~~~~~~~~~~~~~~~~~"); } this.findWeakRegions(); if (Options.v().verbose()) { logger.debug("[RegionAnalysis]~~~~~~~~~~~~~~~ End:" + m.getName() + " ~~~~~~~~~~~~~~~~~~~~"); } } private void findWeakRegions() { /* * Check to see what kind of CFG has been passed in and create the appropriate block CFG. Note that almost all of the * processing is done on the block CFG. */ if (this.m_cfg instanceof ExceptionalUnitGraph) { this.m_blockCFG = new ExceptionalBlockGraph((ExceptionalUnitGraph) this.m_cfg); } else if (this.m_cfg instanceof EnhancedUnitGraph) { this.m_blockCFG = new EnhancedBlockGraph((EnhancedUnitGraph) this.m_cfg); } else if (this.m_cfg instanceof BriefUnitGraph) { this.m_blockCFG = new BriefBlockGraph((BriefUnitGraph) this.m_cfg); } else { throw new RuntimeException("Unsupported CFG passed into the RegionAnalyis constructor!"); } this.m_dom = new MHGDominatorTree<Block>(new MHGDominatorsFinder<Block>(this.m_blockCFG)); try { this.m_pdom = new MHGDominatorTree<Block>(new MHGPostDominatorsFinder<Block>(m_blockCFG)); if (Options.v().verbose()) { logger.debug("[RegionAnalysis] PostDominator tree: "); } this.m_regCount = -1; /* * If a Brief graph or Exceptional graph is used, the CFG might be multi-headed and/or multi-tailed, which in turn, * could result in a post-dominator forest instead of tree. If the post-dominator tree has multiple heads, the * weakRegionDFS does not work correctly because it is designed based on the assumption that there is an auxiliary STOP * node in the CFG that post-dominates all other nodes. In fact, most of the CFG algorithms augment the control flow * graph with two nodes: ENTRY and EXIT (or START and STOP) nodes. We have not added these nodes since the CFG here is * created from the Jimple code and to be consistent we'd have to transform the code to reflect these nodes. Instead, * we implemted the EnhancedUnitGraph (EnhancedBlockGraph) which is guaranteed to be single-headed single-tailed. But * note that EnhancedUnitGraph represents exceptional flow differently. * * */ if (this.m_blockCFG.getHeads().size() == 1) { this.m_regCount++; this.m_regions.put(this.m_regCount, this.createRegion(this.m_regCount)); this.weakRegionDFS2(this.m_blockCFG.getHeads().get(0), this.m_regCount); } else if (this.m_blockCFG.getTails().size() == 1) { this.m_regCount++; this.m_regions.put(this.m_regCount, this.createRegion(this.m_regCount)); this.weakRegionDFS(this.m_blockCFG.getTails().get(0), this.m_regCount); } else { if (Options.v().verbose()) { logger.warn( "RegionAnalysis: the CFG is multi-headed and tailed, so, the results of this analysis might not be reliable!"); } for (int i = 0; i < this.m_blockCFG.getTails().size(); i++) { this.m_regCount++; this.m_regions.put(this.m_regCount, this.createRegion(this.m_regCount)); this.weakRegionDFS(this.m_blockCFG.getTails().get(i), this.m_regCount); } // throw new RuntimeException("RegionAnalysis: cannot properly deal with multi-headed and tailed CFG!"); } } catch (RuntimeException e) { logger.debug("[RegionAnalysis] Exception in findWeakRegions: " + e); } } /** * This algorithms assumes that the first time it's called with a tail of the CFG. Then for each child node w of v in the * post-dominator tree, it compares the parent of v in the dominator tree with w and if they are the same, that means w * belongs to the same region as v, so weakRegionDFS is recursively called with w and the same region id as v. If the * comparison fails, then a new region is created and weakRegionDFS is called recursively with w but this time with the * newly created region id. * * @param v * @param r */ private void weakRegionDFS(Block v, int r) { try { // System.out.println("##entered weakRegionDFS for region " + r); this.m_regions.get(r).add(v); DominatorNode<Block> parentOfV = this.m_dom.getParentOf(this.m_dom.getDode(v)); Block u2 = (parentOfV == null) ? null : parentOfV.getGode(); List<DominatorNode<Block>> children = this.m_pdom.getChildrenOf(this.m_pdom.getDode(v)); for (int i = 0; i < children.size(); i++) { DominatorNode<Block> w = children.get(i); Block u1 = w.getGode(); if (u2 != null && u1.equals(u2)) { this.weakRegionDFS(w.getGode(), r); } else { this.m_regCount++; this.m_regions.put(this.m_regCount, this.createRegion(this.m_regCount)); this.weakRegionDFS(w.getGode(), this.m_regCount); } } } catch (RuntimeException e) { logger.debug("[RegionAnalysis] Exception in weakRegionDFS: ", e); logger.debug("v is " + v.toShortString() + " in region " + r); G.v().out.flush(); } } /** * This algorithm starts from a head node in the CFG and is exactly the same as the above with the difference that post * dominator and dominator trees switch positions. * * @param v * @param r */ private void weakRegionDFS2(Block v, int r) { // regions keep an implicit order of the contained blocks so it matters where blocks are added // below. this.m_regions.get(r).add2Back(v); DominatorNode<Block> parentOfV = this.m_pdom.getParentOf(this.m_pdom.getDode(v)); Block u2 = (parentOfV == null) ? null : parentOfV.getGode(); List<DominatorNode<Block>> children = this.m_dom.getChildrenOf(this.m_dom.getDode(v)); for (int i = 0; i < children.size(); i++) { DominatorNode<Block> w = children.get(i); Block u1 = w.getGode(); if (u2 != null && u1.equals(u2)) { this.weakRegionDFS2(w.getGode(), r); } else { this.m_regCount++; this.m_regions.put(this.m_regCount, this.createRegion(this.m_regCount)); this.weakRegionDFS2(w.getGode(), this.m_regCount); } } } public List<Region> getRegions() { if (this.m_regionsList == null) { this.m_regionsList = new ArrayList<Region>(this.m_regions.values()); } return this.m_regionsList; } public Hashtable<Unit, Region> getUnit2RegionMap() { Hashtable<Unit, Region> unit2region = new Hashtable<Unit, Region>(); List<Region> regions = this.getRegions(); for (Iterator<Region> itr = regions.iterator(); itr.hasNext();) { Region r = itr.next(); List<Unit> units = r.getUnits(); for (Iterator<Unit> itr1 = units.iterator(); itr1.hasNext();) { Unit u = itr1.next(); unit2region.put(u, r); } } return unit2region; } public Hashtable<Block, Region> getBlock2RegionMap() { if (this.m_block2region == null) { this.m_block2region = new Hashtable<Block, Region>(); List<Region> regions = this.getRegions(); for (Iterator<Region> itr = regions.iterator(); itr.hasNext();) { Region r = itr.next(); List<Block> blocks = r.getBlocks(); for (Iterator<Block> itr1 = blocks.iterator(); itr1.hasNext();) { Block u = itr1.next(); m_block2region.put(u, r); } } } return this.m_block2region; } public BlockGraph getBlockCFG() { return this.m_blockCFG; } public DominatorTree<Block> getPostDominatorTree() { return this.m_pdom; } public DominatorTree<Block> getDominatorTree() { return this.m_dom; } public void reset() { this.m_regions.clear(); this.m_regionsList.clear(); this.m_regionsList = null; this.m_block2region.clear(); this.m_block2region = null; m_regCount = 0; } /** * Create a region */ protected Region createRegion(int id) { Region region = new Region(id, this.m_method, this.m_class, this.m_cfg); if (id == 0) { this.m_topLevelRegion = region; } return region; } public Region getTopLevelRegion() { return this.m_topLevelRegion; } public static String CFGtoString(DirectedGraph<Block> cfg, boolean blockDetail) { String s = ""; s += "Headers: " + cfg.getHeads().size() + " " + cfg.getHeads(); for (Block node : cfg) { s += "Node = " + node.toShortString() + "\n"; s += "Preds:\n"; for (Iterator<Block> predsIt = cfg.getPredsOf(node).iterator(); predsIt.hasNext();) { s += " "; s += predsIt.next().toShortString() + "\n"; } s += "Succs:\n"; for (Iterator<Block> succsIt = cfg.getSuccsOf(node).iterator(); succsIt.hasNext();) { s += " "; s += succsIt.next().toShortString() + "\n"; } } if (blockDetail) { s += "Blocks Detail:"; for (Iterator<Block> it = cfg.iterator(); it.hasNext();) { Block node = it.next(); s += node + "\n"; } } return s; } }
12,240
33.775568
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/AbstractBoundedFlowSet.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * provides functional code for most of the methods. Subclasses are invited to provide a more efficient version. Most often * this will be done in the following way:<br> * * <pre> * public void yyy(FlowSet dest) { * if (dest instanceof xxx) { * blahblah; * } else * super.yyy(dest) * } * </pre> */ public abstract class AbstractBoundedFlowSet<T> extends AbstractFlowSet<T> implements BoundedFlowSet<T> { @Override public void complement() { complement(this); } @Override public void complement(FlowSet<T> dest) { if (this == dest) { complement(); } else { BoundedFlowSet<T> tmp = (BoundedFlowSet<T>) topSet(); tmp.difference(this, dest); } } @Override public FlowSet<T> topSet() { BoundedFlowSet<T> tmp = (BoundedFlowSet<T>) emptySet(); tmp.complement(); return tmp; } }
1,697
25.952381
123
java
soot
soot-master/src/main/java/soot/toolkits/scalar/AbstractFlowAnalysis.java
package soot.toolkits.scalar; /*- * #%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.Collections; import java.util.IdentityHashMap; import java.util.Map; import soot.options.Options; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.interaction.InteractionHandler; /** * An abstract class providing a meta-framework for carrying out dataflow analysis. This class provides common methods and * fields required by the BranchedFlowAnalysis and FlowAnalysis abstract classes. * * @param <N> * node type of the directed graph * @param <A> * abstraction type */ public abstract class AbstractFlowAnalysis<N, A> { /** The graph being analysed. */ protected final DirectedGraph<N> graph; /** Maps graph nodes to IN sets. */ protected final Map<N, A> unitToBeforeFlow; /** Filtered: Maps graph nodes to IN sets. */ protected Map<N, A> filterUnitToBeforeFlow; /** Constructs a flow analysis on the given <code>DirectedGraph</code>. */ public AbstractFlowAnalysis(DirectedGraph<N> graph) { this.graph = graph; this.unitToBeforeFlow = new IdentityHashMap<N, A>(graph.size() * 2 + 1); this.filterUnitToBeforeFlow = Collections.emptyMap(); if (Options.v().interactive_mode()) { InteractionHandler.v().handleCfgEvent(graph); } } /** * Returns the flow object corresponding to the initial values for each graph node. */ protected abstract A newInitialFlow(); /** * Returns the initial flow value for entry/exit graph nodes. * * This is equal to {@link #newInitialFlow()} */ protected A entryInitialFlow() { return newInitialFlow(); } /** * Determines whether <code>entryInitialFlow()</code> is applied to trap handlers. */ protected boolean treatTrapHandlersAsEntries() { return false; } /** Returns true if this analysis is forwards. */ protected abstract boolean isForward(); /** * Compute the merge of the <code>in1</code> and <code>in2</code> sets, putting the result into <code>out</code>. The * behavior of this function depends on the implementation ( it may be necessary to check whether <code>in1</code> and * <code>in2</code> are equal or aliased ). Used by the doAnalysis method. */ protected abstract void merge(A in1, A in2, A out); /** * Merges in1 and in2 into out, just before node succNode. By default, this method just calls merge(A,A,A), ignoring the * node. */ protected void merge(N succNode, A in1, A in2, A out) { merge(in1, in2, out); } /** Creates a copy of the <code>source</code> flow object in <code>dest</code>. */ protected abstract void copy(A source, A dest); /** * Carries out the actual flow analysis. Typically called from a concrete FlowAnalysis's constructor. */ protected abstract void doAnalysis(); /** Accessor function returning value of IN set for s. */ public A getFlowBefore(N s) { return unitToBeforeFlow.get(s); } /** * Merges in into inout, just before node succNode. */ protected void mergeInto(N succNode, A inout, A in) { A tmp = newInitialFlow(); merge(succNode, inout, in, tmp); copy(tmp, inout); } }
3,947
30.83871
122
java
soot
soot-master/src/main/java/soot/toolkits/scalar/AbstractFlowSet.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.List; /** * provides functional code for most of the methods. Subclasses are invited to provide a more efficient version. Most often * this will be done in the following way:<br> * * <pre> * public void yyy(FlowSet dest) { * if (dest instanceof xxx) { * blahblah; * } else * super.yyy(dest) * } * </pre> */ public abstract class AbstractFlowSet<T> implements FlowSet<T> { @Override public abstract AbstractFlowSet<T> clone(); /** * implemented, but inefficient. */ @Override public FlowSet<T> emptySet() { FlowSet<T> t = clone(); t.clear(); return t; } @Override public void copy(FlowSet<T> dest) { if (this == dest) { return; } dest.clear(); for (T t : this) { dest.add(t); } } /** * implemented, but *very* inefficient. */ @Override public void clear() { for (T t : this) { remove(t); } } @Override public void union(FlowSet<T> other) { if (this == other) { return; } union(other, this); } @Override public void union(FlowSet<T> other, FlowSet<T> dest) { if (dest != this && dest != other) { dest.clear(); } if (dest != null && dest != this) { for (T t : this) { dest.add(t); } } if (other != null && dest != other) { for (T t : other) { dest.add(t); } } } @Override public void intersection(FlowSet<T> other) { if (this == other) { return; } intersection(other, this); } @Override public void intersection(FlowSet<T> other, FlowSet<T> dest) { if (dest == this && dest == other) { return; } FlowSet<T> elements = null; FlowSet<T> flowSet = null; if (dest == this) { /* * makes automaticly a copy of <code>this</code>, as it will be cleared */ elements = this; flowSet = other; } else { /* makes a copy o <code>other</code>, as it might be cleared */ elements = other; flowSet = this; } dest.clear(); for (T t : elements) { if (flowSet.contains(t)) { dest.add(t); } } } @Override public void difference(FlowSet<T> other) { difference(other, this); } @Override public void difference(FlowSet<T> other, FlowSet<T> dest) { if (dest == this && dest == other) { dest.clear(); return; } FlowSet<T> flowSet = (other == dest) ? other.clone() : other; dest.clear(); // now safe, since we have copies of this & other for (T t : this) { if (!flowSet.contains(t)) { dest.add(t); } } } @Override public abstract boolean isEmpty(); @Override public abstract int size(); @Override public abstract void add(T obj); @Override public void add(T obj, FlowSet<T> dest) { if (dest != this) { copy(dest); } dest.add(obj); } @Override public abstract void remove(T obj); @Override public void remove(T obj, FlowSet<T> dest) { if (dest != this) { copy(dest); } dest.remove(obj); } @Override public boolean isSubSet(FlowSet<T> other) { if (other == this) { return true; } for (T t : other) { if (!contains(t)) { return false; } } return true; } @Override public abstract boolean contains(T obj); @Override public abstract Iterator<T> iterator(); @Override public abstract List<T> toList(); @Override public boolean equals(Object o) { if (!(o instanceof FlowSet)) { return false; } FlowSet<T> other = (FlowSet<T>) o; if (size() != other.size()) { return false; } for (T t : this) { if (!other.contains(t)) { return false; } } return true; } @Override public int hashCode() { int result = 1; for (T t : this) { result += t.hashCode(); } return result; } @Override public String toString() { StringBuffer buffer = new StringBuffer("{"); boolean isFirst = true; for (T t : this) { if (!isFirst) { buffer.append(", "); } isFirst = false; buffer.append(t); } buffer.append("}"); return buffer.toString(); } }
5,111
19.125984
123
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ArrayFlowUniverse.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Arrays; import java.util.Iterator; /** * Provides an implementation of a flow universe, wrapping arrays. */ public class ArrayFlowUniverse<E> implements FlowUniverse<E> { protected final E[] elements; public ArrayFlowUniverse(E[] elements) { this.elements = elements; } @Override public int size() { return elements.length; } @Override public Iterator<E> iterator() { return Arrays.asList(elements).iterator(); } @Override public E[] toArray() { return elements; } }
1,363
24.259259
71
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ArrayPackedSet.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * updated 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import java.util.ArrayList; import java.util.BitSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Reference implementation for a BoundedFlowSet. Items are stored in an Array. */ public class ArrayPackedSet<T> extends AbstractBoundedFlowSet<T> { protected final ObjectIntMapper<T> map; protected final BitSet bits; public ArrayPackedSet(FlowUniverse<T> universe) { this(new ObjectIntMapper<T>(universe)); } ArrayPackedSet(ObjectIntMapper<T> map) { this(map, new BitSet()); } ArrayPackedSet(ObjectIntMapper<T> map, BitSet bits) { this.map = map; this.bits = bits; } @Override public ArrayPackedSet<T> clone() { return new ArrayPackedSet<T>(map, (BitSet) bits.clone()); } @Override public FlowSet<T> emptySet() { return new ArrayPackedSet<T>(map); } @Override public int size() { return bits.cardinality(); } @Override public boolean isEmpty() { return bits.isEmpty(); } @Override public void clear() { bits.clear(); } private BitSet copyBitSet(ArrayPackedSet<?> dest) { assert (dest.map == this.map); if (this != dest) { dest.bits.clear(); dest.bits.or(bits); } return dest.bits; } /** Returns true if flowSet is the same type of flow set as this. */ private boolean sameType(Object flowSet) { return (flowSet instanceof ArrayPackedSet) && (((ArrayPackedSet<?>) flowSet).map == this.map); } private List<T> toList(BitSet bits, int base) { final int len = bits.cardinality(); switch (len) { case 0: return emptyList(); case 1: return singletonList(map.getObject((base - 1) + bits.length())); default: List<T> elements = new ArrayList<T>(len); int i = bits.nextSetBit(0); do { int endOfRun = bits.nextClearBit(i + 1); do { elements.add(map.getObject(base + i++)); } while (i < endOfRun); i = bits.nextSetBit(i + 1); } while (i >= 0); return elements; } } public List<T> toList(int lowInclusive, int highInclusive) { if (lowInclusive > highInclusive) { return emptyList(); } if (lowInclusive < 0) { throw new IllegalArgumentException(); } int highExclusive = highInclusive + 1; return toList(bits.get(lowInclusive, highExclusive), lowInclusive); } @Override public List<T> toList() { return toList(bits, 0); } @Override public void add(T obj) { bits.set(map.getInt(obj)); } @Override public void complement(FlowSet<T> destFlow) { if (sameType(destFlow)) { ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow; copyBitSet(dest).flip(0, dest.map.size()); } else { super.complement(destFlow); } } @Override public void remove(T obj) { bits.clear(map.getInt(obj)); } @Override public boolean isSubSet(FlowSet<T> other) { if (other == this) { return true; } if (sameType(other)) { ArrayPackedSet<T> o = (ArrayPackedSet<T>) other; BitSet tmp = (BitSet) o.bits.clone(); tmp.andNot(bits); return tmp.isEmpty(); } return super.isSubSet(other); } @Override public void union(FlowSet<T> otherFlow, FlowSet<T> destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ArrayPackedSet<T> other = (ArrayPackedSet<T>) otherFlow; ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow; copyBitSet(dest).or(other.bits); } else { super.union(otherFlow, destFlow); } } @Override public void difference(FlowSet<T> otherFlow, FlowSet<T> destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ArrayPackedSet<T> other = (ArrayPackedSet<T>) otherFlow; ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow; copyBitSet(dest).andNot(other.bits); } else { super.difference(otherFlow, destFlow); } } @Override public void intersection(FlowSet<T> otherFlow, FlowSet<T> destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ArrayPackedSet<T> other = (ArrayPackedSet<T>) otherFlow; ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow; copyBitSet(dest).and(other.bits); } else { super.intersection(otherFlow, destFlow); } } /** * Returns true, if the object is in the set. */ @Override public boolean contains(T obj) { /* * check if the object is in the map, direct call of map.getInt will add the object into the map. */ return map.contains(obj) && bits.get(map.getInt(obj)); } @Override public boolean equals(Object otherFlow) { if (sameType(otherFlow)) { return bits.equals(((ArrayPackedSet<?>) otherFlow).bits); } else { return super.equals(otherFlow); } } @Override public void copy(FlowSet<T> destFlow) { if (this == destFlow) { return; } if (sameType(destFlow)) { ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow; copyBitSet(dest); } else { super.copy(destFlow); } } @Override public Iterator<T> iterator() { return new Iterator<T>() { int curr = -1; int next = bits.nextSetBit(0); @Override public boolean hasNext() { return (next >= 0); } @Override public T next() { if (next < 0) { throw new NoSuchElementException(); } curr = next; next = bits.nextSetBit(curr + 1); return map.getObject(curr); } @Override public void remove() { if (curr < 0) { throw new IllegalStateException(); } bits.clear(curr); curr = -1; } }; } }
6,729
23.652015
101
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ArraySparseSet.java
package soot.toolkits.scalar; /*- * #%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.HashSet; import java.util.Iterator; import java.util.List; /** * Reference implementation for a FlowSet. Items are stored in an Array. */ public class ArraySparseSet<T> extends AbstractFlowSet<T> { protected static final int DEFAULT_SIZE = 8; protected int numElements; protected int maxElements; protected T[] elements; public ArraySparseSet() { maxElements = DEFAULT_SIZE; @SuppressWarnings("unchecked") T[] newElements = (T[]) new Object[DEFAULT_SIZE]; elements = newElements; numElements = 0; } private ArraySparseSet(ArraySparseSet<T> other) { numElements = other.numElements; maxElements = other.maxElements; elements = other.elements.clone(); } /** Returns true if flowSet is the same type of flow set as this. */ private boolean sameType(Object flowSet) { return (flowSet instanceof ArraySparseSet); } @Override public ArraySparseSet<T> clone() { return new ArraySparseSet<T>(this); } @Override public FlowSet<T> emptySet() { return new ArraySparseSet<T>(); } @Override public void clear() { numElements = 0; Arrays.fill(elements, null); } @Override public int size() { return numElements; } @Override public boolean isEmpty() { return numElements == 0; } /** Returns a unbacked list of elements in this set. */ @Override public List<T> toList() { return Arrays.asList(Arrays.copyOf(elements, numElements)); } /* * Expand array only when necessary, pointed out by Florian Loitsch March 08, 2002 */ @Override public void add(T e) { /* Expand only if necessary! and removes one if too:) */ // Add element if (!contains(e)) { // Expand array if necessary if (numElements == maxElements) { doubleCapacity(); } elements[numElements++] = e; } } private void doubleCapacity() { int newSize = maxElements * 2; @SuppressWarnings("unchecked") T[] newElements = (T[]) new Object[newSize]; System.arraycopy(elements, 0, newElements, 0, numElements); elements = newElements; maxElements = newSize; } @Override public void remove(Object obj) { for (int i = 0; i < numElements; i++) { if (elements[i].equals(obj)) { remove(i); break; } } } public void remove(int idx) { numElements--; // copy last element to deleted position elements[idx] = elements[numElements]; // delete reference in last cell so that // we only retain a single reference to the // "old last" element, for memory safety elements[numElements] = null; } @Override public void union(FlowSet<T> otherFlow, FlowSet<T> destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ArraySparseSet<T> other = (ArraySparseSet<T>) otherFlow; ArraySparseSet<T> dest = (ArraySparseSet<T>) destFlow; if (dest == other) { // For the special case that dest == other for (int i = 0; i < this.numElements; i++) { dest.add(this.elements[i]); } } else { // Else, force that dest starts with contents of this if (this != dest) { copy(dest); } for (int i = 0; i < other.numElements; i++) { dest.add(other.elements[i]); } } } else { super.union(otherFlow, destFlow); } } @Override public void intersection(FlowSet<T> otherFlow, FlowSet<T> destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ArraySparseSet<T> other = (ArraySparseSet<T>) otherFlow; ArraySparseSet<T> dest = (ArraySparseSet<T>) destFlow; ArraySparseSet<T> workingSet; if (dest == other || dest == this) { workingSet = new ArraySparseSet<T>(); } else { workingSet = dest; workingSet.clear(); } for (int i = 0; i < this.numElements; i++) { if (other.contains(this.elements[i])) { workingSet.add(this.elements[i]); } } if (workingSet != dest) { workingSet.copy(dest); } } else { super.intersection(otherFlow, destFlow); } } @Override public void difference(FlowSet<T> otherFlow, FlowSet<T> destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ArraySparseSet<T> other = (ArraySparseSet<T>) otherFlow; ArraySparseSet<T> dest = (ArraySparseSet<T>) destFlow; ArraySparseSet<T> workingSet; if (dest == other || dest == this) { workingSet = new ArraySparseSet<T>(); } else { workingSet = dest; workingSet.clear(); } for (int i = 0; i < this.numElements; i++) { if (!other.contains(this.elements[i])) { workingSet.add(this.elements[i]); } } if (workingSet != dest) { workingSet.copy(dest); } } else { super.difference(otherFlow, destFlow); } } /** * @deprecated This method uses linear-time lookup. For better performance, consider using a {@link HashSet} instead, if * you require this operation. */ @Deprecated @Override public boolean contains(Object obj) { for (int i = 0; i < numElements; i++) { if (elements[i].equals(obj)) { return true; } } return false; } @Override public boolean equals(Object otherFlow) { if (sameType(otherFlow)) { @SuppressWarnings("unchecked") ArraySparseSet<T> other = (ArraySparseSet<T>) otherFlow; int size = this.numElements; if (other.numElements != size) { return false; } // Make sure that thisFlow is contained in otherFlow for (int i = 0; i < size; i++) { if (!other.contains(this.elements[i])) { return false; } } /* * both arrays have the same size, no element appears twice in one array, all elements of ThisFlow are in otherFlow -> * they are equal! we don't need to test again! // Make sure that otherFlow is contained in ThisFlow for(int i = 0; i < * size; i++) if(!this.contains(other.elements[i])) return false; */ return true; } else { return super.equals(otherFlow); } } @Override public void copy(FlowSet<T> destFlow) { if (sameType(destFlow)) { ArraySparseSet<T> dest = (ArraySparseSet<T>) destFlow; while (dest.maxElements < this.maxElements) { dest.doubleCapacity(); } dest.numElements = this.numElements; System.arraycopy(this.elements, 0, dest.elements, 0, this.numElements); } else { super.copy(destFlow); } } @Override public void copyFreshToExisting(FlowSet<T> destFlow) { if (sameType(destFlow)) { ArraySparseSet<T> dest = (ArraySparseSet<T>) destFlow; dest.maxElements = maxElements; dest.elements = elements; dest.numElements = this.numElements; } else { super.copy(destFlow); } } @Override public Iterator<T> iterator() { return new Iterator<T>() { int nextIdx = 0; @Override public boolean hasNext() { return nextIdx < numElements; } @Override public T next() { return elements[nextIdx++]; } @Override public void remove() { if (nextIdx == 0) { throw new IllegalStateException("'next' has not been called yet."); } ArraySparseSet.this.remove(nextIdx - 1); nextIdx--; } }; } }
8,350
25.015576
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/BackwardFlowAnalysis.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.toolkits.graph.DirectedGraph; /** * Abstract class that provides the fixed point iteration functionality required by all BackwardFlowAnalyses. */ public abstract class BackwardFlowAnalysis<N, A> extends FlowAnalysis<N, A> { /** * Construct the analysis from a DirectedGraph representation of a Body. */ public BackwardFlowAnalysis(DirectedGraph<N> graph) { super(graph); } /** * Returns <code>false</code> * * @return false **/ @Override protected boolean isForward() { return false; } @Override protected void doAnalysis() { doAnalysis(GraphView.BACKWARD, InteractionFlowHandler.BACKWARD, unitToAfterFlow, unitToBeforeFlow); // soot.Timers.v().totalFlowNodes += graph.size(); // soot.Timers.v().totalFlowComputations += numComputations; } }
1,657
28.607143
109
java
soot
soot-master/src/main/java/soot/toolkits/scalar/BinaryIdentitySet.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2007 Eric Bodden * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * An optimized kind of {@link IdentityHashSet} that only holds two objects. (Allows for faster comparison.) * * @author Eric Bodden */ public class BinaryIdentitySet<T> { protected final T o1; protected final T o2; protected final int hashCode; public BinaryIdentitySet(T o1, T o2) { this.o1 = o1; this.o2 = o2; this.hashCode = computeHashCode(); } /** * {@inheritDoc} */ @Override public int hashCode() { return hashCode; } private int computeHashCode() { int result = 1; // must be commutative result += System.identityHashCode(o1); result += System.identityHashCode(o2); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } final BinaryIdentitySet<?> other = (BinaryIdentitySet<?>) obj; // must be commutative return (this.o1 == other.o1 || this.o1 == other.o2) && (this.o2 == other.o2 || this.o2 == other.o1); } public T getO1() { return o1; } public T getO2() { return o2; } @Override public String toString() { return "IdentityPair " + o1 + "," + o2; } }
2,087
23.27907
108
java
soot
soot-master/src/main/java/soot/toolkits/scalar/BoundedFlowSet.java
package soot.toolkits.scalar; /*- * #%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 bounded information for flow analysis. Just like FlowSet, but also provides complementation. Some * implementations of BoundedFlowSet may require a FlowUniverse for construction. * * @see: FlowUniverse */ public interface BoundedFlowSet<T> extends FlowSet<T> { /** * Complements <code>this</code>. */ public void complement(); /** * Complements this BoundedFlowSet, putting the result into <code>dest</code>. <code>dest</code> and <code>this</code> may * be the same object. */ public void complement(FlowSet<T> dest); /** * returns the topped set. */ public FlowSet<T> topSet(); }
1,477
29.791667
124
java
soot
soot-master/src/main/java/soot/toolkits/scalar/BranchedFlowAnalysis.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2000 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashMap; import java.util.List; import java.util.Map; import soot.Unit; import soot.toolkits.graph.DirectedGraph; /** * Abstract class providing functionality for branched flow analysis. * * A branched flow analysis is one which can propagate different information to the successors of a node. This is useful for * propagating information past a statement like <code>if(x &gt; * 0)</code>: one successor has <code>x &gt; 0</code> while the other successor has <code>x &le; 0</code>. */ public abstract class BranchedFlowAnalysis<N extends Unit, A> extends AbstractFlowAnalysis<N, A> { /** Maps graph nodes to OUT sets. */ protected final Map<Unit, List<A>> unitToAfterFallFlow; protected final Map<Unit, List<A>> unitToAfterBranchFlow; public BranchedFlowAnalysis(DirectedGraph<N> graph) { super(graph); this.unitToAfterFallFlow = new HashMap<Unit, List<A>>(graph.size() * 2 + 1, 0.7f); this.unitToAfterBranchFlow = new HashMap<Unit, List<A>>(graph.size() * 2 + 1, 0.7f); } /** * Given the merge of the <code>in</code> sets, compute the <code>fallOut</code> and <code>branchOuts</code> set for * <code>s</code>. */ protected abstract void flowThrough(A in, Unit s, List<A> fallOut, List<A> branchOuts); public A getFallFlowAfter(Unit s) { List<A> fl = unitToAfterFallFlow.get(s); return fl.isEmpty() ? newInitialFlow() : fl.get(0); } public List<A> getBranchFlowAfter(Unit s) { return unitToAfterBranchFlow.get(s); } } // end class BranchedFlowAnalysis
2,372
34.954545
124
java
soot
soot-master/src/main/java/soot/toolkits/scalar/CollectionFlowUniverse.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Provides an implementation of a flow universe, wrapping collections. */ public class CollectionFlowUniverse<E> implements FlowUniverse<E> { protected final Set<E> elements; public CollectionFlowUniverse(Collection<? extends E> elements) { this.elements = new HashSet<E>(elements); } @Override public int size() { return elements.size(); } @Override public Iterator<E> iterator() { return elements.iterator(); } @Override public E[] toArray() { @SuppressWarnings("unchecked") E[] temp = (E[]) elements.toArray(); return temp; } }
1,526
25.327586
71
java
soot
soot-master/src/main/java/soot/toolkits/scalar/CombinedAnalysis.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Analysis that computes live locals, local defs, and local uses all at once. */ public interface CombinedAnalysis extends LocalDefs, LocalUses, LiveLocals { }
995
32.2
78
java
soot
soot-master/src/main/java/soot/toolkits/scalar/CombinedDUAnalysis.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.toolkits.graph.UnitGraph; import soot.util.Cons; import soot.util.HashMultiMap; import soot.util.MultiMap; /** * Analysis that computes live locals, local defs, and local uses all at once. * * SA, 09.09.2014: Inefficient as hell (memory). Use the distinct analyses or fix this class before using it. */ public class CombinedDUAnalysis extends BackwardFlowAnalysis<Unit, FlowSet<ValueBox>> implements CombinedAnalysis { private static final Logger logger = LoggerFactory.getLogger(CombinedDUAnalysis.class); // Implementations of our interfaces... private final Map<Cons<Local, Unit>, List<Unit>> defsOfAt = new HashMap<Cons<Local, Unit>, List<Unit>>(); private final Map<Unit, List<UnitValueBoxPair>> usesOf = new HashMap<Unit, List<UnitValueBoxPair>>(); private final Map<Unit, List<Local>> liveLocalsBefore = new HashMap<Unit, List<Local>>(); private final Map<Unit, List<Local>> liveLocalsAfter = new HashMap<Unit, List<Local>>(); @Override public List<Unit> getDefsOfAt(Local l, Unit s) { Cons<Local, Unit> cons = new Cons<Local, Unit>(l, s); List<Unit> ret = defsOfAt.get(cons); if (ret == null) { defsOfAt.put(cons, ret = new ArrayList<Unit>()); } return ret; } @Override public List<Unit> getDefsOf(Local l) { throw new RuntimeException("Not implemented"); } @Override public List<UnitValueBoxPair> getUsesOf(Unit u) { List<UnitValueBoxPair> ret = usesOf.get(u); if (ret == null) { Local def = unitToLocalDefed.get(u); if (def == null) { usesOf.put(u, ret = Collections.emptyList()); } else { usesOf.put(u, ret = new ArrayList<UnitValueBoxPair>()); for (ValueBox vb : getFlowAfter(u)) { if (vb.getValue() == def) { ret.add(new UnitValueBoxPair(useBoxToUnit.get(vb), vb)); } } } } return ret; } @Override public List<Local> getLiveLocalsBefore(Unit u) { List<Local> ret = liveLocalsBefore.get(u); if (ret == null) { HashSet<Local> hs = new HashSet<Local>(); for (ValueBox vb : getFlowBefore(u)) { hs.add((Local) vb.getValue()); } liveLocalsBefore.put(u, ret = new ArrayList<Local>(hs)); } return ret; } @Override public List<Local> getLiveLocalsAfter(Unit u) { List<Local> ret = liveLocalsAfter.get(u); if (ret == null) { HashSet<Local> hs = new HashSet<Local>(); for (ValueBox vb : getFlowAfter(u)) { hs.add((Local) vb.getValue()); } liveLocalsAfter.put(u, ret = new ArrayList<Local>(hs)); } return ret; } // The actual analysis is below. private final Map<ValueBox, Unit> useBoxToUnit = new HashMap<ValueBox, Unit>(); private final Map<Unit, Local> unitToLocalDefed = new HashMap<Unit, Local>(); private final Map<Unit, ArraySparseSet<ValueBox>> unitToLocalUseBoxes = new HashMap<Unit, ArraySparseSet<ValueBox>>(); private final MultiMap<Value, ValueBox> localToUseBoxes = new HashMultiMap<Value, ValueBox>(); public CombinedDUAnalysis(UnitGraph graph) { super(graph); if (Options.v().verbose()) { logger.debug("[" + graph.getBody().getMethod().getName() + "] Constructing CombinedDUAnalysis..."); } for (Unit u : graph) { List<Value> defs = localsInBoxes(u.getDefBoxes()); switch (defs.size()) { case 0: break; case 1: unitToLocalDefed.put(u, (Local) defs.get(0)); break; default: throw new RuntimeException("Locals defed in " + u + ": " + defs.size()); } ArraySparseSet<ValueBox> localUseBoxes = new ArraySparseSet<ValueBox>(); for (ValueBox vb : u.getUseBoxes()) { Value v = vb.getValue(); if (v instanceof Local) { localUseBoxes.add(vb); if (useBoxToUnit.containsKey(vb)) { throw new RuntimeException("Aliased ValueBox " + vb + " in Unit " + u); } useBoxToUnit.put(vb, u); localToUseBoxes.put(v, vb); } } unitToLocalUseBoxes.put(u, localUseBoxes); } doAnalysis(); for (Unit defUnit : graph) { Local localDefed = unitToLocalDefed.get(defUnit); if (localDefed == null) { continue; } for (ValueBox vb : getFlowAfter(defUnit)) { if (vb.getValue() != localDefed) { continue; } Unit useUnit = useBoxToUnit.get(vb); getDefsOfAt(localDefed, useUnit).add(defUnit); } } if (Options.v().verbose()) { logger.debug("[" + graph.getBody().getMethod().getName() + "] Finished CombinedDUAnalysis..."); } } private List<Value> localsInBoxes(List<ValueBox> boxes) { List<Value> ret = new ArrayList<Value>(); for (ValueBox vb : boxes) { Value v = vb.getValue(); if (!(v instanceof Local)) { continue; } ret.add(v); } return ret; } // STEP 1: What are we computing? // SETS OF USE BOXES CONTAINING LOCALS => Use HashSet. // // STEP 2: Precisely define what we are computing. // A use box B is live at program point P if there exists a path from P to the // unit using B on which the local in B is not defined. // // STEP 3: Decide whether it is a backwards or forwards analysis. // BACKWARDS // // STEP 4: Is the merge operator union or intersection? // UNION protected void merge(FlowSet<ValueBox> inout, FlowSet<ValueBox> in) { inout.union(in); } @Override protected void merge(FlowSet<ValueBox> in1, FlowSet<ValueBox> in2, FlowSet<ValueBox> out) { in1.union(in2, out); } // STEP 5: Define flow equations. // in(s) = ( out(s) minus boxes(def(s)) ) union useboxes(s) @Override protected void flowThrough(FlowSet<ValueBox> out, Unit u, FlowSet<ValueBox> in) { Local def = unitToLocalDefed.get(u); out.copy(in); if (def != null) { Collection<ValueBox> boxesDefed = localToUseBoxes.get(def); for (ValueBox vb : in) { if (boxesDefed.contains(vb)) { in.remove(vb); } } } in.union(unitToLocalUseBoxes.get(u)); } // STEP 6: Determine value for start/end node, and // initial approximation. // // end node: empty set // initial approximation: empty set @Override protected FlowSet<ValueBox> entryInitialFlow() { return new ArraySparseSet<ValueBox>(); } @Override protected FlowSet<ValueBox> newInitialFlow() { return new ArraySparseSet<ValueBox>(); } @Override protected void copy(FlowSet<ValueBox> source, FlowSet<ValueBox> dest) { source.copy(dest); } }
7,781
30.253012
120
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ConstantInitializerToTagTransformer.java
package soot.toolkits.scalar; /*- * #%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.Map.Entry; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.ConflictingFieldRefException; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.AssignStmt; import soot.jimple.Constant; import soot.jimple.DoubleConstant; import soot.jimple.FieldRef; import soot.jimple.FloatConstant; import soot.jimple.IntConstant; import soot.jimple.LongConstant; import soot.jimple.StaticFieldRef; import soot.jimple.StringConstant; import soot.tagkit.ConstantValueTag; import soot.tagkit.DoubleConstantValueTag; import soot.tagkit.FloatConstantValueTag; import soot.tagkit.IntegerConstantValueTag; import soot.tagkit.LongConstantValueTag; import soot.tagkit.StringConstantValueTag; import soot.tagkit.Tag; /** * This is the reverse operation of the {@link ConstantValueToInitializerTransformer}. We scan for {@code <clinit>} methods * that initialize a final field with a constant value and create a {@link ConstantValueTag} from this value. Afterwards, the * assignment in the {@code <clinit>} method is removed. If {@code <clinit>} runs empty, it is deleted as well. * * @author Steven Arzt */ public class ConstantInitializerToTagTransformer extends SceneTransformer { private static final Logger logger = LoggerFactory.getLogger(ConstantInitializerToTagTransformer.class); private static final ConstantInitializerToTagTransformer INSTANCE = new ConstantInitializerToTagTransformer(); public static ConstantInitializerToTagTransformer v() { return INSTANCE; } @Override protected void internalTransform(String phaseName, Map<String, String> options) { for (SootClass sc : Scene.v().getClasses()) { transformClass(sc, false); } } /** * Transforms the given class, i.e. scans for a {@code <clinit>} method and generates new constant value tags for all * constant assignments to static final fields. * * @param sc * The class to transform * @param removeAssignments * True if the assignments inside the {@code <clinit>} method shall be removed, otherwise false */ public void transformClass(SootClass sc, boolean removeAssignments) { // If this class has no <clinit> method, we're done SootMethod smInit = sc.getMethodByNameUnsafe("<clinit>"); if (smInit == null || !smInit.isConcrete()) { return; } Set<SootField> nonConstantFields = new HashSet<SootField>(); Map<SootField, ConstantValueTag> newTags = new HashMap<SootField, ConstantValueTag>(); // in case of mismatch between code/constant table values, constant tags are removed Set<SootField> removeTagList = new HashSet<SootField>(); for (Iterator<Unit> itU = smInit.getActiveBody().getUnits().snapshotIterator(); itU.hasNext();) { Unit u = itU.next(); if (u instanceof AssignStmt) { final AssignStmt assign = (AssignStmt) u; final Value leftOp = assign.getLeftOp(); if (leftOp instanceof StaticFieldRef) { final Value rightOp = assign.getRightOp(); if (rightOp instanceof Constant) { SootField field = null; try { field = ((StaticFieldRef) leftOp).getField(); if (field == null || nonConstantFields.contains(field)) { continue; } } catch (ConflictingFieldRefException ex) { // Ignore this statement continue; } if (field.getDeclaringClass().equals(sc) && field.isStatic() && field.isFinal()) { // Do we already have a constant value for this field? boolean found = false; for (Tag t : field.getTags()) { if (t instanceof ConstantValueTag) { if (checkConstantValue((ConstantValueTag) t, (Constant) rightOp)) { // If we assign the same value we also have // in the constant table, we can get rid of // the assignment. if (removeAssignments) { itU.remove(); } } else { logger.debug("WARNING: Constant value for field '" + field + "' mismatch between code (" + rightOp + ") and constant table (" + t + ")"); removeTagList.add(field); } found = true; break; } } if (!found) { // If we already have a different tag for this field, the // value is not constant and we do not associate the tags. if (!checkConstantValue(newTags.get(field), (Constant) rightOp)) { nonConstantFields.add(field); newTags.remove(field); removeTagList.add(field); continue; } ConstantValueTag newTag = createConstantTagFromValue((Constant) rightOp); if (newTag != null) { newTags.put(field, newTag); } } } } else { // a non-constant is assigned to the field try { SootField sf = ((StaticFieldRef) leftOp).getField(); if (sf != null) { removeTagList.add(sf); } } catch (ConflictingFieldRefException ex) { // let's assume that a broken field doesn't cause any harm } } } } } // Do the actual assignment for (Entry<SootField, ConstantValueTag> entry : newTags.entrySet()) { SootField field = entry.getKey(); if (!removeTagList.contains(field)) { field.addTag(entry.getValue()); } } if (removeAssignments && !newTags.isEmpty()) { for (Iterator<Unit> itU = smInit.getActiveBody().getUnits().snapshotIterator(); itU.hasNext();) { Unit u = itU.next(); if (u instanceof AssignStmt) { final Value leftOp = ((AssignStmt) u).getLeftOp(); if (leftOp instanceof FieldRef) { try { SootField fld = ((FieldRef) leftOp).getField(); if (fld != null && newTags.containsKey(fld)) { itU.remove(); } } catch (ConflictingFieldRefException ex) { // Ignore broken code } } } } } // remove constant tags for (SootField sf : removeTagList) { if (removeTagList.contains(sf)) { List<Tag> toRemoveTagList = new ArrayList<Tag>(); for (Tag t : sf.getTags()) { if (t instanceof ConstantValueTag) { toRemoveTagList.add(t); } } for (Tag t : toRemoveTagList) { sf.getTags().remove(t); } } } } private ConstantValueTag createConstantTagFromValue(Constant rightOp) { if (rightOp instanceof DoubleConstant) { return new DoubleConstantValueTag(((DoubleConstant) rightOp).value); } else if (rightOp instanceof FloatConstant) { return new FloatConstantValueTag(((FloatConstant) rightOp).value); } else if (rightOp instanceof IntConstant) { return new IntegerConstantValueTag(((IntConstant) rightOp).value); } else if (rightOp instanceof LongConstant) { return new LongConstantValueTag(((LongConstant) rightOp).value); } else if (rightOp instanceof StringConstant) { return new StringConstantValueTag(((StringConstant) rightOp).value); } else { return null; } } private boolean checkConstantValue(ConstantValueTag t, Constant rightOp) { if (t == null || rightOp == null) { return true; } if (t instanceof DoubleConstantValueTag) { return (rightOp instanceof DoubleConstant) && (((DoubleConstantValueTag) t).getDoubleValue() == ((DoubleConstant) rightOp).value); } else if (t instanceof FloatConstantValueTag) { return (rightOp instanceof FloatConstant) && (((FloatConstantValueTag) t).getFloatValue() == ((FloatConstant) rightOp).value); } else if (t instanceof IntegerConstantValueTag) { return (rightOp instanceof IntConstant) && (((IntegerConstantValueTag) t).getIntValue() == ((IntConstant) rightOp).value); } else if (t instanceof LongConstantValueTag) { return (rightOp instanceof LongConstant) && (((LongConstantValueTag) t).getLongValue() == ((LongConstant) rightOp).value); } else if (t instanceof StringConstantValueTag) { return (rightOp instanceof StringConstant) && ((StringConstantValueTag) t).getStringValue().equals(((StringConstant) rightOp).value); } else { // We don't know the type, so we assume it's alright return true; } } }
9,941
37.091954
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ConstantValueToInitializerTransformer.java
package soot.toolkits.scalar; /*- * #%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.lang.reflect.Modifier; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import soot.Body; import soot.Local; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.UnitPatchingChain; import soot.Value; import soot.ValueBox; import soot.VoidType; import soot.jimple.Constant; import soot.jimple.DoubleConstant; import soot.jimple.FieldRef; import soot.jimple.FloatConstant; import soot.jimple.IntConstant; import soot.jimple.InvokeExpr; import soot.jimple.Jimple; import soot.jimple.LongConstant; import soot.jimple.ReturnVoidStmt; import soot.jimple.SpecialInvokeExpr; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.tagkit.DoubleConstantValueTag; import soot.tagkit.FloatConstantValueTag; import soot.tagkit.IntegerConstantValueTag; import soot.tagkit.LongConstantValueTag; import soot.tagkit.StringConstantValueTag; import soot.tagkit.Tag; import soot.util.Chain; /** * Transformer that creates a static initializer which sets constant values into final static fields to emulate the * initializations that are done through the constant table in CLASS and DEX code, but that are not supported by Jimple. * * @author Steven Arzt */ public class ConstantValueToInitializerTransformer extends SceneTransformer { public static ConstantValueToInitializerTransformer v() { return new ConstantValueToInitializerTransformer(); } @Override protected void internalTransform(String phaseName, Map<String, String> options) { for (SootClass sc : Scene.v().getClasses()) { transformClass(sc); } } public void transformClass(SootClass sc) { final Jimple jimp = Jimple.v(); SootMethod smInit = null; Set<SootField> alreadyInitialized = new HashSet<SootField>(); for (SootField sf : sc.getFields()) { // We can only create an initializer for all fields that have the // constant value tag. In case of non-static fields, this provides // a default value // If there is already an initializer for this field, we do not // generate a second one (this does not concern overwriting in // user code) if (alreadyInitialized.contains(sf)) { continue; } // Look for constant values for (Tag t : sf.getTags()) { Constant constant = null; if (t instanceof DoubleConstantValueTag) { double value = ((DoubleConstantValueTag) t).getDoubleValue(); constant = DoubleConstant.v(value); } else if (t instanceof FloatConstantValueTag) { float value = ((FloatConstantValueTag) t).getFloatValue(); constant = FloatConstant.v(value); } else if (t instanceof IntegerConstantValueTag) { int value = ((IntegerConstantValueTag) t).getIntValue(); constant = IntConstant.v(value); } else if (t instanceof LongConstantValueTag) { long value = ((LongConstantValueTag) t).getLongValue(); constant = LongConstant.v(value); } else if (t instanceof StringConstantValueTag) { String value = ((StringConstantValueTag) t).getStringValue(); constant = StringConstant.v(value); } if (constant != null) { if (sf.isStatic()) { Stmt initStmt = jimp.newAssignStmt(jimp.newStaticFieldRef(sf.makeRef()), constant); if (smInit == null) { smInit = getOrCreateInitializer(sc, alreadyInitialized); } if (smInit != null) { smInit.getActiveBody().getUnits().addFirst(initStmt); } } else { // We have a default value for a non-static field // So we have to get it into all <init>s, which // do not call other constructors of the same class. // It has to be after the constructor call to the super class // so that it can be potentially overwritten within the method, // without the default value taking precedence. for (SootMethod m : sc.getMethods()) { if (m.isConstructor()) { final Body body = m.retrieveActiveBody(); final UnitPatchingChain units = body.getUnits(); Local thisLocal = null; for (Unit u : units) { if (u instanceof Stmt) { final Stmt s = (Stmt) u; if (s.containsInvokeExpr()) { final InvokeExpr expr = s.getInvokeExpr(); if (expr instanceof SpecialInvokeExpr) { if (expr.getMethod().getDeclaringClass() == sc) { // Calling another constructor in the same class break; } if (thisLocal == null) { thisLocal = body.getThisLocal(); } Stmt initStmt = jimp.newAssignStmt(jimp.newInstanceFieldRef(thisLocal, sf.makeRef()), constant); units.insertAfter(initStmt, s); break; } } } } } } } } } } if (smInit != null) { Chain<Unit> units = smInit.getActiveBody().getUnits(); if (units.isEmpty() || !(units.getLast() instanceof ReturnVoidStmt)) { units.add(jimp.newReturnVoidStmt()); } } } private SootMethod getOrCreateInitializer(SootClass sc, Set<SootField> alreadyInitialized) { // Create a static initializer if we don't already have one SootMethod smInit = sc.getMethodByNameUnsafe(SootMethod.staticInitializerName); if (smInit == null) { smInit = Scene.v().makeSootMethod(SootMethod.staticInitializerName, Collections.<Type>emptyList(), VoidType.v()); smInit.setActiveBody(Jimple.v().newBody(smInit)); sc.addMethod(smInit); smInit.setModifiers(Modifier.PUBLIC | Modifier.STATIC); } else if (smInit.isPhantom()) { return null; } else { // We need to collect those variables that are already initialized somewhere for (Unit u : smInit.retrieveActiveBody().getUnits()) { Stmt s = (Stmt) u; for (ValueBox vb : s.getDefBoxes()) { Value value = vb.getValue(); if (value instanceof FieldRef) { alreadyInitialized.add(((FieldRef) value).getField()); } } } } return smInit; } }
7,486
36.248756
120
java
soot
soot-master/src/main/java/soot/toolkits/scalar/FastColorer.java
package soot.toolkits.scalar; /*- * #%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.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.Body; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.toolkits.exceptions.PedanticThrowAnalysis; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.util.ArraySet; /** * Provides methods for register coloring. Jimple uses these methods to assign the local slots appropriately. */ public class FastColorer { private FastColorer() { } /** * Provides a coloring for the locals of <code>unitBody</code>, attempting to not split locals assigned the same name in * the original Jimple. */ public static <G> void unsplitAssignColorsToLocals(Body unitBody, Map<Local, G> localToGroup, Map<Local, Integer> localToColor, Map<G, Integer> groupToColorCount) { // To understand why a pedantic throw analysis is required, see comment // in assignColorsToLocals method final ExceptionalUnitGraph unitGraph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(unitBody, PedanticThrowAnalysis.v(), Options.v().omit_excepting_unit_edges()); final UnitInterferenceGraph intGraph = new UnitInterferenceGraph(unitBody, localToGroup, new SimpleLiveLocals(unitGraph), unitGraph); Map<Local, String> localToOriginalName = new HashMap<Local, String>(); // Map each local variable to its original name for (Local local : intGraph.getLocals()) { String name = local.getName(); int signIndex = name.indexOf('#'); if (signIndex >= 0) { name = name.substring(0, signIndex); } localToOriginalName.put(local, name); } // maps an original name to the colors being used for it Map<StringGroupPair, List<Integer>> originalNameAndGroupToColors = new HashMap<StringGroupPair, List<Integer>>(); // Assign a color for each local. { int[] freeColors = new int[10]; for (Local local : intGraph.getLocals()) { if (localToColor.containsKey(local)) { // Already assigned, probably a parameter continue; } G group = localToGroup.get(local); int colorCount = groupToColorCount.get(group); if (freeColors.length < colorCount) { freeColors = new int[Math.max(freeColors.length * 2, colorCount)]; } // Set all colors to free. Arrays.fill(freeColors, 0, colorCount, 1); // Remove unavailable colors for this local { Local[] interferences = intGraph.getInterferencesOf(local); if (interferences != null) { for (Local element : interferences) { if (localToColor.containsKey(element)) { int usedColor = localToColor.get(element); freeColors[usedColor] = 0; } } } } // Assign a color to this local. { StringGroupPair key = new StringGroupPair(localToOriginalName.get(local), group); List<Integer> originalNameColors = originalNameAndGroupToColors.get(key); if (originalNameColors == null) { originalNameColors = new ArrayList<Integer>(); originalNameAndGroupToColors.put(key, originalNameColors); } boolean found = false; Integer assignedColor = 0; // Check if the colors assigned to this original name is already free for (Integer color : originalNameColors) { if (freeColors[color] == 1) { found = true; assignedColor = color; } } if (!found) { assignedColor = colorCount++; groupToColorCount.put(group, colorCount); originalNameColors.add(assignedColor); } localToColor.put(local, assignedColor); } } } } /** * Provides an economical coloring for the locals of <code>unitBody</code>. */ public static <G> void assignColorsToLocals(Body unitBody, Map<Local, G> localToGroup, Map<Local, Integer> localToColor, Map<G, Integer> groupToColorCount) { // Build a CFG using a pedantic throw analysis to prevent JVM // "java.lang.VerifyError: Incompatible argument to function" errors. final ExceptionalUnitGraph unitGraph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(unitBody, PedanticThrowAnalysis.v(), Options.v().omit_excepting_unit_edges()); final UnitInterferenceGraph intGraph = new UnitInterferenceGraph(unitBody, localToGroup, new SimpleLiveLocals(unitGraph), unitGraph); // Sort the locals first to maximize the locals per color. We first // assign those locals that have many conflicts and then assign the // easier ones to those color groups. List<Local> sortedLocals = new ArrayList<Local>(intGraph.getLocals()); Collections.sort(sortedLocals, new Comparator<Local>() { @Override public int compare(Local o1, Local o2) { return intGraph.getInterferenceCount(o2) - intGraph.getInterferenceCount(o1); } }); for (Local local : sortedLocals) { if (localToColor.containsKey(local)) { // Already assigned, probably a parameter continue; } G group = localToGroup.get(local); int colorCount = groupToColorCount.get(group); BitSet blockedColors = new BitSet(colorCount); // Block unavailable colors for this local { Local[] interferences = intGraph.getInterferencesOf(local); if (interferences != null) { for (Local element : interferences) { if (localToColor.containsKey(element)) { blockedColors.set(localToColor.get(element)); } } } } // Assign a color to this local. { int assignedColor = -1; for (int i = 0; i < colorCount; i++) { if (!blockedColors.get(i)) { assignedColor = i; break; } } if (assignedColor < 0) { assignedColor = colorCount++; groupToColorCount.put(group, colorCount); } localToColor.put(local, assignedColor); } } } /** Implementation of a unit interference graph. */ private static class UnitInterferenceGraph { // Maps a local to its interfering locals. final Map<Local, Set<Local>> localToLocals; final List<Local> locals; public UnitInterferenceGraph(Body body, Map<Local, ? extends Object> localToGroup, LiveLocals liveLocals, ExceptionalUnitGraph unitGraph) { this.locals = new ArrayList<Local>(body.getLocals()); this.localToLocals = new HashMap<Local, Set<Local>>(body.getLocalCount() * 2 + 1, 0.7f); // Go through code, noting interferences for (Unit unit : body.getUnits()) { List<ValueBox> defBoxes = unit.getDefBoxes(); // Note interferences if this stmt is a definition if (!defBoxes.isEmpty()) { // Only one def box is supported if (defBoxes.size() != 1) { throw new RuntimeException("invalid number of def boxes"); } // Remove those locals that are only live on exceptional flows. // If we have code like this: // a = 42 // b = foo() // catch -> print(a) // we can transform it to: // a = 42 // a = foo() // catch -> print(a) // If an exception is thrown, at the second assignment, the // assignment will not actually happen and "a" will be unchanged. // SA, 2018-02-02: The above is only correct if there is // nothing else in the trap. Take this example: // a = 42 // b = foo() // throw new VeryBadException() // catch -> print(a) // In that case, the value of "b" **will** be changed before // we reach the handler (assuming that foo() does not already // throw the exception). We may want to have a more complex // reasoning here some day, but I'll leave it as is for now. Value defValue = defBoxes.get(0).getValue(); if (defValue instanceof Local) { Local defLocal = (Local) defValue; Set<Local> liveLocalsAtUnit = new HashSet<Local>(); for (Unit succ : unitGraph.getSuccsOf(unit)) { liveLocalsAtUnit.addAll(liveLocals.getLiveLocalsBefore(succ)); } for (Local otherLocal : liveLocalsAtUnit) { if (localToGroup.get(otherLocal).equals(localToGroup.get(defLocal))) { setInterference(defLocal, otherLocal); } } } } } } public List<Local> getLocals() { return locals; } public void setInterference(Local l1, Local l2) { // We need the mapping in both directions // l1 -> l2 Set<Local> locals = localToLocals.get(l1); if (locals == null) { locals = new ArraySet<Local>(); localToLocals.put(l1, locals); } locals.add(l2); // l2 -> l1 locals = localToLocals.get(l2); if (locals == null) { locals = new ArraySet<Local>(); localToLocals.put(l2, locals); } locals.add(l1); } public int getInterferenceCount(Local l) { Set<Local> localSet = localToLocals.get(l); return localSet == null ? 0 : localSet.size(); } public Local[] getInterferencesOf(Local l) { Set<Local> localSet = localToLocals.get(l); if (localSet == null) { return null; } else { return localSet.toArray(new Local[localSet.size()]); } } } /** Binds together a String and a Group. */ private static class StringGroupPair { private final String string; private final Object group; public StringGroupPair(String s, Object g) { this.string = s; this.group = g; } @Override public boolean equals(Object p) { if (p instanceof StringGroupPair) { StringGroupPair temp = (StringGroupPair) p; return this.string.equals(temp.string) && this.group.equals(temp.group); } else { return false; } } @Override public int hashCode() { return string.hashCode() * 101 + group.hashCode() + 17; } } }
11,453
32.2
122
java
soot
soot-master/src/main/java/soot/toolkits/scalar/FlowAnalysis.java
package soot.toolkits.scalar; /*- * #%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.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import soot.baf.GotoInst; import soot.jimple.GotoStmt; import soot.options.Options; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.interaction.FlowInfo; import soot.toolkits.graph.interaction.InteractionHandler; import soot.util.Numberable; import soot.util.PriorityQueue; /** * An abstract class providing a framework for carrying out dataflow analysis. Subclassing either BackwardFlowAnalysis or * ForwardFlowAnalysis and providing implementations for the abstract methods will allow Soot to compute the corresponding * flow analysis. */ public abstract class FlowAnalysis<N, A> extends AbstractFlowAnalysis<N, A> { public enum Flow { IN { @Override <F> F getFlow(Entry<?, F> e) { return e.inFlow; } }, OUT { @Override <F> F getFlow(Entry<?, F> e) { return e.outFlow; } }; abstract <F> F getFlow(Entry<?, F> e); } static class Entry<D, F> implements Numberable { final D data; int number; /** * This Entry is part of a real scc. */ boolean isRealStronglyConnected; Entry<D, F>[] in; Entry<D, F>[] out; F inFlow; F outFlow; @SuppressWarnings("unchecked") Entry(D u, Entry<D, F> pred) { in = new Entry[] { pred }; data = u; number = Integer.MIN_VALUE; isRealStronglyConnected = false; } @Override public String toString() { return data == null ? "" : data.toString(); } @Override public void setNumber(int n) { number = n; } @Override public int getNumber() { return number; } } static enum Orderer { INSTANCE; /** * Creates a new {@code Entry} graph based on a {@code DirectedGraph}. This includes pseudo topological order, local * access for predecessors and successors, a graph entry-point, a {@code Numberable} interface and a real strongly * connected component marker. * * @param g * @param gv * @param entryFlow * @return */ <D, F> List<Entry<D, F>> newUniverse(DirectedGraph<D> g, GraphView gv, F entryFlow, boolean isForward) { final int n = g.size(); Deque<Entry<D, F>> s = new ArrayDeque<Entry<D, F>>(n); List<Entry<D, F>> universe = new ArrayList<Entry<D, F>>(n); Map<D, Entry<D, F>> visited = new HashMap<D, Entry<D, F>>(((n + 1) * 4) / 3); // out of universe node Entry<D, F> superEntry = new Entry<D, F>(null, null); List<D> entries = null; List<D> actualEntries = gv.getEntries(g); if (!actualEntries.isEmpty()) { // normal cases: there is at least // one return statement for a backward analysis // or one entry statement for a forward analysis entries = actualEntries; } else { // cases without any entry statement if (isForward) { // case of a forward flow analysis on // a method without any entry point throw new RuntimeException("error: no entry point for method in forward analysis"); } else { // case of backward analysis on // a method which potentially has // an infinite loop and no return statement entries = new ArrayList<D>(); // a single head is expected assert g.getHeads().size() == 1; D head = g.getHeads().get(0); // collect all 'goto' statements to catch the 'goto' from the infinite loop Set<D> visitedNodes = new HashSet<D>(); List<D> workList = new ArrayList<D>(); workList.add(head); for (D current; !workList.isEmpty();) { current = workList.remove(0); visitedNodes.add(current); // only add 'goto' statements if (current instanceof GotoInst || current instanceof GotoStmt) { entries.add(current); } for (D next : g.getSuccsOf(current)) { if (visitedNodes.contains(next)) { continue; } workList.add(next); } } // if (entries.isEmpty()) { throw new RuntimeException("error: backward analysis on an empty entry set."); } } } visitEntry(visited, superEntry, entries); superEntry.inFlow = entryFlow; superEntry.outFlow = entryFlow; @SuppressWarnings("unchecked") Entry<D, F>[] sv = new Entry[g.size()]; int[] si = new int[g.size()]; int index = 0; int i = 0; Entry<D, F> v = superEntry; for (;;) { if (i < v.out.length) { Entry<D, F> w = v.out[i++]; // an unvisited child node if (w.number == Integer.MIN_VALUE) { w.number = s.size(); s.add(w); visitEntry(visited, w, gv.getOut(g, w.data)); // save old si[index] = i; sv[index] = v; index++; i = 0; v = w; } } else { if (index == 0) { assert universe.size() <= g.size(); Collections.reverse(universe); return universe; } universe.add(v); sccPop(s, v); // restore old index--; v = sv[index]; i = si[index]; } } } private <D, F> Entry<D, F>[] visitEntry(Map<D, Entry<D, F>> visited, Entry<D, F> v, List<D> out) { final int n = out.size(); @SuppressWarnings("unchecked") Entry<D, F>[] a = new Entry[n]; assert (out instanceof RandomAccess); for (int i = 0; i < n; i++) { a[i] = getEntryOf(visited, out.get(i), v); } return v.out = a; } private <D, F> Entry<D, F> getEntryOf(Map<D, Entry<D, F>> visited, D d, Entry<D, F> v) { // either we reach a new node or a merge node, the latter one is rare // so put and restore should be better that a lookup // add and restore if required Entry<D, F> newEntry = new Entry<D, F>(d, v); Entry<D, F> oldEntry = visited.putIfAbsent(d, newEntry); // no restore required if (oldEntry == null) { return newEntry; } // adding self ref (real strongly connected with itself) if (oldEntry == v) { oldEntry.isRealStronglyConnected = true; } // merge nodes are rare, so this is ok int l = oldEntry.in.length; oldEntry.in = Arrays.copyOf(oldEntry.in, l + 1); oldEntry.in[l] = v; return oldEntry; } private <D, F> void sccPop(Deque<Entry<D, F>> s, Entry<D, F> v) { int min = v.number; for (Entry<D, F> e : v.out) { assert e.number > Integer.MIN_VALUE; min = Math.min(min, e.number); } // not our SCC if (min != v.number) { v.number = min; return; } // we only want real SCCs (size > 1) Entry<D, F> w = s.removeLast(); w.number = Integer.MAX_VALUE; if (w == v) { return; } w.isRealStronglyConnected = true; for (;;) { w = s.removeLast(); assert w.number >= v.number; w.isRealStronglyConnected = true; w.number = Integer.MAX_VALUE; if (w == v) { assert w.in.length >= 2; return; } } } } enum InteractionFlowHandler { NONE, FORWARD { @Override public <A, N> void handleFlowIn(FlowAnalysis<N, A> a, N s) { beforeEvent(stop(s), a, s); } @Override public <A, N> void handleFlowOut(FlowAnalysis<N, A> a, N s) { afterEvent(InteractionHandler.v(), a, s); } }, BACKWARD { @Override public <A, N> void handleFlowIn(FlowAnalysis<N, A> a, N s) { afterEvent(stop(s), a, s); } @Override public <A, N> void handleFlowOut(FlowAnalysis<N, A> a, N s) { beforeEvent(InteractionHandler.v(), a, s); } }; <A, N> void beforeEvent(InteractionHandler i, FlowAnalysis<N, A> a, N s) { A savedFlow = a.filterUnitToBeforeFlow.get(s); if (savedFlow == null) { savedFlow = a.newInitialFlow(); } a.copy(a.unitToBeforeFlow.get(s), savedFlow); i.handleBeforeAnalysisEvent(new FlowInfo<A, N>(savedFlow, s, true)); } <A, N> void afterEvent(InteractionHandler i, FlowAnalysis<N, A> a, N s) { A savedFlow = a.filterUnitToAfterFlow.get(s); if (savedFlow == null) { savedFlow = a.newInitialFlow(); } a.copy(a.unitToAfterFlow.get(s), savedFlow); i.handleAfterAnalysisEvent(new FlowInfo<A, N>(savedFlow, s, false)); } InteractionHandler stop(Object s) { InteractionHandler h = InteractionHandler.v(); List<?> stopList = h.getStopUnitList(); if (stopList != null && stopList.contains(s)) { h.handleStopAtNodeEvent(s); } return h; } public <A, N> void handleFlowIn(FlowAnalysis<N, A> a, N s) { } public <A, N> void handleFlowOut(FlowAnalysis<N, A> a, N s) { } } enum GraphView { BACKWARD { @Override <N> List<N> getEntries(DirectedGraph<N> g) { return g.getTails(); } @Override <N> List<N> getOut(DirectedGraph<N> g, N s) { return g.getPredsOf(s); } }, FORWARD { @Override <N> List<N> getEntries(DirectedGraph<N> g) { return g.getHeads(); } @Override <N> List<N> getOut(DirectedGraph<N> g, N s) { return g.getSuccsOf(s); } }; abstract <N> List<N> getEntries(DirectedGraph<N> g); abstract <N> List<N> getOut(DirectedGraph<N> g, N s); } /** Maps graph nodes to OUT sets. */ protected final Map<N, A> unitToAfterFlow; /** Filtered: Maps graph nodes to OUT sets. */ protected Map<N, A> filterUnitToAfterFlow; /** Constructs a flow analysis on the given <code>DirectedGraph</code>. */ public FlowAnalysis(DirectedGraph<N> graph) { super(graph); this.unitToAfterFlow = new IdentityHashMap<N, A>(graph.size() * 2 + 1); this.filterUnitToAfterFlow = Collections.emptyMap(); } /** * Given the merge of the <code>out</code> sets, compute the <code>in</code> set for <code>s</code> (or in to out, * depending on direction). * * This function often causes confusion, because the same interface is used for both forward and backward flow analyses. * The first parameter is always the argument to the flow function (i.e. it is the "in" set in a forward analysis and the * "out" set in a backward analysis), and the third parameter is always the result of the flow function (i.e. it is the * "out" set in a forward analysis and the "in" set in a backward analysis). * * @param in * the input flow * @param d * the current node * @param out * the returned flow **/ protected abstract void flowThrough(A in, N d, A out); /** Accessor function returning value of OUT set for s. */ public A getFlowAfter(N s) { A a = unitToAfterFlow.get(s); return a == null ? newInitialFlow() : a; } @Override public A getFlowBefore(N s) { A a = unitToBeforeFlow.get(s); return a == null ? newInitialFlow() : a; } private void initFlow(Iterable<Entry<N, A>> universe, Map<N, A> in, Map<N, A> out) { assert universe != null; assert in != null; assert out != null; // If a node has only a single in-flow, the in-flow is always equal // to the out-flow if its predecessor, so we use the same object. // this saves memory and requires less object creation and copy calls. // Furthermore a node can be marked as omissible, this allows us to use // the same "flow-set" for out-flow and in-flow. A merge node with within // a real scc cannot be omitted, as it could cause endless loops within // the fixpoint-iteration! for (Entry<N, A> n : universe) { boolean omit = true; if (n.in.length > 1) { n.inFlow = newInitialFlow(); // no merge points in loops omit = !n.isRealStronglyConnected; } else { assert n.in.length == 1 : "missing superhead"; n.inFlow = getFlow(n.in[0], n); assert n.inFlow != null : "topological order is broken"; } if (omit && omissible(n.data)) { // We could recalculate the graph itself but thats more expensive than // just falling through such nodes. n.outFlow = n.inFlow; } else { n.outFlow = newInitialFlow(); } // for legacy api in.put(n.data, n.inFlow); out.put(n.data, n.outFlow); } } /** * If a flow node can be omitted return <code>true</code>, otherwise <code>false</code>. There is no guarantee a node will * be omitted. A omissible node does not influence the result of an analysis. * * If you are unsure, don't overwrite this method * * @param n * the node to check * @return <code>false</code> */ protected boolean omissible(N n) { return false; } /** * You can specify which flow set you would like to use of node {@code from} * * @param from * @param mergeNode * @return Flow.OUT */ protected Flow getFlow(N from, N mergeNode) { return Flow.OUT; } private A getFlow(Entry<N, A> o, Entry<N, A> e) { return (o.inFlow == o.outFlow) ? o.outFlow : getFlow(o.data, e.data).getFlow(o); } private void meetFlows(Entry<N, A> e) { assert e.in.length >= 1; if (e.in.length > 1) { boolean copy = true; for (Entry<N, A> o : e.in) { A flow = getFlow(o, e); if (copy) { copy = false; copy(flow, e.inFlow); } else { mergeInto(e.data, e.inFlow, flow); } } } } final int doAnalysis(GraphView gv, InteractionFlowHandler ifh, Map<N, A> inFlow, Map<N, A> outFlow) { assert gv != null; assert ifh != null; ifh = Options.v().interactive_mode() ? ifh : InteractionFlowHandler.NONE; final List<Entry<N, A>> universe = Orderer.INSTANCE.newUniverse(graph, gv, entryInitialFlow(), isForward()); initFlow(universe, inFlow, outFlow); Queue<Entry<N, A>> q = PriorityQueue.of(universe, true); // Perform fixed point flow analysis for (int numComputations = 0;; numComputations++) { Entry<N, A> e = q.poll(); if (e == null) { return numComputations; } meetFlows(e); // Compute beforeFlow and store it. ifh.handleFlowIn(this, e.data); boolean hasChanged = flowThrough(e); ifh.handleFlowOut(this, e.data); // Update queue appropriately if (hasChanged) { q.addAll(Arrays.asList(e.out)); } } } private boolean flowThrough(Entry<N, A> d) { // omitted, just fall through if (d.inFlow == d.outFlow) { assert !d.isRealStronglyConnected || d.in.length == 1; return true; } if (d.isRealStronglyConnected) { // A flow node that is influenced by at least one back-reference. // It's essential to check if "flowThrough" changes the result. // This requires the calculation of "equals", which itself // can be really expensive - depending on the used flow-model. // Depending on the "merge"+"flowThrough" costs, it can be cheaper // to fall through. Only nodes with real back-references always // need to be checked for changes A out = newInitialFlow(); flowThrough(d.inFlow, d.data, out); if (out.equals(d.outFlow)) { return false; } // copy back the result, as it has changed copyFreshToExisting(out, d.outFlow); return true; } // no back-references, just calculate "flowThrough" flowThrough(d.inFlow, d.data, d.outFlow); return true; } /** * Copies a *fresh* copy of in to dest. The input is not referenced somewhere else. This allows subclasses for a smarter * and faster copying. * * @param in * @param dest */ protected void copyFreshToExisting(A in, A dest) { if (in instanceof FlowSet && dest instanceof FlowSet) { FlowSet<?> fin = (FlowSet<?>) in; FlowSet fdest = (FlowSet) dest; fin.copyFreshToExisting(fdest); } else { copy(in, dest); } } }
17,492
27.961921
124
java
soot
soot-master/src/main/java/soot/toolkits/scalar/FlowSensitiveConstantPropagator.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Phong Co * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.BitSet; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.Local; import soot.Scene; import soot.Singletons; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.dexpler.DexNullArrayRefTransformer; import soot.dexpler.DexNullThrowTransformer; import soot.jimple.AssignStmt; import soot.jimple.CmpgExpr; import soot.jimple.CmplExpr; import soot.jimple.Constant; import soot.jimple.DefinitionStmt; import soot.jimple.DoubleConstant; import soot.jimple.FloatConstant; import soot.jimple.IdentityStmt; import soot.jimple.IfStmt; import soot.jimple.IntConstant; import soot.jimple.LongConstant; import soot.jimple.RealConstant; import soot.jimple.Stmt; import soot.jimple.ThrowStmt; import soot.jimple.internal.ImmediateBox; import soot.jimple.toolkits.scalar.CopyPropagator; import soot.options.Options; import soot.tagkit.Tag; import soot.toolkits.exceptions.ThrowAnalysis; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.util.LocalBitSetPacker; //@formatter:off /** * A constant propagator which can cope with cases like <code>a = 2; b = a; a = b;</code> * * as well as * * <code>if (x) { a = 2; } else { a = 2; } b = a;</code> * * @author Marc Miltenberger * @see BodyTransformer * @see LocalPacker * @see Body */ // @formatter:on public class FlowSensitiveConstantPropagator extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(FlowSensitiveConstantPropagator.class); protected ThrowAnalysis throwAnalysis; protected boolean omitExceptingUnitEdges; public FlowSensitiveConstantPropagator(Singletons.Global g) { } public FlowSensitiveConstantPropagator(ThrowAnalysis ta) { this(ta, false); } public FlowSensitiveConstantPropagator(ThrowAnalysis ta, boolean omitExceptingUnitEdges) { this.throwAnalysis = ta; this.omitExceptingUnitEdges = omitExceptingUnitEdges; } public static FlowSensitiveConstantPropagator v() { return G.v().soot_toolkits_scalar_FlowSensitiveConstantPropagator(); } @Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { if (Options.v().verbose()) { logger.debug("[" + body.getMethod().getName() + "] Splitting for shared initialization of locals..."); } if (throwAnalysis == null) { throwAnalysis = Scene.v().getDefaultThrowAnalysis(); } if (omitExceptingUnitEdges == false) { omitExceptingUnitEdges = Options.v().omit_excepting_unit_edges(); } final LocalBitSetPacker localPacker = new LocalBitSetPacker(body); localPacker.pack(); ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis, omitExceptingUnitEdges); BetterConstantPropagator bcp = createBetterConstantPropagator(graph); bcp.doAnalysis(); boolean propagatedThrow = false; for (Unit u : body.getUnits()) { ConstantState v = bcp.getFlowBefore(u); boolean expectsRealValue = false; if (u instanceof AssignStmt) { AssignStmt assign = ((AssignStmt) u); Value rop = assign.getRightOp(); if (rop instanceof Local) { Local l = (Local) rop; Constant c = v.getConstant(l); if (c != null) { List<Tag> oldTags = assign.getRightOpBox().getTags(); assign.setRightOp((Constant) c); assign.getRightOpBox().getTags().addAll(oldTags); CopyPropagator.copyLineTags(assign.getUseBoxes().get(0), assign); continue; } } expectsRealValue = expectsRealValue(rop); } if (u instanceof IfStmt) { expectsRealValue = expectsRealValue(((IfStmt) u).getCondition()); } for (ValueBox r : u.getUseBoxes()) { if (r instanceof ImmediateBox) { Value src = r.getValue(); if (src instanceof Local) { Constant val = v.getConstant((Local) src); if (val != null) { if (u instanceof ThrowStmt) { propagatedThrow = true; } if (expectsRealValue && !(val instanceof RealConstant)) { if (val instanceof IntConstant) { val = FloatConstant.v(((IntConstant) val).value); } else if (val instanceof LongConstant) { val = DoubleConstant.v(((LongConstant) val).value); } } r.setValue((Constant) val); } } } } } localPacker.unpack(); if (propagatedThrow) { DexNullThrowTransformer.v().transform(body); } DexNullArrayRefTransformer.v().transform(body); } protected BetterConstantPropagator createBetterConstantPropagator(ExceptionalUnitGraph graph) { return new BetterConstantPropagator(graph); } private static boolean expectsRealValue(Value op) { return op instanceof CmpgExpr || op instanceof CmplExpr; } protected static class ConstantState { public BitSet nonConstant = new BitSet(); public Map<Local, Constant> constants = createMap(); protected Map<Local, Constant> createMap() { return new HashMap<>(); } public Constant getConstant(Local l) { Constant r = constants.get(l); return r; } public void setNonConstant(Local l) { nonConstant.set(l.getNumber()); constants.remove(l); } public void setConstant(Local l, Constant value) { if (value == null) { throw new IllegalArgumentException("Not valid"); } constants.put(l, value); nonConstant.clear(l.getNumber()); } public void copyTo(ConstantState dest) { dest.nonConstant = (BitSet) nonConstant.clone(); dest.constants = new HashMap<>(constants); } private void checkConsistency() { for (Local i : constants.keySet()) { if (nonConstant.get(i.getNumber())) { throw new IllegalStateException( "A local seems to be constant and not at the same time: " + i + " (" + i.getNumber() + ")"); } } } @Override public String toString() { return "Non-constants: " + nonConstant + "\nConstants: " + constants; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((constants == null) ? 0 : constants.hashCode()); result = prime * result + ((nonConstant == null) ? 0 : nonConstant.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ConstantState other = (ConstantState) obj; if (nonConstant == null) { if (other.nonConstant != null) { return false; } } else if (!nonConstant.equals(other.nonConstant)) { return false; } if (constants == null) { if (other.constants != null) { return false; } } else if (!constants.equals(other.constants)) { return false; } return true; } public void merge(ConstantState in1, ConstantState in2) { nonConstant.or(in1.nonConstant); nonConstant.or(in2.nonConstant); if (!in1.constants.isEmpty()) { mergeInternal(in1, in2); } if (!in2.constants.isEmpty()) { mergeInternal(in2, in1); } } private void mergeInternal(ConstantState in1, ConstantState in2) { for (Entry<Local, Constant> r : in1.constants.entrySet()) { Local l = r.getKey(); if (in2.nonConstant.get(l.getNumber())) { setNonConstant(l); continue; } Constant rr = in2.getConstant(l); if (rr == null) { setConstant(l, r.getValue()); } else { if (rr.equals(r.getValue())) { setConstant(l, rr); } else { setNonConstant(l); } } } } public void clear() { nonConstant.clear(); constants = createMap(); } public void mergeInto(ConstantState in) { nonConstant.or(in.nonConstant); if (!in.constants.isEmpty()) { mergeInternal(in, this); } Iterator<Local> it = constants.keySet().iterator(); while (it.hasNext()) { if (in.nonConstant.get(it.next().getNumber())) { it.remove(); } } } } protected class BetterConstantPropagator extends ForwardFlowAnalysis<Unit, ConstantState> { public BetterConstantPropagator(DirectedGraph<Unit> graph) { super(graph); } @Override protected boolean omissible(Unit n) { if (!(n instanceof DefinitionStmt)) { return true; } return super.omissible(n); } @Override protected void flowThrough(ConstantState in, Unit d, ConstantState out) { in.copyTo(out); if (d instanceof Stmt) { Stmt s = (Stmt) d; if (s instanceof AssignStmt) { AssignStmt assign = (AssignStmt) s; if (assign.getLeftOp() instanceof Local) { Local l = (Local) assign.getLeftOp(); Object rop = assign.getRightOp(); Constant value = null; if (rop instanceof Constant) { value = (Constant) rop; } else { if (rop instanceof Local) { value = in.getConstant((Local) rop); } } if (value == null) { out.setNonConstant(l); } else { out.setConstant(l, value); } } } else if (s instanceof IdentityStmt) { out.setNonConstant((Local) ((IdentityStmt) s).getLeftOp()); } } } @Override protected ConstantState newInitialFlow() { return new ConstantState(); } @Override protected void mergeInto(Unit succNode, ConstantState inout, ConstantState in) { inout.mergeInto(in); } @Override protected void merge(ConstantState in1, ConstantState in2, ConstantState out) { out.merge(in1, in2); } @Override protected void copy(ConstantState source, ConstantState dest) { if (source == dest) { return; } source.copyTo(dest); } @Override protected void copyFreshToExisting(ConstantState in, ConstantState dest) { // in is fresh, so we can directly reuse the inputs dest.constants = in.constants; dest.nonConstant = in.nonConstant; } } }
11,749
28.228856
110
java
soot
soot-master/src/main/java/soot/toolkits/scalar/FlowSet.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * modified 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.List; /** * Represents information for flow analysis. A FlowSet is an element of a lattice; this lattice might be described by a * FlowUniverse. If add, remove, size, isEmpty, toList and contains are implemented, the lattice must be the powerset of some * set. * * @see: FlowUniverse */ public interface FlowSet<T> extends Iterable<T> { /** * Clones the current FlowSet. */ public FlowSet<T> clone(); /** * returns an empty set, most often more efficient than: <code>((FlowSet)clone()).clear()</code> */ public FlowSet<T> emptySet(); /** * Copies the current FlowSet into dest. */ public void copy(FlowSet<T> dest); /** * Sets this FlowSet to the empty set (more generally, the bottom element of the lattice.) */ public void clear(); /** * Returns the union (join) of this FlowSet and <code>other</code>, putting result into <code>this</code>. */ public void union(FlowSet<T> other); /** * Returns the union (join) of this FlowSet and <code>other</code>, putting result into <code>dest</code>. * <code>dest</code>, <code>other</code> and <code>this</code> could be the same object. */ public void union(FlowSet<T> other, FlowSet<T> dest); /** * Returns the intersection (meet) of this FlowSet and <code>other</code>, putting result into <code>this</code>. */ public void intersection(FlowSet<T> other); /** * Returns the intersection (meet) of this FlowSet and <code>other</code>, putting result into <code>dest</code>. * <code>dest</code>, <code>other</code> and <code>this</code> could be the same object. */ public void intersection(FlowSet<T> other, FlowSet<T> dest); /** * Returns the set difference (this intersect ~other) of this FlowSet and <code>other</code>, putting result into * <code>this</code>. */ public void difference(FlowSet<T> other); /** * Returns the set difference (this intersect ~other) of this FlowSet and <code>other</code>, putting result into * <code>dest</code>. <code>dest</code>, <code>other</code> and <code>this</code> could be the same object. */ public void difference(FlowSet<T> other, FlowSet<T> dest); /** * Returns true if this FlowSet is the empty set. */ public boolean isEmpty(); /* The following methods force the FlowSet to be a powerset. */ /** * Returns the size of the current FlowSet. */ public int size(); /** * Adds <code>obj</code> to <code>this</code>. */ public void add(T obj); /** * puts <code>this</code> union <code>obj</code> into <code>dest</code>. */ public void add(T obj, FlowSet<T> dest); /** * Removes <code>obj</code> from <code>this</code>. */ public void remove(T obj); /** * Puts <code>this</code> minus <code>obj</code> into <code>dest</code>. */ public void remove(T obj, FlowSet<T> dest); /** * Returns true if this FlowSet contains <code>obj</code>. */ public boolean contains(T obj); /** * Returns true if the <code>other</code> FlowSet is a subset of <code>this</code> FlowSet. */ public boolean isSubSet(FlowSet<T> other); /** * returns an iterator over the elements of the flowSet. Note that the iterator might be backed, and hence be faster in the * creation, than doing <code>toList().iterator()</code>. */ @Override public Iterator<T> iterator(); /** * Returns an unbacked list of contained objects for this FlowSet. */ public List<T> toList(); /** * Copies a *fresh* copy of this to dest. The input (this) is not referenced somewhere else. This allows subclasses for a * smarter and faster copying. * * @param in * @param dest */ public default void copyFreshToExisting(FlowSet<T> dest) { copy(dest); } }
4,682
29.019231
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/FlowUniverse.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; /** * Provides an interface of a flow universe, used by an implementation of BoundedFlowSet to do complementation. */ public interface FlowUniverse<E> extends Iterable<E> { /** * returns the number of elements of the universe. * * @return the size of the universe. */ public int size(); /** * returns an iterator over the elements of the universe. * * @return an Iterator over the elements. */ @Override public Iterator<E> iterator(); /** * returns the elements of the universe in form of an array.<br> * The returned array could be backed or not. If you want to be sure that it is unbacked, clone() it. * * @return the elements of the universe. */ public E[] toArray(); }
1,590
27.927273
111
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ForwardBranchedFlowAnalysis.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2000 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.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Timers; import soot.Trap; import soot.Unit; import soot.UnitBox; import soot.options.Options; import soot.toolkits.graph.PseudoTopologicalOrderer; import soot.toolkits.graph.UnitGraph; import soot.toolkits.graph.interaction.FlowInfo; import soot.toolkits.graph.interaction.InteractionHandler; import soot.util.Chain; /** * Abstract class providing an engine for branched forward flow analysis. WARNING: This does not handle exceptional flow as * branches! */ public abstract class ForwardBranchedFlowAnalysis<A> extends BranchedFlowAnalysis<Unit, A> { private static final Logger logger = LoggerFactory.getLogger(ForwardBranchedFlowAnalysis.class); public ForwardBranchedFlowAnalysis(UnitGraph graph) { super(graph); } @Override protected boolean isForward() { return true; } // Accumulate the previous afterFlow sets. private void accumulateAfterFlowSets(Unit s, A[] flowRepositories, List<A> previousAfterFlows) { int repCount = 0; previousAfterFlows.clear(); if (s.fallsThrough()) { copy(unitToAfterFallFlow.get(s).get(0), flowRepositories[repCount]); previousAfterFlows.add(flowRepositories[repCount++]); } if (s.branches()) { for (A fs : getBranchFlowAfter(s)) { copy(fs, flowRepositories[repCount]); previousAfterFlows.add(flowRepositories[repCount++]); } } } // end accumulateAfterFlowSets @Override protected void doAnalysis() { TreeSet<Unit> changedUnits = new TreeSet<Unit>(new Comparator<Unit>() { // map each unit to a distinct integer for a total ordering final Map<Unit, Integer> numbers = new HashMap<Unit, Integer>(); { int i = 1; for (Unit u : new PseudoTopologicalOrderer<Unit>().newList(graph, false)) { numbers.put(u, i); i++; } } @Override public int compare(Unit o1, Unit o2) { return numbers.get(o1) - numbers.get(o2); } }); // initialize unitToIncomingFlowSets final int numNodes = graph.size(); Map<Unit, ArrayList<A>> unitToIncomingFlowSets = new HashMap<Unit, ArrayList<A>>(numNodes * 2 + 1, 0.7f); for (Unit s : graph) { unitToIncomingFlowSets.put(s, new ArrayList<A>()); } int numComputations = 0; int maxBranchSize = 0; // Set initial values and nodes to visit. // WARNING: DO NOT HANDLE THE CASE OF THE TRAPS { Chain<Unit> sl = ((UnitGraph) graph).getBody().getUnits(); for (Unit s : graph) { changedUnits.add(s); unitToBeforeFlow.put(s, newInitialFlow()); if (s.fallsThrough()) { List<A> fl = new ArrayList<A>(); fl.add((newInitialFlow())); unitToAfterFallFlow.put(s, fl); Unit succ = sl.getSuccOf(s); // it's possible for someone to insert some (dead) // fall through code at the very end of a method body if (succ != null) { unitToIncomingFlowSets.get(succ).addAll(fl); } } else { unitToAfterFallFlow.put(s, new ArrayList<A>()); } final List<UnitBox> unitBoxes = s.getUnitBoxes(); List<A> l = new ArrayList<A>(); if (s.branches()) { for (UnitBox ub : unitBoxes) { A f = newInitialFlow(); l.add(f); unitToIncomingFlowSets.get(ub.getUnit()).add(f); } } unitToAfterBranchFlow.put(s, l); if (unitBoxes.size() > maxBranchSize) { maxBranchSize = unitBoxes.size(); } } } // Feng Qian: March 07, 2002 // init entry points final List<Unit> heads = graph.getHeads(); for (Unit s : heads) { // this is a forward flow analysis unitToBeforeFlow.put(s, entryInitialFlow()); } if (treatTrapHandlersAsEntries()) { for (Trap trap : ((UnitGraph) graph).getBody().getTraps()) { unitToBeforeFlow.put(trap.getHandlerUnit(), entryInitialFlow()); } } // Perform fixed point flow analysis { @SuppressWarnings("unchecked") A[] flowRepositories = (A[]) new Object[maxBranchSize + 1]; @SuppressWarnings("unchecked") A[] previousFlowRepositories = (A[]) new Object[maxBranchSize + 1]; for (int i = 0; i < maxBranchSize + 1; i++) { flowRepositories[i] = newInitialFlow(); previousFlowRepositories[i] = newInitialFlow(); } List<A> previousAfterFlows = new ArrayList<A>(); List<A> afterFlows = new ArrayList<A>(); while (!changedUnits.isEmpty()) { Unit s = changedUnits.first(); changedUnits.remove(s); accumulateAfterFlowSets(s, previousFlowRepositories, previousAfterFlows); // Compute and store beforeFlow A beforeFlow = getFlowBefore(s); { Iterator<A> preds = unitToIncomingFlowSets.get(s).iterator(); if (preds.hasNext()) { // Handle the first pred copy(preds.next(), beforeFlow); // Handle remaining preds while (preds.hasNext()) { A otherBranchFlow = preds.next(); A newBeforeFlow = newInitialFlow(); merge(s, beforeFlow, otherBranchFlow, newBeforeFlow); copy(newBeforeFlow, beforeFlow); } if (heads.contains(s)) { mergeInto(s, beforeFlow, entryInitialFlow()); } } } // Compute afterFlow and store it. { List<A> afterFallFlow = unitToAfterFallFlow.get(s); List<A> afterBranchFlow = getBranchFlowAfter(s); if (Options.v().interactive_mode()) { InteractionHandler ih = InteractionHandler.v(); A savedFlow = newInitialFlow(); copy(beforeFlow, savedFlow); FlowInfo<A, Unit> fi = new FlowInfo<A, Unit>(savedFlow, s, true); if (ih.getStopUnitList() != null && ih.getStopUnitList().contains(s)) { ih.handleStopAtNodeEvent(s); } ih.handleBeforeAnalysisEvent(fi); } flowThrough(beforeFlow, s, afterFallFlow, afterBranchFlow); if (Options.v().interactive_mode()) { List<A> l = new ArrayList<A>(); if (!afterFallFlow.isEmpty()) { l.addAll(afterFallFlow); } if (!afterBranchFlow.isEmpty()) { l.addAll(afterBranchFlow); } /* * if (s instanceof soot.jimple.IfStmt){ l.addAll((List)afterFallFlow); l.addAll((List)afterBranchFlow); } else { * l.addAll((List)afterFallFlow); } */ FlowInfo<List<A>, Unit> fi = new FlowInfo<List<A>, Unit>(l, s, false); InteractionHandler.v().handleAfterAnalysisEvent(fi); } numComputations++; } accumulateAfterFlowSets(s, flowRepositories, afterFlows); // Update queue appropriately if (!afterFlows.equals(previousAfterFlows)) { for (Unit succ : graph.getSuccsOf(s)) { changedUnits.add(succ); } } } } // logger.debug(""+graph.getBody().getMethod().getSignature() + // " numNodes: " + numNodes + // " numComputations: " + numComputations + " avg: " + // Main.truncatedOf((double) numComputations / numNodes, 2)); Timers.v().totalFlowNodes += numNodes; Timers.v().totalFlowComputations += numComputations; } // end doAnalysis } // end class ForwardBranchedFlowAnalysis
8,587
31.904215
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ForwardFlowAnalysis.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.toolkits.graph.DirectedGraph; /** * Abstract class that provides the fixed point iteration functionality required by all ForwardFlowAnalyses. */ public abstract class ForwardFlowAnalysis<N, A> extends FlowAnalysis<N, A> { /** * Construct the analysis from a DirectedGraph representation of a Body. */ public ForwardFlowAnalysis(DirectedGraph<N> graph) { super(graph); } @Override protected boolean isForward() { return true; } @Override protected void doAnalysis() { int i = doAnalysis(GraphView.FORWARD, InteractionFlowHandler.FORWARD, unitToBeforeFlow, unitToAfterFlow); soot.Timers.v().totalFlowNodes += graph.size(); soot.Timers.v().totalFlowComputations += i; } }
1,570
29.211538
109
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ForwardFlowAnalysisExtended.java
package soot.toolkits.scalar; /*- * #%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.BitSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.Timers; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.Orderer; import soot.toolkits.graph.PseudoTopologicalOrderer; /** * Abstract class that provides a fixed-point iteration for forward flow analyses that need to distinguish between the * different successors of a unit in an exceptional unit graph. * * Note that this class does not extend FlowAnalysis as it has a different definition of a flow function (namely one that * does not only include the current unit, but also the successor). For the same reason, it does not integrate into the * interactive analysis infrastructure of Soot either. * * @author Steven Arzt */ public abstract class ForwardFlowAnalysisExtended<N, A> { /** Maps graph nodes to IN sets. */ protected Map<N, Map<N, A>> unitToBeforeFlow; /** Maps graph nodes to OUT sets. */ protected Map<N, Map<N, A>> unitToAfterFlow; /** The graph being analysed. */ protected DirectedGraph<N> graph; /** * Construct the analysis from a DirectedGraph representation of a Body. */ public ForwardFlowAnalysisExtended(DirectedGraph<N> graph) { this.graph = graph; this.unitToBeforeFlow = new IdentityHashMap<N, Map<N, A>>(graph.size() * 2 + 1); this.unitToAfterFlow = new IdentityHashMap<N, Map<N, A>>(graph.size() * 2 + 1); } /** * Default implementation constructing a PseudoTopologicalOrderer. * * @return an Orderer to order the nodes for the fixed-point iteration */ protected Orderer<N> constructOrderer() { return new PseudoTopologicalOrderer<N>(); } /** * Returns the flow object corresponding to the initial values for each graph node. */ protected abstract A newInitialFlow(); /** * Returns the initial flow value for entry/exit graph nodes. */ protected abstract A entryInitialFlow(); /** Creates a copy of the <code>source</code> flow object in <code>dest</code>. */ protected abstract void copy(A source, A dest); /** * Compute the merge of the <code>in1</code> and <code>in2</code> sets, putting the result into <code>out</code>. The * behavior of this function depends on the implementation ( it may be necessary to check whether <code>in1</code> and * <code>in2</code> are equal or aliased ). Used by the doAnalysis method. */ protected abstract void merge(A in1, A in2, A out); /** * Merges in1 and in2 into out, just before node succNode. By default, this method just calls merge(A,A,A), ignoring the * node. */ protected void merge(N succNode, A in1, A in2, A out) { merge(in1, in2, out); } /** * Merges in into inout, just before node succNode. */ protected void mergeInto(N succNode, A inout, A in) { A tmp = newInitialFlow(); merge(succNode, inout, in, tmp); copy(tmp, inout); } public A getFromMap(Map<N, Map<N, A>> map, N s, N t) { Map<N, A> m = map.get(s); return (m != null) ? m.get(t) : null; } public void putToMap(Map<N, Map<N, A>> map, N s, N t, A val) { Map<N, A> m = map.get(s); if (m == null) { m = new IdentityHashMap<N, A>(); map.put(s, m); } m.put(t, val); } protected void doAnalysis() { List<N> orderedUnits = constructOrderer().newList(graph, false); final int n = orderedUnits.size(); BitSet head = new BitSet(); BitSet work = new BitSet(n); work.set(0, n); final Map<N, Integer> index = new IdentityHashMap<N, Integer>(n * 2 + 1); { int i = 0; for (N s : orderedUnits) { index.put(s, i++); // Set initial Flows for (N v : graph.getSuccsOf(s)) { putToMap(unitToBeforeFlow, s, v, newInitialFlow()); putToMap(unitToAfterFlow, s, v, newInitialFlow()); } } } // Feng Qian: March 07, 2002 // Set initial values for entry points for (N s : graph.getHeads()) { head.set(index.get(s)); // this is a forward flow analysis for (N v : graph.getSuccsOf(s)) { putToMap(unitToBeforeFlow, s, v, entryInitialFlow()); } } int numComputations = 0; // Perform fixed point flow analysis { A previousFlow = newInitialFlow(); for (int i = work.nextSetBit(0); i >= 0; i = work.nextSetBit(i + 1)) { work.clear(i); N s = orderedUnits.get(i); // For all successors, compute the flow function int k = i; for (N v : graph.getSuccsOf(s)) { A beforeFlow = getFromMap(unitToBeforeFlow, s, v); A afterFlow = getFromMap(unitToAfterFlow, s, v); copy(afterFlow, previousFlow); // Compute and store beforeFlow { final Iterator<N> it = graph.getPredsOf(s).iterator(); if (it.hasNext()) { copy(getFromMap(unitToAfterFlow, it.next(), s), beforeFlow); while (it.hasNext()) { mergeInto(s, beforeFlow, getFromMap(unitToAfterFlow, it.next(), s)); } if (head.get(k)) { mergeInto(s, beforeFlow, entryInitialFlow()); } } } // Compute afterFlow and store it. flowThrough(beforeFlow, s, v, afterFlow); boolean hasChanged = !previousFlow.equals(afterFlow); // Update queue appropriately if (hasChanged) { int j = index.get(v); work.set(j); i = Math.min(i, j - 1); } numComputations++; } } } Timers.v().totalFlowNodes += n; Timers.v().totalFlowComputations += numComputations; } protected abstract void flowThrough(A in, N cur, N next, A out); /** Accessor function returning value of IN set for s. */ public A getFlowBefore(N s) { A beforeFlow = null; final Iterator<N> it = graph.getPredsOf(s).iterator(); if (it.hasNext()) { beforeFlow = getFromMap(unitToAfterFlow, it.next(), s); while (it.hasNext()) { mergeInto(s, beforeFlow, getFromMap(unitToAfterFlow, it.next(), s)); } } return beforeFlow; } }
7,035
30.132743
122
java
soot
soot-master/src/main/java/soot/toolkits/scalar/GuaranteedDefs.java
package soot.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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.toolkits.graph.DominatorsFinder; import soot.toolkits.graph.MHGDominatorsFinder; import soot.toolkits.graph.UnitGraph; /** * Find all locals guaranteed to be defined at (just before) a given program point. * * @author Navindra Umanee **/ public class GuaranteedDefs { private static final Logger logger = LoggerFactory.getLogger(GuaranteedDefs.class); protected final Map<Unit, List<Value>> unitToGuaranteedDefs; public GuaranteedDefs(UnitGraph graph) { if (Options.v().verbose()) { logger.debug("[" + graph.getBody().getMethod().getName() + "] Constructing GuaranteedDefs..."); } this.unitToGuaranteedDefs = new HashMap<Unit, List<Value>>(graph.size() * 2 + 1, 0.7f); GuaranteedDefsAnalysis analysis = new GuaranteedDefsAnalysis(graph); for (Unit s : graph) { FlowSet<Value> set = analysis.getFlowBefore(s); this.unitToGuaranteedDefs.put(s, Collections.unmodifiableList(set.toList())); } } /** * Returns a list of locals guaranteed to be defined at (just before) program point <tt>s</tt>. **/ public List<Value> getGuaranteedDefs(Unit s) { return unitToGuaranteedDefs.get(s); } } /** * Flow analysis to determine all locals guaranteed to be defined at a given program point. **/ class GuaranteedDefsAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Value>> { private static final FlowSet<Value> EMPTY_SET = new ArraySparseSet<Value>(); private final Map<Unit, FlowSet<Value>> unitToGenerateSet; GuaranteedDefsAnalysis(UnitGraph graph) { super(graph); this.unitToGenerateSet = new HashMap<Unit, FlowSet<Value>>(graph.size() * 2 + 1, 0.7f); DominatorsFinder<Unit> df = new MHGDominatorsFinder<Unit>(graph); // pre-compute generate sets for (Unit s : graph) { FlowSet<Value> genSet = EMPTY_SET.clone(); for (Unit dom : df.getDominators(s)) { for (ValueBox box : dom.getDefBoxes()) { Value val = box.getValue(); if (val instanceof Local) { genSet.add(val, genSet); } } } this.unitToGenerateSet.put(s, genSet); } doAnalysis(); } /** * All INs are initialized to the empty set. **/ @Override protected FlowSet<Value> newInitialFlow() { return EMPTY_SET.clone(); } /** * IN(Start) is the empty set **/ @Override protected FlowSet<Value> entryInitialFlow() { return EMPTY_SET.clone(); } /** * OUT is the same as IN plus the genSet. **/ @Override protected void flowThrough(FlowSet<Value> in, Unit unit, FlowSet<Value> out) { // perform generation (kill set is empty) in.union(unitToGenerateSet.get(unit), out); } /** * All paths == Intersection. **/ @Override protected void merge(FlowSet<Value> in1, FlowSet<Value> in2, FlowSet<Value> out) { in1.intersection(in2, out); } @Override protected void copy(FlowSet<Value> source, FlowSet<Value> dest) { source.copy(dest); } }
4,095
28.049645
105
java
soot
soot-master/src/main/java/soot/toolkits/scalar/IdentityPair.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * Copyright (C) 2007 Manu Sridharan * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Just a pair of arbitrary objects. * * @author Ondrej Lhotak * @author Manu Sridharan (genericized it) */ public class IdentityPair<T, U> { protected final T o1; protected final U o2; protected final int hashCode; public IdentityPair(T o1, U o2) { this.o1 = o1; this.o2 = o2; this.hashCode = computeHashCode(); } /** * {@inheritDoc} */ @Override public int hashCode() { return hashCode; } private int computeHashCode() { final int prime = 31; int result = 1; result = prime * result + System.identityHashCode(o1); result = prime * result + System.identityHashCode(o2); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } final IdentityPair<?, ?> other = (IdentityPair<?, ?>) obj; return this.o1 == other.o1 && this.o2 == other.o2; } public T getO1() { return o1; } public U getO2() { return o2; } @Override public String toString() { return "IdentityPair " + o1 + "," + o2; } }
2,042
22.482759
71
java
soot
soot-master/src/main/java/soot/toolkits/scalar/InitAnalysis.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ganesh Sittampalam * Copyright (C) 2007 Eric Bodden * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.toolkits.graph.DirectedBodyGraph; /** * An analysis to check whether or not local variables have been initialised. * * @author Ganesh Sittampalam * @author Eric Bodden */ public class InitAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Local>> { protected final FlowSet<Local> allLocals = new ArraySparseSet<Local>(); public InitAnalysis(DirectedBodyGraph<Unit> g) { super(g); FlowSet<Local> allLocalsRef = this.allLocals; for (Local loc : g.getBody().getLocals()) { allLocalsRef.add(loc); } doAnalysis(); } @Override protected FlowSet<Local> entryInitialFlow() { return new ArraySparseSet<Local>(); } @Override protected FlowSet<Local> newInitialFlow() { FlowSet<Local> ret = new ArraySparseSet<Local>(); allLocals.copy(ret); return ret; } @Override protected void flowThrough(FlowSet<Local> in, Unit unit, FlowSet<Local> out) { in.copy(out); for (ValueBox defBox : unit.getDefBoxes()) { Value lhs = defBox.getValue(); if (lhs instanceof Local) { out.add((Local) lhs); } } } @Override protected void merge(FlowSet<Local> in1, FlowSet<Local> in2, FlowSet<Local> out) { in1.intersection(in2, out); } @Override protected void copy(FlowSet<Local> source, FlowSet<Local> dest) { source.copy(dest); } }
2,300
25.448276
84
java
soot
soot-master/src/main/java/soot/toolkits/scalar/LiveLocals.java
package soot.toolkits.scalar; /*- * #%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; import soot.Local; import soot.Unit; import soot.toolkits.graph.DirectedBodyGraph; /** * Provides an interface for querying for the list of Locals that are live before an after a given unit in a method. */ public interface LiveLocals { /** * Returns the list of Locals that are live before the specified Unit. * * @param s * the Unit that defines this query. * @return a list of Locals that are live before the specified unit in the method. */ public List<Local> getLiveLocalsBefore(Unit s); /** * Returns the list of Locals that are live after the specified Unit. * * @param s * the Unit that defines this query. * @return a list of Locals that are live after the specified unit in the method. */ public List<Local> getLiveLocalsAfter(Unit s); /** * */ public static final class Factory { private Factory() { } public static LiveLocals newLiveLocals(DirectedBodyGraph<Unit> graph) { return new SimpleLiveLocals(graph); } } }
1,894
27.712121
116
java
soot
soot-master/src/main/java/soot/toolkits/scalar/LocalDefs.java
package soot.toolkits.scalar; /*- * #%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; import soot.Local; import soot.Unit; /** * Provides an interface for querying for the definitions of a Local at a given Unit in a method. */ public interface LocalDefs { /** * Returns the definition sites for a Local at a certain point (Unit) in a method. * * You can assume this method never returns {@code null}. * * @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 list of Units where the local is defined in the current method context. If there are no uses an empty list * will returned. */ public List<Unit> getDefsOfAt(Local l, Unit s); /** * Returns the definition sites for a Local merged over all points in a method. * * You can assume this method never returns {@code null}. * * @param l * the Local in question. * @return a list of Units where the local is defined in the current method context. If there are no uses an empty list * will returned. */ public List<Unit> getDefsOf(Local l); }
1,985
31.557377
121
java
soot
soot-master/src/main/java/soot/toolkits/scalar/LocalDefsFactory.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Body; import soot.Singletons; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.SimpleLocalDefs.FlowAnalysisMode; /** * The default implementation of local defs. */ public class LocalDefsFactory { /** * Singleton constructor. * * @param global * the singletons container. Must not be {@code null} * @throws NullPointerException * when {@code global} argument is {@code null} */ public LocalDefsFactory(Singletons.Global global) { if (global == null) { throw new NullPointerException("Cannot instantiate LocalDefsFactory with null Singletons.Global"); } } /** * Creates a new LocalDefs analysis based on a {@code ExceptionalUnitGraph} * * @see soot.toolkits.graph.ExceptionalUnitGraphFactory#createExceptionalUnitGraph(Body) * @see soot.validation.UsesValidator * @param body * @return a new LocalDefs instance */ public LocalDefs newLocalDefs(Body body) { return newLocalDefs(body, false); } /** * Creates a new LocalDefs analysis based on a {@code ExceptionalUnitGraph} If you don't trust the input you should set * {@code expectUndefined} to {@code true}. * * @see soot.toolkits.graph.ExceptionalUnitGraphFactory#createExceptionalUnitGraph(Body) * @param body * @param expectUndefined * if you expect uses of locals that are undefined * @return a new LocalDefs instance */ public LocalDefs newLocalDefs(Body body, boolean expectUndefined) { return newLocalDefs(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body), expectUndefined); } /** * Creates a new LocalDefs analysis based on a given {@code UnitGraph} * * @see soot.toolkits.graph.UnitGraph#UnitGraph(Body) * @param graph * the graph to work with * @return a new LocalDefs instance */ public LocalDefs newLocalDefs(UnitGraph graph) { return newLocalDefs(graph, false); } /** * Creates a new LocalDefs analysis based on a given {@code UnitGraph}. If you don't trust the input you should set * {@code expectUndefined} to {@code true}. * * @see soot.toolkits.graph.UnitGraph#UnitGraph(Body) * @see soot.validation.UsesValidator * @param graph * the graph to work with * @param expectUndefined * if you expect uses of locals that are undefined * @return a new LocalDefs instance */ public LocalDefs newLocalDefs(UnitGraph graph, boolean expectUndefined) { // return new SmartLocalDefs(graph, LiveLocals.Factory.newLiveLocals(graph)); return new SimpleLocalDefs(graph, expectUndefined ? FlowAnalysisMode.OmitSSA : FlowAnalysisMode.Automatic); } /** * Creates a new LocalDefs analysis based on a given {@code UnitGraph}. This analysis will be flow-insensitive, i.e., for a * given local, it will always give all statements that ever write to that local regardless of potential redefinitions in * between. * * @see soot.toolkits.graph.UnitGraph#UnitGraph(Body) * @see soot.validation.UsesValidator * @param graph * the graph to work with * @return a new LocalDefs instance */ public LocalDefs newLocalDefsFlowInsensitive(UnitGraph graph) { // return new SmartLocalDefs(graph, LiveLocals.Factory.newLiveLocals(graph)); return new SimpleLocalDefs(graph, FlowAnalysisMode.FlowInsensitive); } }
4,277
34.355372
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/LocalPacker.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.IdentityUnit; import soot.Local; import soot.PhaseOptions; import soot.Singletons; import soot.Type; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.GroupIntPair; import soot.options.Options; import soot.util.Chain; import soot.util.DeterministicHashMap; /** * A BodyTransformer that attempts to minimize the number of local variables used in Body by 'reusing' them when possible. * Implemented as a singleton. For example the code: {@code for(int i; i < k; i++); for(int j; j < k; j++);} would be * transformed into: {@code for(int i; i < k; i++); for(int i; i < k; i++);} assuming no further conflicting uses of * {@code i} and {@code j}. * * Note: LocalSplitter corresponds to the inverse transformation. * * @see BodyTransformer * @see Body * @see LocalSplitter */ public class LocalPacker extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(LocalPacker.class); public LocalPacker(Singletons.Global g) { } public static LocalPacker v() { return G.v().soot_toolkits_scalar_LocalPacker(); } @Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { if (Options.v().verbose()) { logger.debug("[" + body.getMethod().getName() + "] Packing locals..."); } final Chain<Local> bodyLocalsRef = body.getLocals(); final int origLocalCount = bodyLocalsRef.size(); if (origLocalCount < 1) { return; } // A group represents a bunch of locals which may potentially interfere with each other. // Separate groups can not possibly interfere with each other (coloring say ints and doubles). Map<Local, Type> localToGroup = new DeterministicHashMap<Local, Type>(origLocalCount * 2 + 1, 0.7f); Map<Type, Integer> groupToColorCount = new HashMap<Type, Integer>(origLocalCount * 2 + 1, 0.7f); Map<Local, Integer> localToColor = new HashMap<Local, Integer>(origLocalCount * 2 + 1, 0.7f); // Assign each local to a group, and set that group's color count to 0. for (Local l : bodyLocalsRef) { Type g = l.getType(); localToGroup.put(l, g); groupToColorCount.putIfAbsent(g, 0); } // Assign colors to the parameter locals. for (Unit s : body.getUnits()) { if (s instanceof IdentityUnit) { Value leftOp = ((IdentityUnit) s).getLeftOp(); if (leftOp instanceof Local) { Local l = (Local) leftOp; Type group = localToGroup.get(l); Integer count = groupToColorCount.get(group); localToColor.put(l, count); groupToColorCount.put(group, count + 1); } } } // Call the graph colorer. if (PhaseOptions.getBoolean(options, "unsplit-original-locals")) { FastColorer.unsplitAssignColorsToLocals(body, localToGroup, localToColor, groupToColorCount); } else { FastColorer.assignColorsToLocals(body, localToGroup, localToColor, groupToColorCount); } // Map each local to a new local. Map<Local, Local> localToNewLocal = new HashMap<Local, Local>(origLocalCount * 2 + 1, 0.7f); { Map<GroupIntPair, Local> groupIntToLocal = new HashMap<GroupIntPair, Local>(origLocalCount * 2 + 1, 0.7f); List<Local> originalLocals = new ArrayList<Local>(bodyLocalsRef); bodyLocalsRef.clear(); final Set<String> usedLocalNames = new HashSet<>(); for (Local original : originalLocals) { Type group = localToGroup.get(original); GroupIntPair pair = new GroupIntPair(group, localToColor.get(original)); Local newLocal = groupIntToLocal.get(pair); if (newLocal == null) { newLocal = (Local) original.clone(); newLocal.setType(group); // Added 'usedLocalNames' for distinct naming. // Icky fix. But I guess it works. -PL // It is no substitute for really understanding the // problem, though. I'll leave that to someone // who really understands the local naming stuff. // Does such a person exist? // // I'll just leave this comment as folklore for future // generations. The problem with it is that you can end up // with different locals that share the same name which can // lead to all sorts of funny results. (SA, 2017-03-02) // // If we have a split local, let's find a better name for it String name = newLocal.getName(); if (name != null) { int signIndex = name.indexOf('#'); if (signIndex >= 0) { String newName = name.substring(0, signIndex); if (usedLocalNames.add(newName)) { newLocal.setName(newName); } else { // just leave it alone for now } } else { usedLocalNames.add(name); } } groupIntToLocal.put(pair, newLocal); bodyLocalsRef.add(newLocal); } localToNewLocal.put(original, newLocal); } } // Go through all valueBoxes of this method and perform changes for (Unit s : body.getUnits()) { for (ValueBox box : s.getUseBoxes()) { Value val = box.getValue(); if (val instanceof Local) { box.setValue(localToNewLocal.get((Local) val)); } } for (ValueBox box : s.getDefBoxes()) { Value val = box.getValue(); if (val instanceof Local) { box.setValue(localToNewLocal.get((Local) val)); } } } } }
6,687
34.015707
122
java
soot
soot-master/src/main/java/soot/toolkits/scalar/LocalSplitter.java
package soot.toolkits.scalar; /*- * #%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.ArrayDeque; import java.util.BitSet; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.Local; import soot.Scene; import soot.Singletons; import soot.Timers; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.toolkits.exceptions.ThrowAnalysis; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.util.LocalBitSetPacker; /** * A BodyTransformer that attempts to identify and separate uses of a local variable that are independent of each other. * Conceptually the inverse transform with respect to the LocalPacker transform. For example the code: * {@code for(int i; i < k; i++); for(int i; i < k; i++);} would be transformed into: * {@code for(int i; i < k; i++); for(int j; j < k; j++);} * * @see BodyTransformer * @see LocalPacker * @see Body */ public class LocalSplitter extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(LocalSplitter.class); protected ThrowAnalysis throwAnalysis; protected boolean omitExceptingUnitEdges; public LocalSplitter(Singletons.Global g) { } public LocalSplitter(ThrowAnalysis ta) { this(ta, false); } public LocalSplitter(ThrowAnalysis ta, boolean omitExceptingUnitEdges) { this.throwAnalysis = ta; this.omitExceptingUnitEdges = omitExceptingUnitEdges; } public static LocalSplitter v() { return G.v().soot_toolkits_scalar_LocalSplitter(); } @Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { if (Options.v().verbose()) { logger.debug("[" + body.getMethod().getName() + "] Splitting locals..."); } if (Options.v().time()) { Timers.v().splitTimer.start(); Timers.v().splitPhase1Timer.start(); } if (throwAnalysis == null) { throwAnalysis = Scene.v().getDefaultThrowAnalysis(); } if (!omitExceptingUnitEdges) { omitExceptingUnitEdges = Options.v().omit_excepting_unit_edges(); } // Pack the locals for efficiency final LocalBitSetPacker localPacker = new LocalBitSetPacker(body); localPacker.pack(); // Go through the definitions, building the webs ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis, omitExceptingUnitEdges); // run in panic mode on first split (maybe change this depending on the input source) final LocalDefs defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(graph, true); final LocalUses uses = LocalUses.Factory.newLocalUses(graph, defs); if (Options.v().time()) { Timers.v().splitPhase1Timer.end(); Timers.v().splitPhase2Timer.start(); } // Collect the set of locals that we need to split final BitSet localsToSplit; { int localCount = localPacker.getLocalCount(); BitSet localsVisited = new BitSet(localCount); localsToSplit = new BitSet(localCount); for (Unit s : body.getUnits()) { Iterator<ValueBox> defsInUnitItr = s.getDefBoxes().iterator(); if (defsInUnitItr.hasNext()) { Value value = defsInUnitItr.next().getValue(); if (value instanceof Local) { // If we see a local the second time, we know that we must split it int localNumber = ((Local) value).getNumber(); if (localsVisited.get(localNumber)) { localsToSplit.set(localNumber); } else { localsVisited.set(localNumber); } } } } } { int w = 0; Set<Unit> visited = new HashSet<Unit>(); for (Unit s : body.getUnits()) { Iterator<ValueBox> defsInUnitItr = s.getDefBoxes().iterator(); if (!defsInUnitItr.hasNext()) { continue; } Value singleDef = defsInUnitItr.next().getValue(); if (defsInUnitItr.hasNext()) { throw new RuntimeException("stmt with more than 1 defbox!"); } if (!(singleDef instanceof Local)) { continue; } // we don't want to visit a node twice if (visited.remove(s)) { continue; } // always reassign locals to avoid "use before definition" bugs! // unfortunately this creates a lot of new locals, so it's important // to remove them afterwards Local oldLocal = (Local) singleDef; if (!localsToSplit.get(oldLocal.getNumber())) { continue; } Local newLocal = (Local) oldLocal.clone(); String name = newLocal.getName(); if (name != null) { newLocal.setName(name + '#' + (++w)); // renaming should not be done here } body.getLocals().add(newLocal); Deque<Unit> queue = new ArrayDeque<Unit>(); queue.addFirst(s); do { final Unit head = queue.removeFirst(); if (visited.add(head)) { for (UnitValueBoxPair use : uses.getUsesOf(head)) { ValueBox vb = use.valueBox; Value v = vb.getValue(); if (v == newLocal) { continue; } // should always be true - but who knows ... if (v instanceof Local) { queue.addAll(defs.getDefsOfAt((Local) v, use.unit)); vb.setValue(newLocal); } } for (ValueBox vb : head.getDefBoxes()) { Value v = vb.getValue(); if (v instanceof Local) { vb.setValue(newLocal); } } } } while (!queue.isEmpty()); // keep the set small visited.remove(s); } } // Restore the original local numbering localPacker.unpack(); if (Options.v().time()) { Timers.v().splitPhase2Timer.end(); Timers.v().splitTimer.end(); } } }
6,989
30.772727
120
java
soot
soot-master/src/main/java/soot/toolkits/scalar/LocalUnitPair.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Local; import soot.Unit; /** * Utility class used to package a Local and a Unit together. */ public class LocalUnitPair { Local local; Unit unit; /** * Constructs a LocalUnitPair from a Unit object and a Local object. * * @param local * some Local * @param unit * some Unit. */ public LocalUnitPair(Local local, Unit unit) { this.local = local; this.unit = unit; } /** * Two LocalUnitPairs are equal iff they hold the same Unit objects and the same Local objects within them. * * @param other * another LocalUnitPair * @return true if other contains the same objects as this. */ @Override public boolean equals(Object other) { if (other instanceof LocalUnitPair) { LocalUnitPair temp = (LocalUnitPair) other; return temp.local == this.local && temp.unit == this.unit; } else { return false; } } @Override public int hashCode() { return local.hashCode() * 101 + unit.hashCode() + 17; } public Local getLocal() { return local; } public Unit getUnit() { return unit; } }
1,975
24.012658
109
java
soot
soot-master/src/main/java/soot/toolkits/scalar/LocalUses.java
package soot.toolkits.scalar; /*- * #%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; import soot.Body; import soot.G; import soot.Unit; import soot.toolkits.graph.UnitGraph; /** * Provides an interface to find the Units that use a Local defined at a given Unit. */ public interface LocalUses { /** * Returns a list of the Units that use the Local that is defined by a given Unit. * * @param s * the unit we wish to query for the use of the Local it defines. * @return a list of the uses Local's uses. */ public List<UnitValueBoxPair> getUsesOf(Unit s); /** * */ public static final class Factory { private Factory() { } public static LocalUses newLocalUses(Body body, LocalDefs localDefs) { return new SimpleLocalUses(body, localDefs); } public static LocalUses newLocalUses(UnitGraph graph, LocalDefs localDefs) { return newLocalUses(graph.getBody(), localDefs); } public static LocalUses newLocalUses(Body body) { return newLocalUses(body, G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(body)); } public static LocalUses newLocalUses(UnitGraph graph) { return newLocalUses(graph.getBody(), G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(graph)); } } }
2,073
28.628571
110
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ObjectIntMapper.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Florian Loitsch * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; /** * Gives an injection of Objects to ints. Different instances may map different ints to the same object. */ public class ObjectIntMapper<E> { private final Vector<E> intToObjects; private final Map<E, Integer> objectToInts; private int counter; public ObjectIntMapper() { this.intToObjects = new Vector<E>(); this.objectToInts = new HashMap<E, Integer>(); this.counter = 0; } public ObjectIntMapper(FlowUniverse<E> flowUniverse) { this(flowUniverse.iterator(), flowUniverse.size()); } public ObjectIntMapper(Collection<E> collection) { this(collection.iterator(), collection.size()); } private ObjectIntMapper(Iterator<E> it, int initSize) { this.intToObjects = new Vector<E>(initSize); this.objectToInts = new HashMap<E, Integer>(initSize); this.counter = 0; while (it.hasNext()) { add(it.next()); } } /** * adds <code>o</code> into the map. no test are made, if it is already in the map. */ public int add(E o) { objectToInts.put(o, counter); intToObjects.add(o); return counter++; } /** * returns the mapping of <code>o</code>. if there has been a call to <code>objectToInt</code> with the same <code>o</code> * before, the same value will be returned. * * @param o * @return <code>o</code>'s mapping */ public int getInt(E o) { Integer i = objectToInts.get(o); return (i != null) ? i : add(o); } /** * returns the object associated to <code>i</code>. * * @param i * @return <code>i</code>'s object */ public E getObject(int i) { return intToObjects.get(i); } /** * returns true, if <code>o</code> has already been mapped. * * @param o * @return true if <code>o</code> has already a number. */ public boolean contains(Object o) { return objectToInts.containsKey(o); } /** * returns the number of mapped objects. */ public int size() { return counter; } }
2,924
25.351351
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/Pair.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * Copyright (C) 2007 Manu Sridharan * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.PointsToAnalysis; import soot.SootMethod; /** * Just a pair of arbitrary objects. * * @author Ondrej Lhotak * @author Manu Sridharan (genericized it) * @author xiao, extend it with more functions */ public class Pair<T, U> { protected T o1; protected U o2; public Pair() { this.o1 = null; this.o2 = null; } public Pair(T o1, U o2) { this.o1 = o1; this.o2 = o2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((o1 == null) ? 0 : o1.hashCode()); result = prime * result + ((o2 == null) ? 0 : o2.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } Pair<?, ?> other = (Pair<?, ?>) obj; if (this.o1 == null) { if (other.o1 != null) { return false; } } else if (!this.o1.equals(other.o1)) { return false; } if (this.o2 == null) { if (other.o2 != null) { return false; } } else if (!this.o2.equals(other.o2)) { return false; } return true; } @Override public String toString() { return "Pair " + o1 + "," + o2; } /** * Decide if this pair represents a method parameter. */ public boolean isParameter() { return o1 instanceof SootMethod && o2 instanceof Integer; } /** * Decide if this pair stores the THIS parameter for a method. */ public boolean isThisParameter() { return o1 instanceof SootMethod && PointsToAnalysis.THIS_NODE.equals(o2); } public T getO1() { return o1; } public U getO2() { return o2; } public void setO1(T no1) { o1 = no1; } public void setO2(U no2) { o2 = no2; } public void setPair(T no1, U no2) { o1 = no1; o2 = no2; } }
2,778
21.232
77
java
soot
soot-master/src/main/java/soot/toolkits/scalar/SharedInitializationLocalSplitter.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Phong Co * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.Local; import soot.Scene; import soot.Singletons; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.dexpler.DexNullArrayRefTransformer; import soot.dexpler.DexNullThrowTransformer; import soot.jimple.AssignStmt; import soot.jimple.Constant; import soot.jimple.Jimple; import soot.jimple.toolkits.scalar.ConstantPropagatorAndFolder; import soot.jimple.toolkits.scalar.CopyPropagator; import soot.jimple.toolkits.scalar.DeadAssignmentEliminator; import soot.options.Options; import soot.toolkits.exceptions.ThrowAnalysis; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.util.Chain; import soot.util.HashMultiMap; import soot.util.MultiMap; //@formatter:off /** * There is a problem with the following code <code> * $u2#6 = 0; * interfaceinvoke $u5#30.<Foo: void setMomentary(android.view.View,boolean)>($u4, $u2#6); * interfaceinvoke $u5#56.<Foo: void setSelectedIndex(android.view.View,int)>($u4, $u2#6); * </code> * * since $u2#6 will be boolean as well as int. A cast from boolean to int or vice versa is not valid in Java. The local * splitter does not split the local since it would require the introduction of a new initialization statement. Therefore, we * split for each usage of a constant variable, such as: <code> * $u2#6 = 0; * $u2#6_2 = 0; * interfaceinvoke $u5#30.<Foo: void setMomentary(android.view.View,boolean)>($u4, $u2#6); * interfaceinvoke $u5#56.<Foo: void setSelectedIndex(android.view.View,int)>($u4, $u2#6_2); * </code> * * @author Marc Miltenberger */ // @formatter:on public class SharedInitializationLocalSplitter extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(SharedInitializationLocalSplitter.class); protected ThrowAnalysis throwAnalysis; protected boolean omitExceptingUnitEdges; public SharedInitializationLocalSplitter(Singletons.Global g) { } public SharedInitializationLocalSplitter(ThrowAnalysis ta) { this(ta, false); } public SharedInitializationLocalSplitter(ThrowAnalysis ta, boolean omitExceptingUnitEdges) { this.throwAnalysis = ta; this.omitExceptingUnitEdges = omitExceptingUnitEdges; } public static SharedInitializationLocalSplitter v() { return G.v().soot_toolkits_scalar_SharedInitializationLocalSplitter(); } private static final class Cluster { protected final List<Unit> constantInitializers; protected final Unit use; public Cluster(Unit use, List<Unit> constantInitializers) { this.use = use; this.constantInitializers = constantInitializers; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Constant intializers:\n"); for (Unit r : constantInitializers) { sb.append("\n - ").append(toStringUnit(r)); } return sb.toString(); } private String toStringUnit(Unit u) { return u + " (" + System.identityHashCode(u) + ")"; } } @Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { if (Options.v().verbose()) { logger.debug("[" + body.getMethod().getName() + "] Splitting for shared initialization of locals..."); } if (throwAnalysis == null) { throwAnalysis = Scene.v().getDefaultThrowAnalysis(); } if (omitExceptingUnitEdges == false) { omitExceptingUnitEdges = Options.v().omit_excepting_unit_edges(); } CopyPropagator.v().transform(body); ConstantPropagatorAndFolder.v().transform(body); DexNullThrowTransformer.v().transform(body); DexNullArrayRefTransformer.v().transform(body); FlowSensitiveConstantPropagator.v().transform(body); CopyPropagator.v().transform(body); DexNullThrowTransformer.v().transform(body); DexNullArrayRefTransformer.v().transform(body); DeadAssignmentEliminator.v().transform(body); CopyPropagator.v().transform(body); final ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis, omitExceptingUnitEdges); final LocalDefs defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(graph, true); final MultiMap<Local, Cluster> clustersPerLocal = new HashMultiMap<Local, Cluster>(); final Chain<Unit> units = body.getUnits(); for (Unit s : units) { for (ValueBox useBox : s.getUseBoxes()) { Value v = useBox.getValue(); if (v instanceof Local) { Local luse = (Local) v; List<Unit> allAffectingDefs = defs.getDefsOfAt(luse, s); if (allAffectingDefs.isEmpty()) { continue; } // Make sure we are only affected by Constant definitions via AssignStmt if (!allAffectingDefs.stream() .allMatch(u -> (u instanceof AssignStmt) && (((AssignStmt) u).getRightOp() instanceof Constant))) { continue; } clustersPerLocal.put(luse, new Cluster(s, allAffectingDefs)); } } } final Chain<Local> locals = body.getLocals(); int w = 0; for (Local lcl : clustersPerLocal.keySet()) { Set<Cluster> clusters = clustersPerLocal.get(lcl); if (clusters.size() <= 1) { // Not interesting continue; } for (Cluster cluster : clusters) { // we have an overlap, we need to split. Local newLocal = (Local) lcl.clone(); newLocal.setName(newLocal.getName() + '_' + ++w); locals.add(newLocal); for (Unit u : cluster.constantInitializers) { AssignStmt assign = (AssignStmt) u; AssignStmt newAssign = Jimple.v().newAssignStmt(newLocal, assign.getRightOp()); units.insertAfter(newAssign, assign); CopyPropagator.copyLineTags(newAssign.getUseBoxes().get(0), assign); } replaceLocalsInUnitUses(cluster.use, lcl, newLocal); } } } private void replaceLocalsInUnitUses(Unit change, Value oldLocal, Local newLocal) { for (ValueBox u : change.getUseBoxes()) { if (u.getValue() == oldLocal) { u.setValue(newLocal); } } } }
7,188
33.07109
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/SimpleLiveLocals.java
package soot.toolkits.scalar; /*- * #%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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Local; import soot.Timers; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.toolkits.graph.DirectedBodyGraph; import soot.toolkits.graph.ExceptionalUnitGraph; /** * Analysis that provides an implementation of the LiveLocals interface. */ public class SimpleLiveLocals implements LiveLocals { private static final Logger logger = LoggerFactory.getLogger(SimpleLiveLocals.class); private final FlowAnalysis<Unit, FlowSet<Local>> analysis; /** * Computes the analysis given a DirectedBodyGraph<Unit> computed from a method body. It is recommended that a * ExceptionalUnitGraph (or similar) be provided for correct results in the case of exceptional control flow. * * @param graph * a graph on which to compute the analysis. * * @see ExceptionalUnitGraph */ public SimpleLiveLocals(DirectedBodyGraph<Unit> graph) { if (Options.v().verbose()) { logger.debug("[" + graph.getBody().getMethod().getName() + "] Constructing SimpleLiveLocals..."); } if (Options.v().time()) { Timers.v().liveTimer.start(); } this.analysis = new Analysis(graph); if (Options.v().time()) { Timers.v().liveAnalysisTimer.start(); } this.analysis.doAnalysis(); if (Options.v().time()) { Timers.v().liveAnalysisTimer.end(); Timers.v().liveTimer.end(); } } @Override public List<Local> getLiveLocalsAfter(Unit s) { // ArraySparseSet returns a unbacked list of elements! return analysis.getFlowAfter(s).toList(); } @Override public List<Local> getLiveLocalsBefore(Unit s) { // ArraySparseSet returns a unbacked list of elements! return analysis.getFlowBefore(s).toList(); } private static class Analysis extends BackwardFlowAnalysis<Unit, FlowSet<Local>> { Analysis(DirectedBodyGraph<Unit> g) { super(g); } @Override protected FlowSet<Local> newInitialFlow() { return new ArraySparseSet<Local>(); } @Override protected void flowThrough(FlowSet<Local> in, Unit unit, FlowSet<Local> out) { in.copy(out); // Perform kill for (ValueBox box : unit.getDefBoxes()) { Value v = box.getValue(); if (v instanceof Local) { out.remove((Local) v); } } // Perform generation for (ValueBox box : unit.getUseBoxes()) { Value v = box.getValue(); if (v instanceof Local) { out.add((Local) v); } } } @Override protected void mergeInto(Unit succNode, FlowSet<Local> inout, FlowSet<Local> in) { inout.union(in); } @Override protected void merge(FlowSet<Local> in1, FlowSet<Local> in2, FlowSet<Local> out) { in1.union(in2, out); } @Override protected void copy(FlowSet<Local> source, FlowSet<Local> dest) { source.copy(dest); } } }
3,834
26.992701
112
java
soot
soot-master/src/main/java/soot/toolkits/scalar/SimpleLocalDefs.java
package soot.toolkits.scalar; /*- * #%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.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import soot.IdentityUnit; import soot.Local; import soot.Timers; import soot.Trap; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.ExceptionalGraph; import soot.toolkits.graph.ExceptionalGraph.ExceptionDest; import soot.toolkits.graph.UnitGraph; /** * Analysis that provides an implementation of the LocalDefs interface. */ public class SimpleLocalDefs implements LocalDefs { private static class StaticSingleAssignment implements LocalDefs { final Map<Local, List<Unit>> result; StaticSingleAssignment(Local[] locals, List<Unit>[] unitList) { final int N = locals.length; assert (N == unitList.length); this.result = new HashMap<Local, List<Unit>>((N * 3) / 2 + 7); for (int i = 0; i < N; i++) { List<Unit> curr = unitList[i]; if (!curr.isEmpty()) { assert (curr.size() == 1); result.put(locals[i], curr); } } } @Override public List<Unit> getDefsOfAt(Local l, Unit s) { List<Unit> lst = result.get(l); // singleton-lists are immutable return lst != null ? lst : Collections.emptyList(); } @Override public List<Unit> getDefsOf(Local l) { return getDefsOfAt(l, null); } } // end inner class StaticSingleAssignment private class FlowAssignment extends ForwardFlowAnalysis<Unit, FlowAssignment.FlowBitSet> implements LocalDefs { class FlowBitSet extends BitSet { private static final long serialVersionUID = -8348696077189400377L; FlowBitSet() { super(universe.length); } List<Unit> asList(int fromIndex, int toIndex) { if (fromIndex < 0 || toIndex < fromIndex || universe.length < toIndex) { throw new IndexOutOfBoundsException(); } if (fromIndex == toIndex) { return Collections.emptyList(); } if (fromIndex == toIndex - 1) { if (this.get(fromIndex)) { return Collections.singletonList(universe[fromIndex]); } else { return Collections.emptyList(); } } int i = this.nextSetBit(fromIndex); if (i < 0 || i >= toIndex) { return Collections.emptyList(); } if (i == toIndex - 1) { return Collections.singletonList(universe[i]); } List<Unit> elements = new ArrayList<Unit>(toIndex - i); for (;;) { int endOfRun = Math.min(toIndex, this.nextClearBit(i + 1)); do { elements.add(universe[i++]); } while (i < endOfRun); if (i >= toIndex) { break; } i = this.nextSetBit(i + 1); if (i < 0 || i >= toIndex) { break; } } return elements; } } final Map<Local, Integer> locals; final List<Unit>[] unitList; final int[] localRange; final Unit[] universe; private Map<Unit, Integer> indexOfUnit; FlowAssignment(DirectedGraph<Unit> graph, Local[] locals, List<Unit>[] unitList, int units, boolean omitSSA) { super(graph); this.unitList = unitList; this.universe = new Unit[units]; this.indexOfUnit = new HashMap<Unit, Integer>(units); final int N = locals.length; this.locals = new HashMap<Local, Integer>((N * 3) / 2 + 7); this.localRange = new int[N + 1]; for (int j = 0, i = 0; i < N; this.localRange[++i] = j) { List<Unit> currUnitList = unitList[i]; if (currUnitList.isEmpty()) { continue; } localRange[i + 1] = j; this.locals.put(locals[i], i); if (currUnitList.size() >= 2) { for (Unit u : currUnitList) { this.indexOfUnit.put(u, j); this.universe[j++] = u; } } else if (omitSSA) { this.universe[j++] = currUnitList.get(0); } } assert (localRange[N] == units); doAnalysis(); this.indexOfUnit = null;// release memory } @Override protected boolean omissible(Unit u) { final List<ValueBox> defs = u.getDefBoxes(); if (!defs.isEmpty()) { // avoid temporary creation of iterators (more like micro-tuning) for (ValueBox vb : defs) { Value v = vb.getValue(); if (v instanceof Local) { Local l = (Local) v; int lno = getLocalNumber(l); return (localRange[lno] == localRange[lno + 1]); } } } return true; } @Override protected Flow getFlow(Unit from, Unit to) { // QND if (to instanceof IdentityUnit && graph instanceof ExceptionalGraph) { ExceptionalGraph<Unit> g = (ExceptionalGraph<Unit>) graph; if (!g.getExceptionalPredsOf(to).isEmpty()) { // look if there is a real exception edge for (ExceptionDest<Unit> exd : g.getExceptionDests(from)) { Trap trap = exd.getTrap(); if (trap != null && trap.getHandlerUnit() == to) { return Flow.IN; } } } } return Flow.OUT; } @Override protected void flowThrough(FlowBitSet in, Unit unit, FlowBitSet out) { copy(in, out); // reassign all definitions for (ValueBox vb : unit.getDefBoxes()) { Value v = vb.getValue(); if (v instanceof Local) { Local l = (Local) v; int lno = getLocalNumber(l); int from = localRange[lno]; int to = localRange[1 + lno]; if (from == to) { continue; } assert (from <= to); if (to - from == 1) { // special case: this local has only one def point out.set(from); } else { out.clear(from, to); out.set(indexOfUnit.get(unit)); } } } } @Override protected void copy(FlowBitSet source, FlowBitSet dest) { if (dest != source) { dest.clear(); dest.or(source); } } protected FlowBitSet newInitialFlow() { return new FlowBitSet(); } @Override protected void mergeInto(Unit succNode, FlowBitSet inout, FlowBitSet in) { inout.or(in); } @Override protected void merge(FlowBitSet in1, FlowBitSet in2, FlowBitSet out) { throw new UnsupportedOperationException("should never be called"); } @Override public List<Unit> getDefsOfAt(Local l, Unit s) { Integer lno = locals.get(l); if (lno == null) { return Collections.emptyList(); } int from = localRange[lno]; int to = localRange[lno + 1]; assert (from <= to); if (from == to) { assert (unitList[lno].size() == 1); // both singletonList is immutable return unitList[lno]; } else { return getFlowBefore(s).asList(from, to); } } @Override public List<Unit> getDefsOf(Local l) { List<Unit> defs = new ArrayList<Unit>(); for (Unit u : graph) { List<Unit> defsOf = getDefsOfAt(l, u); if (defsOf != null) { defs.addAll(defsOf); } } return defs; } } // end inner class FlowAssignment /** * The different modes in which the flow analysis can run */ public enum FlowAnalysisMode { /** * Automatically detect the mode to use */ Automatic, /** * Never use the SSA form, even if the unit graph would allow for a flow-insensitive analysis without losing precision */ OmitSSA, /** * Always conduct a flow-insensitive analysis */ FlowInsensitive } private final LocalDefs def; /** * * @param graph */ public SimpleLocalDefs(UnitGraph graph) { this(graph, FlowAnalysisMode.Automatic); } public SimpleLocalDefs(UnitGraph graph, FlowAnalysisMode mode) { this(graph, graph.getBody().getLocals(), mode); } SimpleLocalDefs(DirectedGraph<Unit> graph, Collection<Local> locals, FlowAnalysisMode mode) { this(graph, locals.toArray(new Local[locals.size()]), mode); } SimpleLocalDefs(DirectedGraph<Unit> graph, Local[] locals, boolean omitSSA) { this(graph, locals, omitSSA ? FlowAnalysisMode.OmitSSA : FlowAnalysisMode.Automatic); } SimpleLocalDefs(DirectedGraph<Unit> graph, Local[] locals, FlowAnalysisMode mode) { final boolean time = Options.v().time(); if (time) { Timers.v().defsTimer.start(); } // reassign local numbers int[] oldNumbers = assignNumbers(locals); this.def = init(graph, locals, mode); // restore local numbering restoreNumbers(locals, oldNumbers); if (time) { Timers.v().defsTimer.end(); } } protected void restoreNumbers(Local[] locals, int[] oldNumbers) { for (int i = 0; i < oldNumbers.length; i++) { locals[i].setNumber(oldNumbers[i]); } } protected int[] assignNumbers(Local[] locals) { final int N = locals.length; int[] oldNumbers = new int[N]; for (int i = 0; i < N; i++) { oldNumbers[i] = locals[i].getNumber(); locals[i].setNumber(i); } return oldNumbers; } private LocalDefs init(DirectedGraph<Unit> graph, Local[] locals, FlowAnalysisMode mode) { @SuppressWarnings("unchecked") List<Unit>[] unitList = new List[locals.length]; Arrays.fill(unitList, Collections.emptyList()); final boolean omitSSA = (mode == FlowAnalysisMode.OmitSSA); boolean doFlowAnalsis = omitSSA; int units = 0; // collect all def points for (Unit unit : graph) { for (ValueBox box : unit.getDefBoxes()) { Value v = box.getValue(); if (v instanceof Local) { Local l = (Local) v; int lno = getLocalNumber(l); switch (unitList[lno].size()) { case 0: unitList[lno] = Collections.singletonList(unit); if (omitSSA) { units++; } break; case 1: if (!omitSSA) { units++; } unitList[lno] = new ArrayList<Unit>(unitList[lno]); doFlowAnalsis = true; // fallthrough default: unitList[lno].add(unit); units++; break; } } } } if (doFlowAnalsis && mode != FlowAnalysisMode.FlowInsensitive) { return new FlowAssignment(graph, locals, unitList, units, omitSSA); } else { return new StaticSingleAssignment(locals, unitList); } } // Is protected so that in case we have a smarter implementation we can use it. protected int getLocalNumber(Local l) { return l.getNumber(); } @Override public List<Unit> getDefsOfAt(Local l, Unit s) { return def.getDefsOfAt(l, s); } @Override public List<Unit> getDefsOf(Local l) { return def.getDefsOf(l); } }
12,035
26.925754
122
java
soot
soot-master/src/main/java/soot/toolkits/scalar/SimpleLocalUses.java
package soot.toolkits.scalar; /*- * #%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.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.Local; import soot.Timers; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.toolkits.graph.UnitGraph; /** * Analysis that implements the LocalUses interface. Uses for a Local defined at a given Unit are returned as a list of * UnitValueBoxPairs each containing a Unit that use the local and the Local itself wrapped in a ValueBox. */ public class SimpleLocalUses implements LocalUses { private static final Logger logger = LoggerFactory.getLogger(SimpleLocalUses.class); final Body body; private final Map<Unit, List<UnitValueBoxPair>> unitToUses; /** * Construct the analysis from a UnitGraph representation of a method body and a LocalDefs interface. This supposes that a * LocalDefs analysis must have been computed prior. * * <p> * Note: If you do not already have a UnitGraph, it may be cheaper to use the constructor which only requires a Body. */ public SimpleLocalUses(UnitGraph graph, LocalDefs localDefs) { this(graph.getBody(), localDefs); } /** * Construct the analysis from a method body and a LocalDefs interface. This supposes that a LocalDefs analysis must have * been computed prior. */ public SimpleLocalUses(Body body, LocalDefs localDefs) { this.body = body; this.unitToUses = new HashMap<Unit, List<UnitValueBoxPair>>(body.getUnits().size() * 2 + 1, 0.7f); final Options options = Options.v(); if (options.verbose()) { logger.debug("[" + body.getMethod().getName() + "] Constructing SimpleLocalUses..."); } if (options.time()) { Timers.v().usesTimer.start(); } // Traverse units and associate uses with definitions for (Unit unit : body.getUnits()) { for (ValueBox useBox : unit.getUseBoxes()) { Value v = useBox.getValue(); if (v instanceof Local) { // Add this statement to the uses of the definition of the local Local l = (Local) v; List<Unit> defs = localDefs.getDefsOfAt(l, unit); if (defs != null) { UnitValueBoxPair newPair = new UnitValueBoxPair(unit, useBox); for (Unit def : defs) { List<UnitValueBoxPair> lst = unitToUses.get(def); if (lst == null) { unitToUses.put(def, lst = new ArrayList<UnitValueBoxPair>()); } lst.add(newPair); } } } } } if (options.time()) { Timers.v().usesTimer.end(); } if (options.verbose()) { logger.debug("[" + body.getMethod().getName() + "] finished SimpleLocalUses..."); } } /** * Uses for a Local defined at a given Unit are returned as a list of UnitValueBoxPairs each containing a Unit that use the * local and the Local itself wrapped in a ValueBox. * * @param s * a unit that we want to query for the uses of the Local it (may) define. * @return a UnitValueBoxPair of the Units that use the Local. */ @Override public List<UnitValueBoxPair> getUsesOf(Unit s) { List<UnitValueBoxPair> l = unitToUses.get(s); return (l == null) ? Collections.emptyList() : Collections.unmodifiableList(l); } /** * Gets all variables that are used in this body * * @return The list of variables used in this body */ public Set<Local> getUsedVariables() { Set<Local> res = new HashSet<Local>(); for (List<UnitValueBoxPair> vals : unitToUses.values()) { for (UnitValueBoxPair val : vals) { res.add((Local) val.valueBox.getValue()); } } return res; } /** * Gets all variables that are not used in this body * * @return The list of variables declared, but not used in this body */ public Set<Local> getUnusedVariables() { Set<Local> res = new HashSet<Local>(body.getLocals()); res.retainAll(getUsedVariables()); return res; } }
5,003
31.705882
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/SmartLocalDefs.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.BitSet; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Local; import soot.Timers; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraph.ExceptionDest; import soot.toolkits.graph.UnitGraph; import soot.util.Cons; import soot.util.LocalBitSetPacker; /** * Analysis that provides an implementation of the LocalDefs interface. * * This Analysis calculates only the definitions of the locals used by a unit. If you need all definitions of local you * should use {@see SimpleLocalDefs}. * * Be warned: This implementation requires a lot of memory and CPU time, normally {@see SimpleLocalDefs} is much faster. */ public class SmartLocalDefs implements LocalDefs { private static final Logger logger = LoggerFactory.getLogger(SmartLocalDefs.class); private final UnitGraph graph; private Map<Local, Set<Unit>> localToDefs; // for each local, set of units where it's defined private Map<Unit, BitSet> liveLocalsAfter; private final Map<Cons<Unit, Local>, List<Unit>> answer; public SmartLocalDefs(UnitGraph g, LiveLocals live) { this.graph = g; this.localToDefs = new HashMap<Local, Set<Unit>>(2 * g.getBody().getLocalCount() + 1); this.liveLocalsAfter = new HashMap<Unit, BitSet>(2 * g.getBody().getUnits().size() + 1); this.answer = new HashMap<Cons<Unit, Local>, List<Unit>>(); final Options op = Options.v(); if (op.verbose()) { logger.debug("[" + g.getBody().getMethod().getName() + "] Constructing SmartLocalDefs..."); } if (op.time()) { Timers.v().defsTimer.start(); } final LocalBitSetPacker localPacker = new LocalBitSetPacker(g.getBody()); localPacker.pack(); for (Unit u : g) { // translate locals to bits BitSet set = new BitSet(localPacker.getLocalCount()); for (Local l : live.getLiveLocalsAfter(u)) { set.set(l.getNumber()); } liveLocalsAfter.put(u, set); Local l = localDef(u); if (l != null) { addDefOf(l, u); } } if (op.verbose()) { logger.debug("[" + g.getBody().getMethod().getName() + "] done localToDefs map..."); } LocalDefsAnalysis analysis = new LocalDefsAnalysis(g); liveLocalsAfter = null; for (Unit u : g) { Set<Unit> s1 = analysis.getFlowBefore(u); if (s1 == null || s1.isEmpty()) { continue; } for (ValueBox vb : u.getUseBoxes()) { Value v = vb.getValue(); if (v instanceof Local) { Local l = (Local) v; Set<Unit> s2 = defsOf(l); if (s2 == null || s2.isEmpty()) { continue; } List<Unit> lst = intersectionAsList(s1, s2); if (!lst.isEmpty()) { this.answer.putIfAbsent(new Cons<Unit, Local>(u, l), lst); } } } } localToDefs = null; localPacker.unpack(); if (op.time()) { Timers.v().defsTimer.end(); } if (op.verbose()) { logger.debug("[" + g.getBody().getMethod().getName() + "] SmartLocalDefs finished."); } } /** * Intersects 2 sets and returns the result as a list * * @param a * @param b * @return */ private static <T> List<T> intersectionAsList(Set<T> a, Set<T> b) { if (a == null || b == null || a.isEmpty() || b.isEmpty()) { return Collections.<T>emptyList(); } else if (a.size() < b.size()) { List<T> c = new ArrayList<T>(a); c.retainAll(b); return c; } else { List<T> c = new ArrayList<T>(b); c.retainAll(a); return c; } } public void printAnswer() { System.out.println(answer.toString()); } private Local localDef(Unit u) { List<ValueBox> defBoxes = u.getDefBoxes(); switch (defBoxes.size()) { case 0: return null; case 1: Value v = defBoxes.get(0).getValue(); return (v instanceof Local) ? (Local) v : null; default: throw new RuntimeException(); } } private Set<Unit> defsOf(Local l) { Set<Unit> s = localToDefs.get(l); return (s == null) ? Collections.emptySet() : s; } private void addDefOf(Local l, Unit u) { Set<Unit> s = localToDefs.get(l); if (s == null) { localToDefs.put(l, s = new HashSet<Unit>()); } s.add(u); } class LocalDefsAnalysis extends ForwardFlowAnalysisExtended<Unit, Set<Unit>> { LocalDefsAnalysis(UnitGraph g) { super(g); doAnalysis(); } @Override protected void mergeInto(Unit succNode, Set<Unit> inout, Set<Unit> in) { inout.addAll(in); } @Override protected void merge(Set<Unit> in1, Set<Unit> in2, Set<Unit> out) { // mergeInto should be called throw new RuntimeException("should never be called"); } @Override protected void flowThrough(Set<Unit> in, Unit u, Unit succ, Set<Unit> out) { out.clear(); final BitSet liveLocals = liveLocalsAfter.get(u); final Local l = localDef(u); if (l == null) { // add all units contained in mask for (Unit inU : in) { if (liveLocals.get(localDef(inU).getNumber())) { out.add(inU); } } } else { // check unit whether contained in allDefUnits before add // into out set. Set<Unit> allDefUnits = defsOf(l); boolean isExceptionalTarget = false; if (graph instanceof ExceptionalUnitGraph) { for (ExceptionDest ed : ((ExceptionalUnitGraph) graph).getExceptionDests(u)) { if (ed.getTrap() != null && ed.getTrap().getHandlerUnit() == succ) { isExceptionalTarget = true; } } } for (Unit inU : in) { if (liveLocals.get(localDef(inU).getNumber())) { // If we have a = foo and foo can throw an exception, we // must keep the old definition of a. if (isExceptionalTarget || !allDefUnits.contains(inU)) { out.add(inU); } } } assert (isExceptionalTarget || !out.removeAll(allDefUnits)); if (liveLocals.get(l.getNumber())) { if (!isExceptionalTarget) { out.add(u); } } } } @Override protected void copy(Set<Unit> sourceSet, Set<Unit> destSet) { destSet.clear(); destSet.addAll(sourceSet); } @Override protected Set<Unit> newInitialFlow() { return new HashSet<Unit>(); } @Override protected Set<Unit> entryInitialFlow() { return new HashSet<Unit>(); } } @Override public List<Unit> getDefsOfAt(Local l, Unit s) { List<Unit> lst = answer.get(new Cons<Unit, Local>(s, l)); return lst != null ? lst : Collections.emptyList(); } @Override public List<Unit> getDefsOf(Local l) { List<Unit> result = new ArrayList<Unit>(); for (Cons<Unit, Local> cons : answer.keySet()) { if (cons.cdr() == l) { result.addAll(answer.get(cons)); } } return result; } /** * Returns the associated unit graph. */ public UnitGraph getGraph() { return graph; } }
8,251
27.260274
120
java
soot
soot-master/src/main/java/soot/toolkits/scalar/SmartLocalDefsPool.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2015 Eric Bodden and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import com.google.common.collect.Maps; import java.util.Map; import soot.Body; import soot.G; import soot.Singletons; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.graph.UnitGraph; /** * This class implements a pool for {@link SmartLocalDefs} instances. This is useful, as these analyses are expensive to * compute. A {@link SmartLocalDefs} instance requires a {@link UnitGraph} (usually a {@link ExceptionalUnitGraph}), and * creating these repeatedly, and applying the {@link SmartLocalDefs} analysis repeatedly costs time. Therefore in this class * we pool these instances in cases in which the respective body is still the same. * * @author Eric Bodden */ public class SmartLocalDefsPool { protected Map<Body, Pair<Long, SmartLocalDefs>> pool = Maps.newHashMap(); /** * This method returns a fresh instance of a {@link SmartLocalDefs} analysis, based on a freshly created * {@link ExceptionalUnitGraph} for b, with standard parameters. If the body b's modification count has not changed since * the last time such an analysis was requested for b, then the previously created analysis is returned instead. * * @see Body#getModificationCount() */ public SmartLocalDefs getSmartLocalDefsFor(Body b) { Pair<Long, SmartLocalDefs> modCountAndSLD = pool.get(b); if (modCountAndSLD != null && modCountAndSLD.o1.longValue() == b.getModificationCount()) { return modCountAndSLD.o2; } else { ExceptionalUnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b); SmartLocalDefs newSLD = new SmartLocalDefs(g, new SimpleLiveLocals(g)); pool.put(b, new Pair<Long, SmartLocalDefs>(b.getModificationCount(), newSLD)); return newSLD; } } public void clear() { pool.clear(); } public static SmartLocalDefsPool v() { return G.v().soot_toolkits_scalar_SmartLocalDefsPool(); } public SmartLocalDefsPool(Singletons.Global g) { } public void invalidate(Body b) { pool.remove(b); } }
2,913
34.108434
125
java
soot
soot-master/src/main/java/soot/toolkits/scalar/UnitValueBoxPair.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Unit; import soot.ValueBox; /** * Utility class used to package a Unit and a ValueBox together. */ public class UnitValueBoxPair { public Unit unit; public ValueBox valueBox; /** * Constructs a UnitValueBoxPair from a Unit object and a ValueBox object. * * @param unit * some Unit * @param valueBox * some ValueBox */ public UnitValueBoxPair(Unit unit, ValueBox valueBox) { this.unit = unit; this.valueBox = valueBox; } /** * Two UnitValueBoxPairs are equal iff they the Units they hold are 'equal' and the ValueBoxes they hold are 'equal'. * * @param other * another UnitValueBoxPair * @return true if equal. */ @Override public boolean equals(Object other) { if (other instanceof UnitValueBoxPair) { UnitValueBoxPair otherPair = (UnitValueBoxPair) other; if (this.unit.equals(otherPair.unit) && this.valueBox.equals(otherPair.valueBox)) { return true; } } return false; } @Override public int hashCode() { return unit.hashCode() + valueBox.hashCode(); } @Override public String toString() { return valueBox + " in " + unit; } public Unit getUnit() { return unit; } public ValueBox getValueBox() { return valueBox; } }
2,148
24.282353
119
java
soot
soot-master/src/main/java/soot/toolkits/scalar/UnusedLocalEliminator.java
package soot.toolkits.scalar; /*- * #%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.BitSet; import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.Local; import soot.Singletons; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.options.Options; import soot.util.Chain; /** * A BodyTransformer that removes all unused local variables from a given Body. Implemented as a singleton. * * @see BodyTransformer * @see Body */ public class UnusedLocalEliminator extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(UnusedLocalEliminator.class); public UnusedLocalEliminator(Singletons.Global g) { } public static UnusedLocalEliminator v() { return G.v().soot_toolkits_scalar_UnusedLocalEliminator(); } @Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { if (Options.v().verbose()) { logger.debug("[" + body.getMethod().getName() + "] Eliminating unused locals..."); } final Chain<Local> locals = body.getLocals(); final int numLocals = locals.size(); final int[] oldNumbers = new int[numLocals]; { int i = 0; for (Local local : locals) { oldNumbers[i] = local.getNumber(); local.setNumber(i); i++; } } BitSet usedLocals = new BitSet(numLocals); // Traverse statements noting all the uses and defs for (Unit s : body.getUnits()) { for (ValueBox vb : s.getUseBoxes()) { Value v = vb.getValue(); if (v instanceof Local) { Local l = (Local) v; // assert locals.contains(l); usedLocals.set(l.getNumber()); } } for (ValueBox vb : s.getDefBoxes()) { Value v = vb.getValue(); if (v instanceof Local) { Local l = (Local) v; // assert locals.contains(l); usedLocals.set(l.getNumber()); } } } // Remove all locals that are unused. for (Iterator<Local> localIt = locals.iterator(); localIt.hasNext();) { final Local local = localIt.next(); final int lno = local.getNumber(); if (!usedLocals.get(lno)) { localIt.remove(); } else { local.setNumber(oldNumbers[lno]); } } } }
3,172
27.845455
107
java
soot
soot-master/src/main/java/soot/toolkits/scalar/ValueUnitPair.java
package soot.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 soot.AbstractValueBox; import soot.EquivTo; import soot.Unit; import soot.UnitBox; import soot.UnitPrinter; import soot.Value; import soot.jimple.Jimple; /** * Utility class used to package a Value and a Unit together. * * @author Navindra Umanee **/ public class ValueUnitPair extends AbstractValueBox implements UnitBox, EquivTo { // oub was initially a private inner class. ended up being a // *bad* *bad* idea with endless opportunity for *evil* *evil* // pointer bugs. in the end so much code needed to be copy pasted // that using an innerclass to reuse code from AbstractUnitBox was // a losing proposition. // protected UnitBox oub; protected Unit unit; /** * Constructs a ValueUnitPair from a Unit object and a Value object. * * @param value * some Value * @param unit * some Unit. **/ public ValueUnitPair(Value value, Unit unit) { setValue(value); setUnit(unit); } @Override public boolean canContainValue(Value value) { return true; } /** * @see soot.UnitBox#setUnit(Unit) **/ @Override public void setUnit(Unit unit) { /* Code copied from AbstractUnitBox */ if (!canContainUnit(unit)) { throw new RuntimeException("Cannot put " + unit + " in this box"); } // Remove this from set of back pointers. if (this.unit != null) { this.unit.removeBoxPointingToThis(this); } // Perform link this.unit = unit; // Add this to back pointers if (this.unit != null) { this.unit.addBoxPointingToThis(this); } } /** * @see soot.UnitBox#getUnit() **/ @Override public Unit getUnit() { return unit; } /** * @see soot.UnitBox#canContainUnit(Unit) **/ @Override public boolean canContainUnit(Unit u) { return true; } /** * @see soot.UnitBox#isBranchTarget() **/ @Override public boolean isBranchTarget() { return true; } @Override public String toString() { return "Value = " + getValue() + ", Unit = " + getUnit(); } @Override public void toString(UnitPrinter up) { super.toString(up); up.literal(isBranchTarget() ? ", " : " #"); up.startUnitBox(this); up.unitRef(unit, isBranchTarget()); up.endUnitBox(this); } @Override public int hashCode() { // If you need to change this implementation, please change it in // a subclass. Otherwise, Shimple is likely to break in evil ways. return super.hashCode(); } @Override public boolean equals(Object other) { // If you need to change this implementation, please change it in // a subclass. Otherwise, Shimple is likely to break in evil ways. return super.equals(other); } /** * Two ValueUnitPairs are equivTo iff they hold the same Unit objects and equivalent Value objects within them. * * @param other * another ValueUnitPair * @return true if other contains the same objects as this. **/ @Override public boolean equivTo(Object other) { return (other instanceof ValueUnitPair) && ((ValueUnitPair) other).getValue().equivTo(this.getValue()) && ((ValueUnitPair) other).getUnit().equals(getUnit()); } /** * Non-deterministic hashcode consistent with equivTo() implementation. * * <p> * * <b>Note:</b> If you are concerned about non-determinism, remember that current implementations of equivHashCode() in * other parts of Soot are non-deterministic as well (see Constant.java for example). **/ @Override public int equivHashCode() { // this is not deterministic because a Unit's hash code is // non-deterministic. return (getUnit().hashCode() * 17) + (getValue().equivHashCode() * 101); } @Override public Object clone() { // Note to self: Do not try to "fix" this. 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. Value cv = Jimple.cloneIfNecessary(getValue()); Unit cu = getUnit(); return new ValueUnitPair(cv, cu); } }
5,043
26.562842
121
java
soot
soot-master/src/main/java/soot/tools/BadFields.java
package soot.tools; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.PackManager; import soot.PrimType; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Transform; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.FieldRef; import soot.jimple.InvokeExpr; import soot.jimple.StaticFieldRef; import soot.jimple.Stmt; public class BadFields extends SceneTransformer { private static final Logger logger = LoggerFactory.getLogger(BadFields.class); public static void main(String[] args) { PackManager.v().getPack("cg").add(new Transform("cg.badfields", new BadFields())); soot.Main.main(args); } private SootClass lastClass; private SootClass currentClass; protected void internalTransform(String phaseName, Map<String, String> options) { lastClass = null; for (Iterator<SootClass> clIt = Scene.v().getApplicationClasses().iterator(); clIt.hasNext();) { final SootClass cl = clIt.next(); currentClass = cl; handleClass(cl); for (Iterator<SootMethod> it = cl.methodIterator(); it.hasNext();) { handleMethod(it.next()); } } Scene.v().setCallGraph(Scene.v().internalMakeCallGraph()); } private void handleClass(SootClass cl) { for (Iterator<SootField> fIt = cl.getFields().iterator(); fIt.hasNext();) { final SootField f = fIt.next(); if (!f.isStatic()) { continue; } String typeName = f.getType().toString(); if (typeName.equals("java.lang.Class")) { continue; } if (f.isFinal()) { if (f.getType() instanceof PrimType) { continue; } if (typeName.equals("java.io.PrintStream")) { continue; } if (typeName.equals("java.lang.String")) { continue; } if (typeName.equals("java.lang.Object")) { continue; } if (typeName.equals("java.lang.Integer")) { continue; } if (typeName.equals("java.lang.Boolean")) { continue; } } warn("Bad field " + f); } } private void warn(String warning) { if (lastClass != currentClass) { logger.debug("" + "In class " + currentClass); } lastClass = currentClass; logger.debug("" + " " + warning); } private void handleMethod(SootMethod m) { if (!m.isConcrete()) { return; } for (Iterator<ValueBox> bIt = m.retrieveActiveBody().getUseAndDefBoxes().iterator(); bIt.hasNext();) { final ValueBox b = bIt.next(); Value v = b.getValue(); if (!(v instanceof StaticFieldRef)) { continue; } StaticFieldRef sfr = (StaticFieldRef) v; SootField f = sfr.getField(); if (!f.getDeclaringClass().getName().equals("java.lang.System")) { continue; } if (f.getName().equals("err")) { logger.debug("" + "Use of System.err in " + m); } if (f.getName().equals("out")) { logger.debug("" + "Use of System.out in " + m); } } for (Iterator<Unit> sIt = m.getActiveBody().getUnits().iterator(); sIt.hasNext();) { final Stmt s = (Stmt) sIt.next(); if (!s.containsInvokeExpr()) { continue; } InvokeExpr ie = s.getInvokeExpr(); SootMethod target = ie.getMethod(); if (target.getDeclaringClass().getName().equals("java.lang.System") && target.getName().equals("exit")) { warn("" + m + " calls System.exit"); } } if (m.getName().equals("<clinit>")) { for (Iterator<Unit> sIt = m.getActiveBody().getUnits().iterator(); sIt.hasNext();) { final Stmt s = (Stmt) sIt.next(); for (Iterator<ValueBox> bIt = s.getUseBoxes().iterator(); bIt.hasNext();) { final ValueBox b = bIt.next(); Value v = b.getValue(); if (v instanceof FieldRef) { warn(m.getName() + " reads field " + v); } } if (!s.containsInvokeExpr()) { continue; } InvokeExpr ie = s.getInvokeExpr(); SootMethod target = ie.getMethod(); calls(target); } } } private void calls(SootMethod target) { if (target.getName().equals("<init>")) { if (target.getDeclaringClass().getName().equals("java.io.PrintStream")) { return; } if (target.getDeclaringClass().getName().equals("java.lang.Boolean")) { return; } if (target.getDeclaringClass().getName().equals("java.lang.Integer")) { return; } if (target.getDeclaringClass().getName().equals("java.lang.String")) { return; } if (target.getDeclaringClass().getName().equals("java.lang.Object")) { return; } } if (target.getName().equals("getProperty")) { if (target.getDeclaringClass().getName().equals("java.lang.System")) { return; } } if (target.getName().equals("charAt")) { if (target.getDeclaringClass().getName().equals("java.lang.String")) { return; } } warn("<clinit> invokes " + target); } }
6,026
29.286432
111
java
soot
soot-master/src/main/java/soot/tools/CFGViewer.java
package soot.tools; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Sable Research Group * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.util.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.PackManager; import soot.PhaseOptions; import soot.SootMethod; import soot.Transform; import soot.jimple.JimpleBody; import soot.options.Options; import soot.toolkits.graph.DirectedGraph; import soot.util.cfgcmd.AltClassLoader; import soot.util.cfgcmd.CFGGraphType; import soot.util.cfgcmd.CFGIntermediateRep; import soot.util.cfgcmd.CFGToDotGraph; import soot.util.dot.DotGraph; /** * A utility class for generating dot graph file for a control flow graph * * @author Feng Qian */ public class CFGViewer extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(CFGViewer.class); private static final String packToJoin = "jtp"; private static final String phaseSubname = "printcfg"; private static final String phaseFullname = packToJoin + '.' + phaseSubname; private static final String altClassPathOptionName = "alt-class-path"; private static final String graphTypeOptionName = "graph-type"; private static final String defaultGraph = "BriefUnitGraph"; private static final String irOptionName = "ir"; private static final String defaultIR = "jimple"; private static final String multipageOptionName = "multipages"; private static final String briefLabelOptionName = "brief"; private CFGGraphType graphtype; private CFGIntermediateRep ir; private CFGToDotGraph drawer; private Map<String, String> methodsToPrint; // If the user specifies // particular // methods to print, this is a map // from method name to the class // name declaring the method. @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { initialize(options); SootMethod meth = b.getMethod(); if ((methodsToPrint == null) || (meth.getDeclaringClass().getName() == methodsToPrint.get(meth.getName()))) { Body body = ir.getBody((JimpleBody) b); print_cfg(body); } } public static void main(String[] args) { CFGViewer viewer = new CFGViewer(); Transform printTransform = new Transform(phaseFullname, viewer); printTransform.setDeclaredOptions("enabled " + altClassPathOptionName + ' ' + graphTypeOptionName + ' ' + irOptionName + ' ' + multipageOptionName + ' ' + briefLabelOptionName + ' '); printTransform.setDefaultOptions( "enabled " + altClassPathOptionName + ": " + graphTypeOptionName + ':' + defaultGraph + ' ' + irOptionName + ':' + defaultIR + ' ' + multipageOptionName + ":false " + ' ' + briefLabelOptionName + ":false "); PackManager.v().getPack("jtp").add(printTransform); args = viewer.parse_options(args); if (args.length == 0) { usage(); } else { soot.Main.main(args); } } private static void usage() { System.out.println("Usage:\n" // + " java soot.util.CFGViewer [soot options] [CFGViewer options] [class[:method]]...\n\n" + " CFGViewer options:\n" // + " (When specifying the value for an '=' option, you only\n" // + " need to type enough characters to specify the choice\n" // + " unambiguously, and case is ignored.)\n" + "\n" // + " --alt-classpath PATH :\n" // + " specifies the classpath from which to load classes\n" // + " that implement graph types whose names begin with 'Alt'.\n" // + " --graph={" + CFGGraphType.help(0, 70, " ".length()) + "} :\n" // + " show the specified type of graph.\n" + " Defaults to " + defaultGraph + ".\n" // + " --ir={" + CFGIntermediateRep.help(0, 70, " ".length()) + "} :\n" // + " create the CFG from the specified intermediate\n" // + " representation. Defaults to " + defaultIR + ".\n" // + " --brief :\n" + " label nodes with the unit or block index,\n" // + " instead of the text of their statements.\n" // + " --multipages :\n" + " produce dot file output for multiple 8.5x11\" pages.\n" // + " By default, a single page is produced.\n" // + " --help :\n" + " print this message.\n" // + "\n" // + " Particularly relevant soot options (see \"soot --help\" for details):\n" // + " --soot-class-path PATH\n" // + " --show-exception-dests\n" // + " --throw-analysis {pedantic|unit}\n" // + " --omit-excepting-unit-edges\n" // + " --trim-cfgs\n"); } /** * Parse the command line arguments specific to CFGViewer, and convert them into phase options for jtp.printcfg. * * @return an array of arguments to pass on to Soot.Main.main(). */ private String[] parse_options(String[] args) { List<String> sootArgs = new ArrayList<String>(args.length); for (int i = 0, n = args.length; i < n; i++) { if (args[i].equals("--alt-classpath") || args[i].equals("--alt-class-path")) { sootArgs.add("-p"); sootArgs.add(phaseFullname); sootArgs.add(altClassPathOptionName + ':' + args[++i]); } else if (args[i].startsWith("--graph=")) { sootArgs.add("-p"); sootArgs.add(phaseFullname); sootArgs.add(graphTypeOptionName + ':' + args[i].substring("--graph=".length())); } else if (args[i].startsWith("--ir=")) { sootArgs.add("-p"); sootArgs.add(phaseFullname); sootArgs.add(irOptionName + ':' + args[i].substring("--ir=".length())); } else if (args[i].equals("--brief")) { sootArgs.add("-p"); sootArgs.add(phaseFullname); sootArgs.add(briefLabelOptionName + ":true"); } else if (args[i].equals("--multipages")) { sootArgs.add("-p"); sootArgs.add(phaseFullname); sootArgs.add(multipageOptionName + ":true"); } else if (args[i].equals("--help")) { return new String[0]; // This is a cheesy method to inveigle // our caller into printing the help // and exiting. } else if (args[i].equals("--soot-class-path") || args[i].equals("-soot-class-path") || args[i].equals("--soot-classpath") || args[i].equals("-soot-classpath") || args[i].equals("--process-dir") || args[i].equals("-process-dir") || args[i].equals("--android-jars") || args[i].equals("-android-jars") || args[i].equals("--force-android-jar") || args[i].equals("-force-android-jar")) { // Pass classpaths without treating ":" as a method specifier. sootArgs.add(args[i]); sootArgs.add(args[++i]); } else if (args[i].equals("-p") || args[i].equals("--phase-option") || args[i].equals("-phase-option")) { // Pass phase options without treating ":" as a method // specifier. sootArgs.add(args[i]); sootArgs.add(args[++i]); sootArgs.add(args[++i]); } else { int smpos = args[i].indexOf(':'); if (smpos == -1) { sootArgs.add(args[i]); } else { String clsname = args[i].substring(0, smpos); sootArgs.add(clsname); String methname = args[i].substring(smpos + 1); if (methodsToPrint == null) { methodsToPrint = new HashMap<String, String>(); } methodsToPrint.put(methname, clsname); } } } String[] sootArgsArray = new String[sootArgs.size()]; return (String[]) sootArgs.toArray(sootArgsArray); } private void initialize(Map<String, String> options) { if (drawer == null) { drawer = new CFGToDotGraph(); drawer.setBriefLabels(PhaseOptions.getBoolean(options, briefLabelOptionName)); drawer.setOnePage(!PhaseOptions.getBoolean(options, multipageOptionName)); drawer.setUnexceptionalControlFlowAttr("color", "black"); drawer.setExceptionalControlFlowAttr("color", "red"); drawer.setExceptionEdgeAttr("color", "lightgray"); drawer.setShowExceptions(Options.v().show_exception_dests()); ir = CFGIntermediateRep.getIR(PhaseOptions.getString(options, irOptionName)); graphtype = CFGGraphType.getGraphType(PhaseOptions.getString(options, graphTypeOptionName)); AltClassLoader.v().setAltClassPath(PhaseOptions.getString(options, altClassPathOptionName)); AltClassLoader.v() .setAltClasses(new String[] { "soot.toolkits.graph.ArrayRefBlockGraph", "soot.toolkits.graph.Block", "soot.toolkits.graph.Block$AllMapTo", "soot.toolkits.graph.BlockGraph", "soot.toolkits.graph.BriefBlockGraph", "soot.toolkits.graph.BriefUnitGraph", "soot.toolkits.graph.CompleteBlockGraph", "soot.toolkits.graph.CompleteUnitGraph", "soot.toolkits.graph.TrapUnitGraph", "soot.toolkits.graph.UnitGraph", "soot.toolkits.graph.ZonedBlockGraph", }); } } protected void print_cfg(Body body) { String filename = soot.SourceLocator.v().getOutputDir(); if (!filename.isEmpty()) { filename = filename + File.separator; } String methodname = body.getMethod().getSubSignature(); String classname = body.getMethod().getDeclaringClass().getName().replaceAll("\\$", "\\."); filename = filename + classname + " " + methodname.replace(File.separatorChar, '.') + DotGraph.DOT_EXTENSION; logger.debug("Generate dot file in " + filename); DirectedGraph<?> graph = graphtype.buildGraph(body); DotGraph canvas = graphtype.drawGraph(drawer, graph, body); canvas.plot(filename); } }
10,630
43.85654
124
java
soot
soot-master/src/main/java/soot/util/AbstractMultiMap.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import heros.solver.Pair; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public abstract class AbstractMultiMap<K, V> implements MultiMap<K, V>, Serializable { private static final long serialVersionUID = 4558567794548019671L; private class EntryIterator implements Iterator<Pair<K, V>> { Iterator<K> keyIterator = keySet().iterator(); Iterator<V> valueIterator = null; K currentKey = null; @Override public boolean hasNext() { if (valueIterator != null && valueIterator.hasNext()) { return true; } // Prepare for the next key valueIterator = null; currentKey = null; return keyIterator.hasNext(); } @Override public Pair<K, V> next() { // Obtain the next key if (valueIterator == null) { currentKey = keyIterator.next(); valueIterator = get(currentKey).iterator(); } return new Pair<K, V>(currentKey, valueIterator.next()); } @Override public void remove() { if (valueIterator == null) { // Removing an element twice or removing no valid element does not make sense return; } valueIterator.remove(); if (get(currentKey).isEmpty()) { keyIterator.remove(); valueIterator = null; currentKey = null; } } } @Override public boolean putAll(MultiMap<K, V> m) { boolean hasNew = false; for (K key : m.keySet()) { if (putAll(key, m.get(key))) { hasNew = true; } } return hasNew; } @Override public boolean putAll(Map<K, Set<V>> m) { boolean hasNew = false; for (K key : m.keySet()) { if (putAll(key, m.get(key))) { hasNew = true; } } return hasNew; } @Override public boolean isEmpty() { return numKeys() == 0; } @Override public boolean contains(K key, V value) { Set<V> set = get(key); if (set == null) { return false; } return set.contains(value); } @Override public Iterator<Pair<K, V>> iterator() { return new EntryIterator(); } @Override public boolean putMap(Map<K, V> m) { boolean hasNew = false; for (Entry<K, V> entry : m.entrySet()) { if (put(entry.getKey(), entry.getValue())) { hasNew = true; } } return hasNew; } }
3,238
23.353383
86
java
soot
soot-master/src/main/java/soot/util/ArrayNumberer.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.NoSuchElementException; /** * A class that numbers objects, so they can be placed in bitsets. * * @author Ondrej Lhotak * @author xiao, generalize it. */ public class ArrayNumberer<E extends Numberable> implements IterableNumberer<E> { protected E[] numberToObj; protected int lastNumber; protected BitSet freeNumbers; @SuppressWarnings("unchecked") public ArrayNumberer() { this.numberToObj = (E[]) new Numberable[1024]; this.lastNumber = 0; } public ArrayNumberer(E[] elements) { this.numberToObj = elements; this.lastNumber = elements.length; } private void resize(int n) { numberToObj = Arrays.copyOf(numberToObj, n); } @Override public synchronized void add(E o) { if (o.getNumber() != 0) { return; } // In case we removed entries from the numberer, we want to re-use the free space int chosenNumber = -1; if (freeNumbers != null) { int ns = freeNumbers.nextSetBit(0); if (ns != -1) { chosenNumber = ns; freeNumbers.clear(ns); } } if (chosenNumber == -1) { chosenNumber = ++lastNumber; } if (chosenNumber >= numberToObj.length) { resize(numberToObj.length * 2); } numberToObj[chosenNumber] = o; o.setNumber(chosenNumber); } @Override public long get(E o) { if (o == null) { return 0; } int ret = o.getNumber(); if (ret == 0) { throw new RuntimeException("unnumbered: " + o); } return ret; } @Override public E get(long number) { if (number == 0) { return null; } E ret = numberToObj[(int) number]; if (ret == null) { return null; } return ret; } @Override public int size() { return lastNumber; } @Override public Iterator<E> iterator() { return new Iterator<E>() { int cur = 1; @Override public final boolean hasNext() { return cur <= lastNumber && cur < numberToObj.length && numberToObj[cur] != null; } @Override public final E next() { if (hasNext()) { return numberToObj[cur++]; } throw new NoSuchElementException(); } @Override public final void remove() { ArrayNumberer.this.remove(numberToObj[cur - 1]); } }; } @Override public boolean remove(E o) { if (o == null) { return false; } int num = o.getNumber(); if (num == 0) { return false; } if (freeNumbers == null) { freeNumbers = new BitSet(2 * num); } numberToObj[num] = null; o.setNumber(0); freeNumbers.set(num); return true; } }
3,562
21.987097
89
java
soot
soot-master/src/main/java/soot/util/ArraySet.java
package soot.util; /*- * #%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.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * Provides an implementation of the Set interface using an array. * * @param <E> */ public class ArraySet<E> extends AbstractSet<E> { private static final int DEFAULT_SIZE = 8; private int numElements; private int maxElements; private E[] elements; public ArraySet(int size) { maxElements = size; @SuppressWarnings("unchecked") E[] newElements = (E[]) new Object[size]; elements = newElements; numElements = 0; } public ArraySet() { this(DEFAULT_SIZE); } /** * Create a set which contains the given elements. */ public ArraySet(E[] elements) { this(); for (E element : elements) { add(element); } } @Override final public void clear() { numElements = 0; } @Override final public boolean contains(Object obj) { for (int i = 0; i < numElements; i++) { if (elements[i].equals(obj)) { return true; } } return false; } /** * Add an element without checking whether it is already in the set. It is up to the caller to guarantee that it isn't. */ final public boolean addElement(E e) { if (e == null) { throw new RuntimeException("oops"); } // Expand array if necessary if (numElements == maxElements) { doubleCapacity(); } // Add element elements[numElements++] = e; return true; } @Override final public boolean add(E e) { if (e == null) { throw new RuntimeException("oops"); } if (contains(e)) { return false; } else { // Expand array if necessary if (numElements == maxElements) { doubleCapacity(); } // Add element elements[numElements++] = e; return true; } } @Override final public boolean addAll(Collection<? extends E> s) { if (s instanceof ArraySet) { boolean ret = false; ArraySet<? extends E> as = (ArraySet<? extends E>) s; for (E elem : as.elements) { ret |= add(elem); } return ret; } else { return super.addAll(s); } } @Override final public int size() { return numElements; } @Override final public Iterator<E> iterator() { return new ArrayIterator(); } private class ArrayIterator implements Iterator<E> { int nextIndex; ArrayIterator() { nextIndex = 0; } @Override final public boolean hasNext() { return nextIndex < numElements; } @Override final public E next() throws NoSuchElementException { if (!(nextIndex < numElements)) { throw new NoSuchElementException(); } else { return elements[nextIndex++]; } } @Override final public void remove() throws NoSuchElementException { if (nextIndex == 0) { throw new NoSuchElementException(); } else { removeElementAt(nextIndex - 1); nextIndex = nextIndex - 1; } } } private void removeElementAt(int index) { // Handle simple case if (index == numElements - 1) { numElements--; return; } // Else, shift over elements System.arraycopy(elements, index + 1, elements, index, numElements - (index + 1)); numElements--; } private void doubleCapacity() { // plus one to ensure that we have at least one element int newSize = maxElements * 2 + 1; @SuppressWarnings("unchecked") E[] newElements = (E[]) new Object[newSize]; System.arraycopy(elements, 0, newElements, 0, numElements); elements = newElements; maxElements = newSize; } @Override final public E[] toArray() { @SuppressWarnings("unchecked") E[] array = (E[]) new Object[numElements]; System.arraycopy(elements, 0, array, 0, numElements); return array; } @Override final public <T> T[] toArray(T[] array) { if (array.length < numElements) { @SuppressWarnings("unchecked") T[] ret = (T[]) Arrays.copyOf(elements, numElements, array.getClass()); return ret; } else { System.arraycopy(elements, 0, array, 0, numElements); if (array.length > numElements) { array[numElements] = null; } return array; } } final public Object[] getUnderlyingArray() { return elements; } }
5,238
22.388393
121
java
soot
soot-master/src/main/java/soot/util/BitSetIterator.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2001 Felix Kwok * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.NoSuchElementException; /** * A fast enumerator for sparse bit sets. When the enumerator is created, it takes a snapshot of the underlying BitVector, * and iterates through the set bits. Note that this class almost implements the Iterator interface, but it doesn't because * the return type of next is int rather than Object. */ public class BitSetIterator { long[] bits; // Bits inherited from the underlying BitVector int index; // The 64-bit block currently being examined long save = 0; // A copy of the 64-bit block (for fast access) /* * Computes log_2(x) modulo 67. This uses the fact that 2 is a primitive root modulo 67 */ final static int[] lookup = { -1, 0, 1, 39, 2, 15, 40, 23, 3, 12, 16, 59, 41, 19, 24, 54, 4, -1, 13, 10, 17, 62, 60, 28, 42, 30, 20, 51, 25, 44, 55, 47, 5, 32, -1, 38, 14, 22, 11, 58, 18, 53, -1, 9, 61, 27, 29, 50, 43, 46, 31, 37, 21, 57, 52, 8, 26, 49, 45, 36, 56, 7, 48, 35, 6, 34, 33 }; /** Creates a new BitSetIterator */ BitSetIterator(long[] bits) { // this.bits = new long[bits.length]; // System.arraycopy(bits,0,this.bits,0,bits.length); this.bits = bits; index = 0; /* Zip through empty blocks */ while (index < bits.length && bits[index] == 0L) { index++; } if (index < bits.length) { save = bits[index]; } } /** Returns true if there are more set bits in the BitVector; false otherwise. */ public boolean hasNext() { return index < bits.length; } /** * Returns the index of the next set bit. Note that the return type is int, and not Object. */ public int next() { if (index >= bits.length) { throw new NoSuchElementException(); } long k = (save & (save - 1)); // Clears the last non-zero bit. save is guaranteed non-zero. long diff = save ^ k; // Finds out which bit it is. diff has exactly one bit set. save = k; // Computes the position of the set bit. int result = (diff < 0) ? 64 * index + 63 : 64 * index + lookup[(int) (diff % 67)]; if (save == 0) { index++; while (index < bits.length && bits[index] == 0L) { index++; } if (index < bits.length) { save = bits[index]; } } return result; } }
3,084
32.172043
123
java
soot
soot-master/src/main/java/soot/util/BitVector.java
package soot.util; /*- * #%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% */ /** * This is the Soot internal implementation of java.util.BitSet with Felix and Jerome's clever efficient iterator. It was * re-implemented from scratch by Ondrej Lhotak to avoid licence issues. It was named BitVector rather than BitSet to avoid a * name clash with the one in the standard Java library. * * @author Ondrej Lhotak */ public class BitVector { private long[] bits; public BitVector() { this(64); } /** Copy constructor */ // Added by Adam Richard. More efficient than clone(), and easier to extend public BitVector(BitVector other) { final long[] otherBits = other.bits; bits = new long[otherBits.length]; System.arraycopy(otherBits, 0, bits, 0, otherBits.length); } public BitVector(int numBits) { int lastIndex = indexOf(numBits - 1); bits = new long[lastIndex + 1]; } private int indexOf(int bit) { return bit >> 6; } private long mask(int bit) { return 1L << (bit & 63); } public void and(BitVector other) { if (this == other) { return; } final long[] otherBits = other.bits; int numToAnd = otherBits.length; if (bits.length < numToAnd) { numToAnd = bits.length; } int i; for (i = 0; i < numToAnd; i++) { bits[i] = bits[i] & otherBits[i]; } for (; i < bits.length; i++) { bits[i] = 0L; } } public void andNot(BitVector other) { final long[] otherBits = other.bits; int numToAnd = otherBits.length; if (bits.length < numToAnd) { numToAnd = bits.length; } for (int i = 0; i < numToAnd; i++) { bits[i] = bits[i] & ~otherBits[i]; } } public void clear(int bit) { if (indexOf(bit) < bits.length) { bits[indexOf(bit)] &= ~mask(bit); } } @Override public Object clone() { try { BitVector ret = (BitVector) super.clone(); System.arraycopy(bits, 0, ret.bits, 0, ret.bits.length); return ret; } catch (CloneNotSupportedException e) { // cannot occur throw new RuntimeException(e); } } @Override public boolean equals(Object o) { if (!(o instanceof BitVector)) { return false; } final long[] otherBits = ((BitVector) o).bits; long[] longer = otherBits; int min = bits.length; if (otherBits.length < min) { min = otherBits.length; longer = bits; } int i; for (i = 0; i < min; i++) { if (bits[i] != otherBits[i]) { return false; } } for (; i < longer.length; i++) { if (longer[i] != 0L) { return false; } } return true; } public boolean get(int bit) { if (indexOf(bit) >= bits.length) { return false; } return (bits[indexOf(bit)] & mask(bit)) != 0L; } @Override public int hashCode() { long ret = 0; for (long element : bits) { ret ^= element; } return (int) ((ret >> 32) ^ ret); } /** Returns index of highest-numbered one bit. */ public int length() { int i; for (i = bits.length - 1; i >= 0; i--) { if (bits[i] != 0L) { break; } } if (i < 0) { return 0; } long j = bits[i]; i++; i <<= 6; for (long k = 1L << 63; (k & j) == 0L; k >>= 1, i--) { } return i; } public void copyFrom(BitVector other) { if (this == other) { return; } final long[] otherBits = other.bits; int j; for (j = otherBits.length - 1; j >= 0; j--) { if (otherBits[j] != 0L) { break; } } expand(j << 6); int i = j + 1; for (; j >= 0; j--) { bits[j] = otherBits[j]; } for (; i < bits.length; i++) { bits[i] = 0L; } } public void or(BitVector other) { if (this == other) { return; } final long[] otherBits = other.bits; int j; for (j = otherBits.length - 1; j >= 0; j--) { if (otherBits[j] != 0L) { break; } } expand(j << 6); for (; j >= 0; j--) { bits[j] |= otherBits[j]; } } /** * Count the number of ones in the bitvector. * * @author Adam Richard This is Brian Kernighan's algorithm from: http://graphics.stanford.edu/~seander/bithacks.html and * is efficient for sparse bit sets. */ public int cardinality() { int c = 0; for (long v : bits) { while (v != 0) { v &= v - 1; ++c; } } return c; } /** * Returns true if the both the current and the specified bitvectors have at least one bit set in common. * * @author Quentin Sabah Inspired by the BitVector.and method. */ public boolean intersects(BitVector other) { final long[] otherBits = other.bits; int numToCheck = otherBits.length; if (bits.length < numToCheck) { numToCheck = bits.length; } int i; for (i = 0; i < numToCheck; i++) { if ((bits[i] & otherBits[i]) != 0) { return true; } } return false; } private void expand(int bit) { int n = indexOf(bit) + 1; if (n <= bits.length) { return; } if (bits.length * 2 > n) { n = bits.length * 2; } long[] newBits = new long[n]; System.arraycopy(bits, 0, newBits, 0, bits.length); bits = newBits; } public void xor(BitVector other) { if (this == other) { return; } final long[] otherBits = other.bits; int j; for (j = otherBits.length - 1; j >= 0; j--) { if (otherBits[j] != 0L) { break; } } expand(j << 6); for (; j >= 0; j--) { bits[j] ^= otherBits[j]; } } public boolean set(int bit) { expand(bit); boolean ret = !get(bit); bits[indexOf(bit)] |= mask(bit); return ret; } /** Returns number of bits in the underlying array. */ public int size() { return bits.length << 6; } @Override public String toString() { StringBuilder ret = new StringBuilder(); ret.append('{'); boolean start = true; for (BitSetIterator it = new BitSetIterator(bits); it.hasNext();) { int bit = it.next(); if (start) { start = false; } else { ret.append(", "); } ret.append(bit); } ret.append('}'); return ret.toString(); } /** * Computes this = this OR ((orset AND andset ) AND (NOT andnotset)) Returns true iff this is modified. */ public boolean orAndAndNot(BitVector orset, BitVector andset, BitVector andnotset) { final long[] a, b, c, d; final int al, bl, cl, dl; { a = this.bits; al = a.length; } if (orset == null) { b = null; bl = 0; } else { b = orset.bits; bl = b.length; } if (andset == null) { c = null; cl = 0; } else { c = andset.bits; cl = c.length; } if (andnotset == null) { d = null; dl = 0; } else { d = andnotset.bits; dl = d.length; } final long[] e; if (al < bl) { e = new long[bl]; System.arraycopy(a, 0, e, 0, al); this.bits = e; } else { e = a; } boolean ret = false; if (c == null) { if (dl <= bl) { int i = 0; for (; i < dl; i++) { long l = b[i] & ~d[i]; if ((l & ~e[i]) != 0) { ret = true; } e[i] |= l; } for (; i < bl; i++) { long l = b[i]; if ((l & ~e[i]) != 0) { ret = true; } e[i] |= l; } } else { for (int i = 0; i < bl; i++) { long l = b[i] & ~d[i]; if ((l & ~e[i]) != 0) { ret = true; } e[i] |= l; } } } else if (bl <= cl && bl <= dl) { // bl is the shortest for (int i = 0; i < bl; i++) { long l = b[i] & c[i] & ~d[i]; if ((l & ~e[i]) != 0) { ret = true; } e[i] |= l; } } else if (cl <= bl && cl <= dl) { // cl is the shortest for (int i = 0; i < cl; i++) { long l = b[i] & c[i] & ~d[i]; if ((l & ~e[i]) != 0) { ret = true; } e[i] |= l; } } else { // dl is the shortest int i = 0; for (; i < dl; i++) { long l = b[i] & c[i] & ~d[i]; if ((l & ~e[i]) != 0) { ret = true; } e[i] |= l; } for (int shorter = (bl < cl) ? bl : cl; i < shorter; i++) { long l = b[i] & c[i]; if ((l & ~e[i]) != 0) { ret = true; } e[i] |= l; } } return ret; } public static BitVector and(BitVector set1, BitVector set2) { int min = set1.size(); { int max = set2.size(); if (min > max) { min = max; } // max is not necessarily correct at this point, so let it go // out of scope } BitVector ret = new BitVector(min); long[] retbits = ret.bits; long[] bits1 = set1.bits; long[] bits2 = set2.bits; min >>= 6; for (int i = 0; i < min; i++) { retbits[i] = bits1[i] & bits2[i]; } return ret; } public static BitVector or(BitVector set1, BitVector set2) { int min = set1.size(); int max = set2.size(); if (min > max) { min = max; max = set1.size(); } BitVector ret = new BitVector(max); long[] retbits = ret.bits; long[] bits1 = set1.bits; long[] bits2 = set2.bits; min >>= 6; max >>= 6; for (int i = 0; i < min; i++) { retbits[i] = bits1[i] | bits2[i]; } if (bits1.length == min) { System.arraycopy(bits2, min, retbits, min, max - min); } else { System.arraycopy(bits1, min, retbits, min, max - min); } return ret; } public BitSetIterator iterator() { return new BitSetIterator(bits); } }
10,608
21.913607
125
java
soot
soot-master/src/main/java/soot/util/Chain.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrice Pominville * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Augmented data type guaranteeing O(1) insertion and removal from a set of ordered, unique elements. * * @param <E> * element type */ public interface Chain<E> extends Collection<E>, Serializable { /** Inserts <code>toInsert</code> in the Chain before <code>point</code>. */ public void insertBefore(E toInsert, E point); /** Inserts <code>toInsert</code> in the Chain after <code>point</code>. */ public void insertAfter(E toInsert, E point); /** Inserts <code>toInsert</code> in the Chain before <code>point</code>. */ public void insertBefore(Chain<E> toInsert, E point); /** Inserts <code>toInsert</code> in the Chain after <code>point</code>. */ public void insertAfter(Chain<E> toInsert, E point); /** Inserts <code>toInsert</code> in the Chain before <code>point</code>. */ public void insertBefore(List<E> toInsert, E point); /** Inserts <code>toInsert</code> in the Chain after <code>point</code>. */ public void insertAfter(List<E> toInsert, E point); /** Inserts <code>toInsert</code> in the Chain before <code>point</code>. */ public void insertBefore(Collection<? extends E> toInsert, E point); /** Inserts <code>toInsert</code> in the Chain after <code>point</code>. */ public void insertAfter(Collection<? extends E> toInsert, E point); /** Replaces <code>out</code> in the Chain by <code>in</code>. */ public void swapWith(E out, E in); /** * Removes the given object from this Chain. Parameter has to be of type {@link Object} to be compatible with the * {@link Collection} interface. */ @Override public boolean remove(Object u); /** Adds the given object at the beginning of the Chain. */ public void addFirst(E u); /** Adds the given object at the end of the Chain. */ public void addLast(E u); /** Removes the first object contained in this Chain. */ public void removeFirst(); /** Removes the last object contained in this Chain. */ public void removeLast(); /** * Returns true if object <code>someObject</code> follows object <code>someReferenceObject</code> in the Chain, i.e. * someReferenceObject comes first and then someObject. */ public boolean follows(E someObject, E someReferenceObject); /** Returns the first object in this Chain. */ public E getFirst(); /** Returns the last object in this Chain. */ public E getLast(); /** Returns the object immediately following <code>point</code>. */ public E getSuccOf(E point); /** Returns the object immediately preceding <code>point</code>. */ public E getPredOf(E point); /** * Returns an iterator over a copy of this chain. This avoids ConcurrentModificationExceptions from being thrown if the * underlying Chain is modified during iteration. Do not use this to remove elements which have not yet been iterated over! */ public Iterator<E> snapshotIterator(); /** Returns an iterator over this Chain. */ @Override public Iterator<E> iterator(); /** Returns an iterator over this Chain, starting at the given object. */ public Iterator<E> iterator(E u); /** Returns an iterator over this Chain, starting at head and reaching tail (inclusive). */ public Iterator<E> iterator(E head, E tail); /** Returns the size of this Chain. */ @Override public int size(); /** Returns the number of times this chain has been modified. */ long getModificationCount(); /** * Gets all elements in the chain. There is no guarantee on sorting. On the other hand, the collection returned by this * method is thread-safe. You can iterate over it even in the case of concurrent modifications to the underlying chain. * * @return All elements in the chain in an unsorted collection */ public Collection<E> getElementsUnsorted(); }
4,713
34.179104
125
java
soot
soot-master/src/main/java/soot/util/ConcurrentHashMultiMap.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * A concurrent version of the {@link HashMultiMap} * * @author Steven Arzt */ public class ConcurrentHashMultiMap<K, V> extends AbstractMultiMap<K, V> { private static final long serialVersionUID = -3182515910302586044L; private final Map<K, ConcurrentMap<V, V>> m = new ConcurrentHashMap<K, ConcurrentMap<V, V>>(0); public ConcurrentHashMultiMap() { } public ConcurrentHashMultiMap(MultiMap<K, V> m) { putAll(m); } @Override public int numKeys() { return m.size(); } @Override public boolean containsKey(Object key) { return m.containsKey(key); } @Override public boolean containsValue(V value) { for (Map<V, V> s : m.values()) { if (s.containsKey(value)) { return true; } } return false; } protected ConcurrentMap<V, V> newSet() { return new ConcurrentHashMap<V, V>(); } private ConcurrentMap<V, V> findSet(K key) { ConcurrentMap<V, V> s = m.get(key); if (s == null) { synchronized (this) { // Better check twice, another thread may have created a set in // the meantime s = m.get(key); if (s == null) { s = newSet(); m.put(key, s); } } } return s; } @Override public boolean put(K key, V value) { return findSet(key).put(value, value) == null; } public V putIfAbsent(K key, V value) { return findSet(key).putIfAbsent(value, value); } @Override public boolean putAll(K key, Set<V> values) { if (values == null || values.isEmpty()) { return false; } ConcurrentMap<V, V> s = m.get(key); if (s == null) { synchronized (this) { // We atomically create a new set, and add the data, before // making the new set visible to the outside. Therefore, // concurrent threads will only either see the empty set from // before or the full set from after the add, but never anything // in between. s = m.get(key); if (s == null) { ConcurrentMap<V, V> newSet = newSet(); for (V v : values) { newSet.put(v, v); } m.put(key, newSet); return true; } } } // No "else", we can fall through if the set was created between first // check and obtaining the lock. boolean ok = false; for (V v : values) { if (s.put(v, v) == null) { ok = true; } } return ok; } @Override public boolean remove(K key, V value) { Map<V, V> s = m.get(key); if (s == null) { return false; } boolean ret = s.remove(value) != null; if (s.isEmpty()) { m.remove(key); } return ret; } @Override public boolean remove(K key) { return null != m.remove(key); } @Override public boolean removeAll(K key, Set<V> values) { Map<V, V> s = m.get(key); if (s == null) { return false; } boolean ret = false; for (V v : values) { if (s.remove(v) != null) { ret = true; } } if (s.isEmpty()) { m.remove(key); } return ret; } @Override public Set<V> get(K o) { Map<V, V> ret = m.get(o); if (ret == null) { return Collections.emptySet(); } else { return Collections.unmodifiableSet(ret.keySet()); } } @Override public Set<K> keySet() { return m.keySet(); } @Override public Set<V> values() { Set<V> ret = new HashSet<V>(m.size()); for (Map<V, V> s : m.values()) { ret.addAll(s.keySet()); } return ret; } @Override public boolean equals(Object o) { if (!(o instanceof MultiMap)) { return false; } @SuppressWarnings("unchecked") MultiMap<K, V> mm = (MultiMap<K, V>) o; if (!keySet().equals(mm.keySet())) { return false; } for (Map.Entry<K, ConcurrentMap<V, V>> e : m.entrySet()) { Map<V, V> s = e.getValue(); if (!s.equals(mm.get(e.getKey()))) { return false; } } return true; } @Override public int hashCode() { return m.hashCode(); } @Override public int size() { return m.size(); } @Override public void clear() { m.clear(); } @Override public String toString() { return m.toString(); } }
5,295
21.440678
97
java
soot
soot-master/src/main/java/soot/util/Cons.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** A Lisp-style cons cell. */ public final class Cons<U, V> { final private U car; final private V cdr; public Cons(U car, V cdr) { this.car = car; this.cdr = cdr; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((car == null) ? 0 : car.hashCode()); result = prime * result + ((cdr == null) ? 0 : cdr.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") Cons<U, V> other = (Cons<U, V>) obj; if (car == null) { if (other.car != null) { return false; } } else if (!car.equals(other.car)) { return false; } if (cdr == null) { if (other.cdr != null) { return false; } } else if (!cdr.equals(other.cdr)) { return false; } return true; } public U car() { return car; } public V cdr() { return cdr; } @Override public String toString() { return car.toString() + "," + cdr.toString(); } }
2,037
22.425287
71
java
soot
soot-master/src/main/java/soot/util/DeterministicHashMap.java
package soot.util; /*- * #%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.AbstractSet; import java.util.HashMap; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; /** * Implementation of HashMap which guarantees a stable (between executions) order for its elements upon iteration. * * This is quite useful for maps of Locals, to avoid nondeterministic local-name drift. */ public class DeterministicHashMap<K, V> extends HashMap<K, V> { Set<K> keys = new TrustingMonotonicArraySet<K>(); /** Constructs a DeterministicHashMap with the given initial capacity. */ public DeterministicHashMap(int initialCapacity) { super(initialCapacity); } /** Constructs a DeterministicHashMap with the given initial capacity and load factor. */ public DeterministicHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** Inserts a mapping in this HashMap from <code>key</code> to <code>value</code>. */ @Override public V put(K key, V value) { if (!containsKey(key)) { keys.add(key); } return super.put(key, value); } /** Removes the given object from this HashMap (unsupported). */ @Override public V remove(Object obj) { throw new UnsupportedOperationException(); } /** Returns a backed list of keys for this HashMap (unsupported). */ @Override public Set<K> keySet() { return keys; } } /** * ArraySet which doesn't check that the elements that you insert are previous uncontained. */ class TrustingMonotonicArraySet<T> extends AbstractSet<T> { private static final int DEFAULT_SIZE = 8; private int numElements; private int maxElements; private T[] elements; public TrustingMonotonicArraySet() { maxElements = DEFAULT_SIZE; @SuppressWarnings("unchecked") T[] newElements = (T[]) new Object[DEFAULT_SIZE]; elements = newElements; numElements = 0; } /** * Create a set which contains the given elements. */ public TrustingMonotonicArraySet(T[] elements) { this(); for (T element : elements) { add(element); } } @Override public void clear() { numElements = 0; } @Override public boolean contains(Object obj) { for (int i = 0; i < numElements; i++) { if (elements[i].equals(obj)) { return true; } } return false; } @Override public boolean add(T e) { // Expand array if necessary if (numElements == maxElements) { doubleCapacity(); } // Add element elements[numElements++] = e; return true; } @Override public int size() { return numElements; } @Override public Iterator<T> iterator() { return new ArrayIterator(); } private class ArrayIterator implements Iterator<T> { private int nextIndex; ArrayIterator() { nextIndex = 0; } @Override public boolean hasNext() { return nextIndex < numElements; } @Override public T next() throws NoSuchElementException { if (!(nextIndex < numElements)) { throw new NoSuchElementException(); } return elements[nextIndex++]; } @Override public void remove() throws NoSuchElementException { if (nextIndex == 0) { throw new NoSuchElementException(); } else { removeElementAt(nextIndex - 1); nextIndex = nextIndex - 1; } } } private void removeElementAt(int index) { throw new UnsupportedOperationException(); /* * // Handle simple case if(index == numElements - 1) { numElements--; return; } * * // Else, shift over elements System.arraycopy(elements, index + 1, elements, index, numElements - (index + 1)); * numElements--; */ } private void doubleCapacity() { int newSize = maxElements * 2; @SuppressWarnings("unchecked") T[] newElements = (T[]) new Object[newSize]; System.arraycopy(elements, 0, newElements, 0, numElements); elements = newElements; maxElements = newSize; } @Override public T[] toArray() { @SuppressWarnings("unchecked") T[] array = (T[]) new Object[numElements]; System.arraycopy(elements, 0, array, 0, numElements); return array; } }
5,012
23.816832
118
java
soot
soot-master/src/main/java/soot/util/EmptyChain.java
package soot.util; /*- * #%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.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Class representing an unmodifiable empty chain * * @author Steven Arzt * * @param <T> */ public class EmptyChain<T> implements Chain<T> { private static final long serialVersionUID = 1675685752701192002L; // Lazy initialized singleton private static class EmptyIteratorSingleton { static final Iterator<Object> INSTANCE = new Iterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { throw new NoSuchElementException(); } }; } private static <X> Iterator<X> emptyIterator() { @SuppressWarnings("unchecked") Iterator<X> retVal = (Iterator<X>) EmptyIteratorSingleton.INSTANCE; return retVal; } // Lazy initialized singleton private static class EmptyChainSingleton { static final EmptyChain<Object> INSTANCE = new EmptyChain<Object>(); } public static <X> EmptyChain<X> v() { @SuppressWarnings("unchecked") EmptyChain<X> retVal = (EmptyChain<X>) EmptyChainSingleton.INSTANCE; return retVal; } @Override public String toString() { return "[]"; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object o) { return false; } @Override public Object[] toArray() { return new Object[0]; } @Override public <X> X[] toArray(X[] a) { @SuppressWarnings("unchecked") X[] retVal = (X[]) new Object[0]; return retVal; } @Override public boolean add(T e) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends T> c) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public boolean removeAll(Collection<?> c) { throw new RuntimeException("Cannot remove elements from an unmodifiable chain"); } @Override public boolean retainAll(Collection<?> c) { throw new RuntimeException("Cannot add elements to an unmodifiable chain or remove ones from such chain"); } @Override public void clear() { throw new RuntimeException("Cannot remove elements from an unmodifiable chain"); } @Override public void insertBefore(List<T> toInsert, T point) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void insertAfter(List<T> toInsert, T point) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void insertAfter(T toInsert, T point) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void insertBefore(T toInsert, T point) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void insertBefore(Chain<T> toInsert, T point) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void insertAfter(Chain<T> toInsert, T point) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void swapWith(T out, T in) { throw new RuntimeException("Cannot replace elements in an unmodifiable chain"); } @Override public boolean remove(Object u) { throw new RuntimeException("Cannot remove elements from an unmodifiable chain"); } @Override public void addFirst(T u) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void addLast(T u) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void removeFirst() { throw new RuntimeException("Cannot remove elements from an unmodifiable chain"); } @Override public void removeLast() { throw new RuntimeException("Cannot remove elements from an unmodifiable chain"); } @Override public boolean follows(T someObject, T someReferenceObject) { return false; } @Override public T getFirst() { throw new NoSuchElementException(); } @Override public T getLast() { throw new NoSuchElementException(); } @Override public T getSuccOf(T point) { throw new NoSuchElementException(); } @Override public T getPredOf(T point) { throw new NoSuchElementException(); } @Override public Iterator<T> snapshotIterator() { return emptyIterator(); } @Override public Iterator<T> iterator() { return emptyIterator(); } @Override public Iterator<T> iterator(T u) { return emptyIterator(); } @Override public Iterator<T> iterator(T head, T tail) { return emptyIterator(); } @Override public int size() { return 0; } @Override public long getModificationCount() { return 0; } @Override public Collection<T> getElementsUnsorted() { return Collections.emptyList(); } @Override public void insertAfter(Collection<? extends T> toInsert, T point) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } @Override public void insertBefore(Collection<? extends T> toInsert, T point) { throw new RuntimeException("Cannot add elements to an unmodifiable chain"); } }
6,418
23.041199
110
java
soot
soot-master/src/main/java/soot/util/EscapedReader.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A FilterReader which catches escaped characters (<code>\\unnnn</code>) in the input and de-escapes them. Used in the * Jimple Parser. */ public class EscapedReader extends FilterReader { private static final Logger logger = LoggerFactory.getLogger(EscapedReader.class); /** Constructs an EscapedReader around the given Reader. */ public EscapedReader(Reader fos) { super(fos); } private StringBuffer mini = new StringBuffer(); boolean nextF; int nextch = 0; /** Reads a character from the input. */ public int read() throws IOException { /* if you already read the char, just return it */ if (nextF) { nextF = false; return nextch; } int ch = super.read(); if (ch != '\\') { return ch; } /* we may have an escape sequence here .. */ mini = new StringBuffer(); ch = super.read(); if (ch != 'u') { nextF = true; nextch = ch; return '\\'; } mini.append("\\u"); while (mini.length() < 6) { ch = super.read(); mini.append((char) ch); } // logger.debug(""+mini.toString()); ch = Integer.parseInt(mini.substring(2).toString(), 16); return ch; } }
2,166
24.494118
119
java
soot
soot-master/src/main/java/soot/util/EscapedWriter.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.FilterWriter; import java.io.IOException; import java.io.Writer; /** * A FilterWriter which catches to-be-escaped characters (<code>\\unnnn</code>) in the input and substitutes their escaped * representation. Used for Soot output. */ public class EscapedWriter extends FilterWriter { /** Convenience field containing the system's line separator. */ public final String lineSeparator = System.getProperty("line.separator"); private final int cr = lineSeparator.charAt(0); private final int lf = (lineSeparator.length() == 2) ? lineSeparator.charAt(1) : -1; /** Constructs an EscapedWriter around the given Writer. */ public EscapedWriter(Writer fos) { super(fos); } private final StringBuffer mini = new StringBuffer(); /** Print a single character (unsupported). */ public void print(int ch) throws IOException { write(ch); throw new RuntimeException(); } /** Write a segment of the given String. */ public void write(String s, int off, int len) throws IOException { for (int i = off; i < off + len; i++) { write(s.charAt(i)); } } /** Write a single character. */ public void write(int ch) throws IOException { if (ch >= 32 && ch <= 126 || ch == cr || ch == lf || ch == ' ') { super.write(ch); return; } mini.setLength(0); mini.append(Integer.toHexString(ch)); while (mini.length() < 4) { mini.insert(0, "0"); } mini.insert(0, "\\u"); for (int i = 0; i < mini.length(); i++) { super.write(mini.charAt(i)); } } }
2,386
29.21519
122
java
soot
soot-master/src/main/java/soot/util/FastStack.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrice Pominville * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; /** * A fast, but simple stack implementation. Sadly, java's own stack implementation synchronizes and as such is a bit slower. * * Note that this implementation does not perform error checking, however, the original implementation would also have thrown * an exception in case this implementation throws an exception. It's just that the exception text differs. * * @param <T> * The elements of the stack * @author Marc Miltenberger */ public class FastStack<T> extends ArrayList<T> { private static final long serialVersionUID = 1L; /** * Creates a new stack */ public FastStack() { } /** * Creates a new stack with the given initial size * * @param initialSize * the initial size */ public FastStack(int initialSize) { super(initialSize); } /** * Returns the last item on the stack or throws an exception of there is none. * * @return the last item on the stack */ public T peek() { return get(size() - 1); } /** * Pushes an item onto the stack * * @param t * the item */ public void push(T t) { add(t); } /** * Returns and removes the last item from the stack. Throws an exception of there is none. * * @return the last item on the stack, which got pop-ed. */ public T pop() { return remove(size() - 1); } /** * Returns true if and only if the stack is empty * * @return true if and only if the stack is empty */ public boolean empty() { return size() == 0; } }
2,397
24.510638
125
java
soot
soot-master/src/main/java/soot/util/HashChain.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrice Pominville * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.Serializable; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; /** * Reference implementation of the Chain interface, using a HashMap as the underlying structure. */ public class HashChain<E> extends AbstractCollection<E> implements Chain<E> { protected final Map<E, Link<E>> map; protected E firstItem; protected E lastItem; protected int stateCount = 0; /** Constructs an empty HashChain. */ public HashChain() { this.map = new ConcurrentHashMap<>(); this.firstItem = null; this.lastItem = null; } /** Constructs an empty HashChain with the given initial capacity. */ public HashChain(int initialCapacity) { this.map = new ConcurrentHashMap<>(initialCapacity); this.firstItem = null; this.lastItem = null; } /** Constructs a HashChain filled with the contents of the src Chain. */ public HashChain(Chain<E> src) { this(src.size()); addAll(src); } // Lazy initialized singleton private static class EmptyIteratorSingleton { static final Iterator<Object> INSTANCE = new Iterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { return null; } @Override public void remove() { // do nothing } }; } protected static <X> Iterator<X> emptyIterator() { @SuppressWarnings("unchecked") Iterator<X> retVal = (Iterator<X>) EmptyIteratorSingleton.INSTANCE; return retVal; } /** Erases the contents of the current HashChain. */ @Override public synchronized void clear() { stateCount++; firstItem = lastItem = null; map.clear(); } @Override public synchronized void swapWith(E out, E in) { insertBefore(in, out); remove(out); } /** Adds the given object to this HashChain. */ @Override public synchronized boolean add(E item) { addLast(item); return true; } /** * Gets all elements in the chain. There is no guarantee on sorting. * * @return All elements in the chain in an unsorted collection */ @Override public synchronized Collection<E> getElementsUnsorted() { return map.keySet(); } /** * Returns an unbacked list containing the contents of the given Chain. * * @deprecated you can use <code>new ArrayList<E>(c)</code> instead */ @Deprecated public static <E> List<E> toList(Chain<E> c) { return new ArrayList<E>(c); } @Override public synchronized boolean follows(E someObject, E someReferenceObject) { Iterator<E> it; try { it = iterator(someReferenceObject); } catch (NoSuchElementException e) { // someReferenceObject not in chain. return false; } while (it.hasNext()) { if (it.next() == someObject) { return true; } } return false; } @Override public synchronized boolean contains(Object o) { return map.containsKey(o); } @Override public synchronized boolean containsAll(Collection<?> c) { for (Object next : c) { if (!(map.containsKey(next))) { return false; } } return true; } @Override public synchronized void insertAfter(E toInsert, E point) { if (toInsert == null) { throw new RuntimeException("Cannot insert a null object into a Chain!"); } if (point == null) { throw new RuntimeException("Insertion point cannot be null!"); } if (map.containsKey(toInsert)) { throw new RuntimeException("Chain already contains object."); } Link<E> temp = map.get(point); if (temp == null) { throw new RuntimeException("Insertion point not found in chain!"); } stateCount++; Link<E> newLink = temp.insertAfter(toInsert); map.put(toInsert, newLink); } @Override public synchronized void insertAfter(Collection<? extends E> toInsert, E point) { if (toInsert == null) { throw new RuntimeException("Cannot insert a null Collection into a Chain!"); } if (point == null) { throw new RuntimeException("Insertion point cannot be null!"); } E previousPoint = point; for (E o : toInsert) { insertAfter(o, previousPoint); previousPoint = o; } } @Override public synchronized void insertAfter(List<E> toInsert, E point) { insertAfter((Collection<E>) toInsert, point); } @Override public synchronized void insertAfter(Chain<E> toInsert, E point) { insertAfter((Collection<E>) toInsert, point); } @Override public synchronized void insertBefore(E toInsert, E point) { if (toInsert == null) { throw new RuntimeException("Cannot insert a null object into a Chain!"); } if (point == null) { throw new RuntimeException("Insertion point cannot be null!"); } if (map.containsKey(toInsert)) { throw new RuntimeException("Chain already contains object."); } Link<E> temp = map.get(point); if (temp == null) { throw new RuntimeException("Insertion point not found in chain!"); } stateCount++; Link<E> newLink = temp.insertBefore(toInsert); map.put(toInsert, newLink); } @Override public synchronized void insertBefore(Collection<? extends E> toInsert, E point) { if (toInsert == null) { throw new RuntimeException("Cannot insert a null Collection into a Chain!"); } if (point == null) { throw new RuntimeException("Insertion point cannot be null!"); } for (E o : toInsert) { insertBefore(o, point); } } @Override public synchronized void insertBefore(List<E> toInsert, E point) { insertBefore((Collection<E>) toInsert, point); } @Override public synchronized void insertBefore(Chain<E> toInsert, E point) { insertBefore((Collection<E>) toInsert, point); } public static <T> HashChain<T> listToHashChain(List<T> list) { HashChain<T> c = new HashChain<T>(); for (T next : list) { c.addLast(next); } return c; } @Override public synchronized boolean remove(Object item) { if (item == null) { throw new RuntimeException("Cannot remove a null object from a Chain!"); } stateCount++; /* * 4th April 2005 Nomair A Naeem map.get(obj) can return null only return true if this is non null else return false */ Link<E> link = map.get(item); if (link != null) { link.unlinkSelf(); map.remove(item); return true; } return false; } @Override public synchronized void addFirst(E item) { if (item == null) { throw new RuntimeException("Cannot insert a null object into a Chain!"); } stateCount++; if (map.containsKey(item)) { throw new RuntimeException("Chain already contains object."); } Link<E> newLink; if (firstItem != null) { Link<E> temp = map.get(firstItem); newLink = temp.insertBefore(item); } else { newLink = new Link<E>(item); firstItem = lastItem = item; } map.put(item, newLink); } @Override public synchronized void addLast(E item) { if (item == null) { throw new RuntimeException("Cannot insert a null object into a Chain!"); } stateCount++; if (map.containsKey(item)) { throw new RuntimeException("Chain already contains object: " + item); } Link<E> newLink; if (lastItem != null) { Link<E> temp = map.get(lastItem); newLink = temp.insertAfter(item); } else { newLink = new Link<E>(item); firstItem = lastItem = item; } map.put(item, newLink); } @Override public synchronized void removeFirst() { stateCount++; E item = firstItem; map.get(item).unlinkSelf(); map.remove(item); } @Override public synchronized void removeLast() { stateCount++; E item = lastItem; map.get(item).unlinkSelf(); map.remove(item); } @Override public synchronized E getFirst() { if (firstItem == null) { throw new NoSuchElementException(); } return firstItem; } @Override public synchronized E getLast() { if (lastItem == null) { throw new NoSuchElementException(); } return lastItem; } @Override public synchronized E getSuccOf(E point) throws NoSuchElementException { Link<E> link = map.get(point); if (link == null) { throw new NoSuchElementException(); } link = link.getNext(); return link == null ? null : link.getItem(); } @Override public synchronized E getPredOf(E point) throws NoSuchElementException { if (point == null) { throw new RuntimeException("Chain cannot contain null objects!"); } Link<E> link = map.get(point); if (link == null) { throw new NoSuchElementException(); } link = link.getPrevious(); return link == null ? null : link.getItem(); } @Override public Iterator<E> snapshotIterator() { if (firstItem == null || isEmpty()) { return emptyIterator(); } else { return (new ArrayList<E>(this)).iterator(); } } public Iterator<E> snapshotIterator(E from) { if (from == null || firstItem == null || isEmpty()) { return emptyIterator(); } else { ArrayList<E> l = new ArrayList<E>(map.size()); for (Iterator<E> it = new LinkIterator<E>(from); it.hasNext();) { E next = it.next(); l.add(next); } return l.iterator(); } } @Override public synchronized Iterator<E> iterator() { if (firstItem == null || isEmpty()) { return emptyIterator(); } else { return new LinkIterator<E>(firstItem); } } @Override public synchronized Iterator<E> iterator(E from) { if (from == null || firstItem == null || isEmpty()) { return emptyIterator(); } else { return new LinkIterator<E>(from); } } /** * <p> * Returns an iterator ranging from <code>head</code> to <code>tail</code>, inclusive. * </p> * * <p> * If <code>tail</code> is the element immediately preceding <code>head</code> in this <code>HashChain</code>, the returned * iterator will iterate 0 times (a special case to allow the specification of an empty range of elements). Otherwise if * <code>tail</code> is not one of the elements following <code>head</code>, the returned iterator will iterate past the * end of the <code>HashChain</code>, provoking a {@link NoSuchElementException}. * </p> * * @throws NoSuchElementException * if <code>head</code> is not an element of the chain. */ @Override public synchronized Iterator<E> iterator(E head, E tail) { if (head == null || firstItem == null || isEmpty()) { return emptyIterator(); } else if (this.getPredOf(head) == tail) { return emptyIterator(); } else { return new LinkIterator<E>(head, tail); } } @Override public synchronized int size() { return map.size(); } /** Returns a textual representation of the contents of this Chain. */ @Override public synchronized String toString() { StringBuilder strBuf = new StringBuilder(); strBuf.append('['); boolean b = false; for (E next : this) { if (!b) { b = true; } else { strBuf.append(", "); } strBuf.append(next.toString()); } strBuf.append(']'); return strBuf.toString(); } @SuppressWarnings("serial") protected class Link<X extends E> implements Serializable { private Link<X> nextLink; private Link<X> previousLink; private X item; public Link(X item) { this.item = item; this.nextLink = null; this.previousLink = null; } public Link<X> getNext() { return nextLink; } public Link<X> getPrevious() { return previousLink; } public void setNext(Link<X> link) { this.nextLink = link; } public void setPrevious(Link<X> link) { this.previousLink = link; } public void unlinkSelf() { bind(previousLink, nextLink); } public Link<X> insertAfter(X item) { Link<X> newLink = new Link<X>(item); bind(newLink, nextLink); bind(this, newLink); return newLink; } public Link<X> insertBefore(X item) { Link<X> newLink = new Link<X>(item); bind(previousLink, newLink); bind(newLink, this); return newLink; } private void bind(Link<X> a, Link<X> b) { if (a == null) { firstItem = (b == null) ? null : b.item; } else { a.nextLink = b; } if (b == null) { lastItem = (a == null) ? null : a.item; } else { b.previousLink = a; } } public X getItem() { return item; } @Override public String toString() { if (item != null) { return item.toString(); } else { return "Link item is null: " + super.toString(); } } } protected class LinkIterator<X extends E> implements Iterator<E> { private final X destination; private Link<E> currentLink; private int iteratorStateCount; // only when this is true can remove() be called (in accordance w/ iterator semantics) private boolean state; public LinkIterator(X from) { this(from, null); } public LinkIterator(X from, X to) { if (from == null) { // NOTE: 'to' is allowed to be 'null' to traverse entire chain throw new RuntimeException("Chain cannot contain null objects!"); } Link<E> nextLink = map.get(from); if (nextLink == null) { throw new NoSuchElementException( "HashChain.LinkIterator(obj) with obj that is not in the chain: " + from.toString()); } this.destination = to; this.currentLink = new Link<E>(null); this.currentLink.setNext(nextLink); this.iteratorStateCount = stateCount; this.state = false; } @Override public boolean hasNext() { if (stateCount != iteratorStateCount) { throw new ConcurrentModificationException(); } if (destination == null) { return (currentLink.getNext() != null); } else { // Ignore whether (currentLink.getNext() == null), so // next() will produce a NoSuchElementException if // destination is not in the chain. return (destination != currentLink.getItem()); } } @Override public E next() throws NoSuchElementException { if (stateCount != iteratorStateCount) { throw new ConcurrentModificationException(); } Link<E> temp = currentLink.getNext(); if (temp == null) { String exceptionMsg; if (destination != null && destination != currentLink.getItem()) { exceptionMsg = "HashChain.LinkIterator.next() reached end of chain without reaching specified tail unit"; } else { exceptionMsg = "HashChain.LinkIterator.next() called past the end of the Chain"; } throw new NoSuchElementException(exceptionMsg); } currentLink = temp; state = true; return currentLink.getItem(); } @Override public void remove() throws IllegalStateException { if (stateCount != iteratorStateCount) { throw new ConcurrentModificationException(); } stateCount++; iteratorStateCount++; if (!state) { throw new IllegalStateException(); } else { currentLink.unlinkSelf(); map.remove(currentLink.getItem()); state = false; } } @Override public String toString() { if (currentLink == null) { return "Current object under iterator is null" + super.toString(); } else { return currentLink.toString(); } } } /** Returns the number of times this chain has been modified. */ @Override public long getModificationCount() { return stateCount; } }
16,968
25.106154
125
java
soot
soot-master/src/main/java/soot/util/HashMultiMap.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * A map with sets as values, HashMap implementation. * * @author Ondrej Lhotak */ public class HashMultiMap<K, V> extends AbstractMultiMap<K, V> { private static final long serialVersionUID = -1928446853508616896L; private static final float DEFAULT_LOAD_FACTOR = 0.7f; protected final Map<K, Set<V>> m; protected final float loadFactor; protected Map<K, Set<V>> createMap() { return createMap(0); } protected Map<K, Set<V>> createMap(int initialSize) { return new HashMap<K, Set<V>>(initialSize, loadFactor); } public HashMultiMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; this.m = createMap(); } public HashMultiMap(int initialSize) { this.loadFactor = DEFAULT_LOAD_FACTOR; this.m = createMap(initialSize); } public HashMultiMap(int initialSize, float loadFactor) { this.loadFactor = loadFactor; this.m = createMap(initialSize); } public HashMultiMap(MultiMap<K, V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; this.m = createMap(); putAll(m); } public HashMultiMap(Map<K, Set<V>> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; this.m = createMap(); putAll(m); } @Override public int numKeys() { return m.size(); } @Override public boolean containsKey(Object key) { return m.containsKey(key); } @Override public boolean containsValue(V value) { for (Set<V> s : m.values()) { if (s.contains(value)) { return true; } } return false; } protected Set<V> newSet() { return new HashSet<V>(4); } private Set<V> findSet(K key) { Set<V> s = m.get(key); if (s == null) { s = newSet(); m.put(key, s); } return s; } @Override public boolean put(K key, V value) { return findSet(key).add(value); } @Override public boolean putAll(K key, Set<V> values) { if (values.isEmpty()) { return false; } return findSet(key).addAll(values); } @Override public boolean remove(K key, V value) { Set<V> s = m.get(key); if (s == null) { return false; } boolean ret = s.remove(value); if (s.isEmpty()) { m.remove(key); } return ret; } @Override public boolean remove(K key) { return null != m.remove(key); } @Override public boolean removeAll(K key, Set<V> values) { Set<V> s = m.get(key); if (s == null) { return false; } boolean ret = s.removeAll(values); if (s.isEmpty()) { m.remove(key); } return ret; } @Override public Set<V> get(K o) { Set<V> ret = m.get(o); return (ret == null) ? Collections.emptySet() : ret; } @Override public Set<K> keySet() { return m.keySet(); } @Override public Set<V> values() { Set<V> ret = new HashSet<V>(m.size()); for (Set<V> s : m.values()) { ret.addAll(s); } return ret; } @Override public boolean equals(Object o) { if (!(o instanceof MultiMap)) { return false; } @SuppressWarnings("unchecked") MultiMap<K, V> mm = (MultiMap<K, V>) o; if (!keySet().equals(mm.keySet())) { return false; } Iterator<Map.Entry<K, Set<V>>> it = m.entrySet().iterator(); while (it.hasNext()) { Map.Entry<K, Set<V>> e = it.next(); Set<V> s = e.getValue(); if (!s.equals(mm.get(e.getKey()))) { return false; } } return true; } @Override public int hashCode() { return m.hashCode(); } @Override public int size() { return m.size(); } @Override public void clear() { m.clear(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Entry<K, Set<V>> entry : m.entrySet()) { builder.append(entry.getKey()).append(":\n").append(entry.getValue().toString()).append("\n\n"); } if (builder.length() > 2) { builder.delete(builder.length() - 2, builder.length()); } return builder.toString(); } }
4,984
20.960352
102
java
soot
soot-master/src/main/java/soot/util/INumberedMap.java
package soot.util; import java.util.Iterator; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Common interface for numbered maps * * @author Steven Arzt * * @param <K> * The common type of the keys * @param <V> * The common type of the values */ public interface INumberedMap<K extends Numberable, V> { /** * Associates a value with a key. * * @param key * The key * @param value * The value * @return True if the association was new, false if the same value was already associated with the given key before */ public boolean put(K key, V value); /** * Returns the value associated with a given key. * * @param key * The key * @return The value associated with the given key */ public V get(K key); /** * Returns an iterator over the keys with non-null values. * * @return The iterator */ public Iterator<K> keyIterator(); /** * Removes the given key from the map * * @param key * The key to be removed */ public void remove(K key); }
1,851
23.693333
118
java
soot
soot-master/src/main/java/soot/util/IdentityHashMultiMap.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; /** * An identity-based version of the MultiMap. * * @author Steven Arzt */ public class IdentityHashMultiMap<K, V> extends HashMultiMap<K, V> { private static final long serialVersionUID = 4960774381646981495L; @Override protected Map<K, Set<V>> createMap(int initialSize) { return new IdentityHashMap<K, Set<V>>(initialSize); } @SuppressWarnings("deprecation") @Override protected Set<V> newSet() { return new IdentityHashSet<V>(); } }
1,366
26.897959
71
java
soot
soot-master/src/main/java/soot/util/IdentityHashSet.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.AbstractSet; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Set; /** * Implements a hashset with comparison over identity. * * @author Eric Bodden * @deprecated can be replaced with * <code>java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<E,Boolean>())</code> */ @Deprecated public class IdentityHashSet<E> extends AbstractSet<E> implements Set<E> { protected IdentityHashMap<E, E> delegate; /** * Creates a new, empty IdentityHashSet. */ public IdentityHashSet() { delegate = new IdentityHashMap<E, E>(); } /** * Creates a new IdentityHashSet containing the same elements as the given collection. * * @param original * The original collection whose elements to inherit */ public IdentityHashSet(Collection<E> original) { delegate = new IdentityHashMap<E, E>(); addAll(original); } /** * {@inheritDoc} */ @Override public int size() { return delegate.size(); } /** * {@inheritDoc} */ @Override public boolean contains(Object o) { return delegate.containsKey(o); } /** * {@inheritDoc} */ @Override public Iterator<E> iterator() { return delegate.keySet().iterator(); } /** * {@inheritDoc} */ @Override public boolean add(E o) { return delegate.put(o, o) == null; } /** * {@inheritDoc} */ @Override public boolean remove(Object o) { return delegate.remove(o) != null; } /** * {@inheritDoc} */ @Override public void clear() { delegate.entrySet().clear(); } /* * Equality based on identity. */ @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((delegate == null) ? 0 : delegate.hashCode()); return result; } /* * Hash code based on identity. */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final IdentityHashSet<?> other = (IdentityHashSet<?>) obj; if (delegate == null) { if (other.delegate != null) { return false; } } else if (!delegate.equals(other.delegate)) { return false; } return true; } /** * {@inheritDoc} */ @Override public String toString() { return delegate.keySet().toString(); } }
3,323
20.584416
107
java
soot
soot-master/src/main/java/soot/util/IntegerNumberer.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A numberer that associates each number with the corresponding Long object. */ public class IntegerNumberer implements Numberer<Long> { /** Tells the numberer that a new object needs to be assigned a number. */ @Override public void add(Long o) { } /** * Should return the number that was assigned to object o that was previously passed as an argument to add(). */ @Override public long get(Long o) { if (o == null) { return 0; } return o.longValue(); } /** Should return the object that was assigned the number number. */ @Override public Long get(long number) { if (number == 0) { return null; } return new Long(number); } /** Should return the number of objects that have been assigned numbers. */ @Override public int size() { throw new RuntimeException("IntegerNumberer does not implement the size() method."); } @Override public boolean remove(Long o) { return false; } }
1,795
26.630769
111
java
soot
soot-master/src/main/java/soot/util/Invalidable.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A class implementing this interface can be invalidated. The invalidation state can be retrieved by other classes. * * @author Marc Miltenberger */ public interface Invalidable { /** * Return true if the object is invalid. * * @return true if the object is invalid. */ public boolean isInvalid(); /** * Invalidates the object. Does nothing if the object is already invalid. */ public void invalidate(); }
1,261
28.348837
116
java
soot
soot-master/src/main/java/soot/util/IterableMap.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Sable Research Group * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; public class IterableMap<K, V> implements Map<K, V> { private final HashMap<K, V> content_map; private final HashMap<V, HashChain<K>> back_map; private final HashChain<K> key_chain; private final HashChain<V> value_chain; private transient Set<K> keySet = null; private transient Set<V> valueSet = null; private transient Collection<V> values = null; public IterableMap() { this(7, 0.7f); } public IterableMap(int initialCapacity) { this(initialCapacity, 0.7f); } public IterableMap(int initialCapacity, float loadFactor) { content_map = new HashMap<K, V>(initialCapacity, loadFactor); back_map = new HashMap<V, HashChain<K>>(initialCapacity, loadFactor); key_chain = new HashChain<K>(); value_chain = new HashChain<V>(); } @Override public void clear() { for (K next : key_chain) { content_map.remove(next); } for (V next : value_chain) { back_map.remove(next); } key_chain.clear(); value_chain.clear(); } public Iterator<K> iterator() { return key_chain.iterator(); } @Override public boolean containsKey(Object key) { return key_chain.contains(key); } @Override public boolean containsValue(Object value) { return value_chain.contains(value); } @Override public Set<Map.Entry<K, V>> entrySet() { return content_map.entrySet(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof IterableMap)) { return false; } IterableMap<?, ?> other = (IterableMap<?, ?>) o; if (!this.key_chain.equals(other.key_chain)) { return false; } // check that the other has our mapping for (K ko : key_chain) { if (other.content_map.get(ko) != this.content_map.get(ko)) { return false; } } return true; } @Override public V get(Object key) { return content_map.get(key); } @Override public int hashCode() { return content_map.hashCode(); } @Override public boolean isEmpty() { return key_chain.isEmpty(); } @Override public Set<K> keySet() { if (keySet == null) { keySet = new AbstractSet<K>() { @Override public Iterator<K> iterator() { return key_chain.iterator(); } @Override public int size() { return key_chain.size(); } @Override public boolean contains(Object o) { return key_chain.contains(o); } @Override public boolean remove(Object o) { if (!key_chain.contains(o)) { return false; } if (IterableMap.this.content_map.get(o) == null) { IterableMap.this.remove(o); return true; } return (IterableMap.this.remove(o) != null); } @Override public void clear() { IterableMap.this.clear(); } }; } return keySet; } public Set<V> valueSet() { if (valueSet == null) { valueSet = new AbstractSet<V>() { @Override public Iterator<V> iterator() { return value_chain.iterator(); } @Override public int size() { return value_chain.size(); } @Override public boolean contains(Object o) { return value_chain.contains(o); } @Override public boolean remove(Object o) { if (value_chain.contains(o) == false) { return false; } HashChain c = (HashChain) IterableMap.this.back_map.get(o); for (Iterator it = c.snapshotIterator(); it.hasNext();) { Object ko = it.next(); if (IterableMap.this.content_map.get(o) == null) { IterableMap.this.remove(ko); } else if (IterableMap.this.remove(ko) == null) { return false; } } return true; } @Override public void clear() { IterableMap.this.clear(); } }; } return valueSet; } @Override public V put(K key, V value) { if (key_chain.contains(key)) { V old_value = content_map.get(key); if (old_value == value) { return value; } HashChain<K> kc = back_map.get(old_value); kc.remove(key); if (kc.isEmpty()) { value_chain.remove(old_value); back_map.remove(old_value); } kc = back_map.get(value); if (kc == null) { kc = new HashChain<K>(); back_map.put(value, kc); value_chain.add(value); } kc.add(key); return old_value; } else { key_chain.add(key); content_map.put(key, value); HashChain<K> kc = back_map.get(value); if (kc == null) { kc = new HashChain<K>(); back_map.put(value, kc); value_chain.add(value); } kc.add(key); return null; } } @Override public void putAll(Map<? extends K, ? extends V> t) { Iterator<? extends K> it; if (t instanceof IterableMap) { it = ((IterableMap<? extends K, ? extends V>) t).key_chain.iterator(); } else { it = t.keySet().iterator(); } while (it.hasNext()) { K key = it.next(); put(key, t.get(key)); } } @Override public V remove(Object key) { if (!key_chain.contains(key)) { return null; } key_chain.remove(key); V value = content_map.remove(key); HashChain<K> c = back_map.get(value); c.remove(key); if (c.isEmpty()) { back_map.remove(value); } return value; } @Override public int size() { return key_chain.size(); } @Override public Collection<V> values() { if (values == null) { values = new AbstractCollection<V>() { @Override public Iterator<V> iterator() { return new Mapping_Iterator<K, V>(IterableMap.this.key_chain, IterableMap.this.content_map); } @Override public int size() { return key_chain.size(); } @Override public boolean contains(Object o) { return value_chain.contains(o); } @Override public void clear() { IterableMap.this.clear(); } }; } return values; } public static class Mapping_Iterator<K, V> implements Iterator<V> { private final Iterator<K> it; private final HashMap<K, V> m; public Mapping_Iterator(HashChain<K> c, HashMap<K, V> m) { this.it = c.iterator(); this.m = m; } @Override public boolean hasNext() { return it.hasNext(); } @Override public V next() throws NoSuchElementException { return m.get(it.next()); } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("You cannot remove from an Iterator on the values() for an IterableMap."); } } }
8,073
22.268012
120
java
soot
soot-master/src/main/java/soot/util/IterableNumberer.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2005 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; /** * A numberer which also supports an iterator on newly-added objects. * * @author xiao, generalize the interface */ public interface IterableNumberer<E> extends Numberer<E>, Iterable<E> { /** Returns an iterator over all objects added to the numberer. */ @Override Iterator<E> iterator(); }
1,151
30.135135
71
java
soot
soot-master/src/main/java/soot/util/IterableSet.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Sable Research Group * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.Set; public class IterableSet<T> extends HashChain<T> implements Set<T> { public IterableSet(Collection<T> c) { super(); addAll(c); } public IterableSet() { super(); } @Override public boolean add(T o) { if (o == null) { throw new IllegalArgumentException("Cannot add \"null\" to an IterableSet."); } if (contains(o)) { return false; } return super.add(o); } @Override public boolean remove(Object o) { if (o == null || !contains(o)) { return false; } return super.remove(o); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (this == o) { return true; } if (!(o instanceof IterableSet)) { return false; } IterableSet<?> other = (IterableSet<?>) o; if (this.size() != other.size()) { return false; } for (T t : this) { if (!other.contains(t)) { return false; } } return true; } @Override public int hashCode() { int code = 23 * size(); for (T t : this) { // use addition here to have hash code independent of order code += t.hashCode(); } return code; } @Override public Object clone() { IterableSet<T> s = new IterableSet<T>(); s.addAll(this); return s; } public boolean isSubsetOf(IterableSet<T> other) { if (other == null) { throw new IllegalArgumentException("Cannot set compare an IterableSet with \"null\"."); } if (this.size() > other.size()) { return false; } for (T t : this) { if (!other.contains(t)) { return false; } } return true; } public boolean isSupersetOf(IterableSet<T> other) { if (other == null) { throw new IllegalArgumentException("Cannot set compare an IterableSet with \"null\"."); } if (this.size() < other.size()) { return false; } for (T t : other) { if (!contains(t)) { return false; } } return true; } public boolean isStrictSubsetOf(IterableSet<T> other) { if (other == null) { throw new IllegalArgumentException("Cannot set compare an IterableSet with \"null\"."); } if (this.size() >= other.size()) { return false; } return isSubsetOf(other); } public boolean isStrictSupersetOf(IterableSet<T> other) { if (other == null) { throw new IllegalArgumentException("Cannot set compare an IterableSet with \"null\"."); } if (this.size() <= other.size()) { return false; } return isSupersetOf(other); } public boolean intersects(IterableSet<T> other) { if (other == null) { throw new IllegalArgumentException("Cannot set intersect an IterableSet with \"null\"."); } if (other.size() < this.size()) { for (T t : other) { if (this.contains(t)) { return true; } } } else { for (T t : this) { if (other.contains(t)) { return true; } } } return false; } public IterableSet<T> intersection(IterableSet<T> other) { if (other == null) { throw new IllegalArgumentException("Cannot set intersect an IterableSet with \"null\"."); } IterableSet<T> c = new IterableSet<T>(); if (other.size() < this.size()) { for (T t : other) { if (this.contains(t)) { c.add(t); } } } else { for (T t : this) { if (other.contains(t)) { c.add(t); } } } return c; } public IterableSet<T> union(IterableSet<T> other) { if (other == null) { throw new IllegalArgumentException("Cannot set union an IterableSet with \"null\"."); } IterableSet<T> c = new IterableSet<T>(); c.addAll(this); c.addAll(other); return c; } @Override public String toString() { StringBuilder b = new StringBuilder(); for (T t : this) { b.append(t.toString()).append('\n'); } return b.toString(); } public UnmodifiableIterableSet<T> asUnmodifiable() { return new UnmodifiableIterableSet<T>(this); } }
5,021
21.723982
95
java