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/util/JasminOutputStream.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.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; /** * An output stream that wraps an existing output stream, and converts Jasmin code written into a class file that gets * written to the original output stream. (Write Jasmin into this stream, and .class will come out.) */ public class JasminOutputStream extends ByteArrayOutputStream { final private OutputStream out; public JasminOutputStream(OutputStream out) { this.out = out; } @Override public void flush() { ByteArrayInputStream bais = new ByteArrayInputStream(this.toByteArray()); jasmin.Main.assemble(bais, out, false); } @Override public void close() throws IOException { this.out.close(); super.close(); } }
1,616
29.509434
118
java
soot
soot-master/src/main/java/soot/util/LargeNumberedMap.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.Iterator; import java.util.NoSuchElementException; /** * A java.util.Map with Numberable objects as the keys. This one is designed for maps close to the size of the universe. For * smaller maps, use SmallNumberedMap. * * @author Ondrej Lhotak */ public final class LargeNumberedMap<K extends Numberable, V> implements INumberedMap<K, V> { private final IterableNumberer<K> universe; private V[] values; public LargeNumberedMap(IterableNumberer<K> universe) { this.universe = universe; int size = universe.size(); this.values = newArray(size < 8 ? 8 : size); } @SuppressWarnings("unchecked") private static <T> T[] newArray(int size) { return (T[]) new Object[size]; } @Override public boolean put(K key, V value) { int number = key.getNumber(); if (number == 0) { throw new RuntimeException(String.format("oops, forgot to initialize. Object is of type %s, and looks like this: %s", key.getClass().getName(), key.toString())); } if (number >= values.length) { Object[] oldValues = values; values = newArray(Math.max(universe.size() * 2, number) + 5); System.arraycopy(oldValues, 0, values, 0, oldValues.length); } boolean ret = (values[number] != value); values[number] = value; return ret; } @Override public V get(K key) { int i = key.getNumber(); if (i >= values.length) { return null; } return values[i]; } @Override public void remove(K key) { int i = key.getNumber(); if (i < values.length) { values[i] = null; } } @Override public Iterator<K> keyIterator() { return new Iterator<K>() { int cur = 0; private void advance() { while (cur < values.length && values[cur] == null) { cur++; } } @Override public boolean hasNext() { advance(); return cur < values.length; } @Override public K next() { if (!hasNext()) { throw new NoSuchElementException(); } return universe.get(cur++); } @Override public void remove() { values[cur - 1] = null; } }; } }
3,028
25.112069
124
java
soot
soot-master/src/main/java/soot/util/LargePriorityQueue.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.BitSet; import java.util.Iterator; import java.util.List; import java.util.Map; // QND class LargePriorityQueue<E> extends PriorityQueue<E> { private final BitSet queue; private long modCount = 0; LargePriorityQueue(List<? extends E> universe, Map<E, Integer> ordinalMap) { super(universe, ordinalMap); queue = new BitSet(N); } @Override boolean add(int ordinal) { if (contains(ordinal)) { return false; } queue.set(ordinal); min = Math.min(min, ordinal); modCount++; return true; } @Override void addAll() { queue.set(0, N); min = 0; modCount++; } @Override int nextSetBit(int fromIndex) { int i = queue.nextSetBit(fromIndex); return (i < 0) ? Integer.MAX_VALUE : i; } @Override boolean remove(int ordinal) { if (!contains(ordinal)) { return false; } queue.clear(ordinal); if (min == ordinal) { min = nextSetBit(min + 1); } modCount++; return true; } @Override boolean contains(int ordinal) { return queue.get(ordinal); } @Override public Iterator<E> iterator() { return new Itr() { @Override long getExpected() { return modCount; } }; } @Override public int size() { return queue.cardinality(); } }
2,158
20.59
78
java
soot
soot-master/src/main/java/soot/util/LocalBitSetPacker.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 soot.Body; import soot.Local; /** * Class for packing local numbers such that bit sets can easily be used to reference locals in bodies * * @author Steven Arzt * */ public class LocalBitSetPacker { private final Body body; private Local[] locals; private int[] oldNumbers; public LocalBitSetPacker(Body body) { this.body = body; } /** * Reassigns the local numbers such that a dense bit set can be created over them */ public void pack() { int n = body.getLocalCount(); locals = new Local[n]; oldNumbers = new int[n]; n = 0; for (Local local : body.getLocals()) { locals[n] = local; oldNumbers[n] = local.getNumber(); local.setNumber(n++); } } /** * Restores the original local numbering */ public void unpack() { for (int i = 0; i < locals.length; i++) { locals[i].setNumber(oldNumbers[i]); } locals = null; oldNumbers = null; } public int getLocalCount() { return locals == null ? 0 : locals.length; } }
1,875
23.684211
102
java
soot
soot-master/src/main/java/soot/util/MapNumberer.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.ArrayList; import java.util.HashMap; import java.util.Map; public class MapNumberer<T> implements Numberer<T> { final Map<T, Integer> map = new HashMap<T, Integer>(); final ArrayList<T> al = new ArrayList<T>(); int nextIndex = 1; public MapNumberer() { al.add(null); } @Override public void add(T o) { if (!map.containsKey(o)) { map.put(o, nextIndex); al.add(o); nextIndex++; } } @Override public T get(long number) { return al.get((int) number); } @Override public long get(Object o) { if (o == null) { return 0; } Integer i = map.get(o); if (i == null) { throw new RuntimeException("couldn't find " + o); } return i; } @Override public int size() { /* subtract 1 for null */ return nextIndex - 1; } public boolean contains(Object o) { return map.containsKey(o); } @Override public boolean remove(T o) { Integer i = map.remove(o); if (i == null) { return false; } else { al.set(i, null); return true; } } }
1,912
21.244186
71
java
soot
soot-master/src/main/java/soot/util/MediumPriorityQueue.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 static java.lang.Long.numberOfTrailingZeros; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @author Steven Lambeth * */ class MediumPriorityQueue<E> extends PriorityQueue<E> { final static int MAX_CAPACITY = Long.SIZE * Long.SIZE; private final long[] data; private int size = 0; private long modCount = 0; private long lookup = 0; MediumPriorityQueue(List<? extends E> universe, Map<E, Integer> ordinalMap) { super(universe, ordinalMap); data = new long[(N + Long.SIZE - 1) >>> 6]; assert N > SmallPriorityQueue.MAX_CAPACITY; assert N <= MAX_CAPACITY; } @Override void addAll() { size = N; Arrays.fill(data, -1); data[data.length - 1] = -1L >>> -size; lookup = -1L >>> -data.length; min = 0; modCount++; } @Override public void clear() { size = 0; Arrays.fill(data, 0); lookup = 0; min = Integer.MAX_VALUE; modCount++; } @Override int nextSetBit(int fromIndex) { assert fromIndex >= 0; for (int bb = fromIndex >>> 6; fromIndex < N;) { // remove everything from t1 that is less than "fromIndex", long m1 = -1L << fromIndex; // t1 contains now all active bits long t1 = data[bb] & m1; // the expected index m1 in t1 is set (optional test if NOTZ is // expensive) if ((t1 & -m1) != 0) { return fromIndex; } // some bits are left in t1, so we can finish if (t1 != 0) { return (bb << 6) + numberOfTrailingZeros(t1); } // we know the previous block is empty, so we start our lookup on // the next one long m0 = -1L << ++bb; long t0 = lookup & m0; // find next used block if ((t0 & -m0) == 0) { bb = numberOfTrailingZeros(t0); } // re-assign new search index fromIndex = bb << 6; // next and last round } return fromIndex; } @Override boolean add(int ordinal) { int bucket = ordinal >>> 6; long prv = data[bucket]; long now = prv | (1L << ordinal); if (prv == now) { return false; } data[bucket] = now; lookup |= (1L << bucket); size++; modCount++; min = Math.min(min, ordinal); return true; } @Override boolean contains(int ordinal) { assert ordinal >= 0; assert ordinal < N; return ((data[ordinal >>> 6] >>> ordinal) & 1L) == 1L; } @Override boolean remove(int index) { assert index >= 0; assert index < N; int bucket = index >>> 6; long old = data[bucket]; long now = old & ~(1L << index); if (old == now) { return false; } if (0 == now) { lookup &= ~(1L << bucket); } size--; modCount++; data[bucket] = now; if (min == index) { min = nextSetBit(min + 1); } return true; } @Override public Iterator<E> iterator() { return new Itr() { @Override long getExpected() { return modCount; } }; } @Override public int size() { return size; } }
3,940
21.140449
79
java
soot
soot-master/src/main/java/soot/util/MultiMap.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 heros.solver.Pair; import java.util.Map; import java.util.Set; /** * A map with sets as values. * * @author Ondrej Lhotak */ public interface MultiMap<K, V> extends Iterable<Pair<K, V>> { public boolean isEmpty(); public int numKeys(); public boolean contains(K key, V value); public boolean containsKey(K key); public boolean containsValue(V value); public boolean put(K key, V value); public boolean putAll(K key, Set<V> values); public boolean putAll(Map<K, Set<V>> m); public boolean putMap(Map<K, V> m); public boolean putAll(MultiMap<K, V> m); public boolean remove(K key, V value); public boolean remove(K key); public boolean removeAll(K key, Set<V> values); public Set<V> get(K o); public Set<K> keySet(); public Set<V> values(); /** * Gets the number of keys in this MultiMap * * @return The number of keys in this MultiMap */ public int size(); public void clear(); }
1,778
22.103896
71
java
soot
soot-master/src/main/java/soot/util/Numberable.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% */ /** * A class that numbers objects, so they can be placed in bitsets. * * @author Ondrej Lhotak */ public interface Numberable { public void setNumber(int number); public int getNumber(); }
1,018
27.305556
71
java
soot
soot-master/src/main/java/soot/util/NumberedSet.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.Iterator; /** * Holds a set of Numberable objects. * * @author Ondrej Lhotak */ public final class NumberedSet<N extends Numberable> { private final IterableNumberer<N> universe; private Numberable[] array = new Numberable[8]; private BitVector bits; private int size = 0; public NumberedSet(IterableNumberer<N> universe) { this.universe = universe; } public boolean add(Numberable o) { if (array != null) { int pos = findPosition(o); if (array[pos] == o) { return false; } size++; if (size * 3 > array.length * 2) { doubleSize(); if (array != null) { pos = findPosition(o); } else { int number = o.getNumber(); if (number == 0) { throw new RuntimeException("unnumbered"); } return bits.set(number); } } array[pos] = o; return true; } else { int number = o.getNumber(); if (number == 0) { throw new RuntimeException("unnumbered"); } if (bits.set(number)) { size++; return true; } else { return false; } } } public boolean contains(Numberable o) { if (array != null) { return array[findPosition(o)] != null; } else { int number = o.getNumber(); if (number == 0) { throw new RuntimeException("unnumbered"); } return bits.get(number); } } private int findPosition(Numberable o) { int number = o.getNumber(); if (number == 0) { throw new RuntimeException("unnumbered"); } number = number & (array.length - 1); while (true) { Numberable temp = array[number]; if (temp == o || temp == null) { return number; } number = (number + 1) & (array.length - 1); } } private void doubleSize() { int uniSize = universe.size(); if (array.length * 128 > uniSize) { bits = new BitVector(uniSize); Numberable[] oldArray = array; array = null; for (Numberable element : oldArray) { if (element != null) { bits.set(element.getNumber()); } } } else { Numberable[] oldArray = array; array = new Numberable[array.length * 2]; for (Numberable element : oldArray) { if (element != null) { array[findPosition(element)] = element; } } } } public final int size() { return size; } public Iterator<N> iterator() { if (array == null) { return new BitSetIterator(); } else { return new NumberedSetIterator(); } } private class BitSetIterator implements Iterator<N> { private final soot.util.BitSetIterator iter; BitSetIterator() { iter = NumberedSet.this.bits.iterator(); } @Override public final boolean hasNext() { return iter.hasNext(); } @Override public final N next() { return NumberedSet.this.universe.get(iter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } } private class NumberedSetIterator implements Iterator<N> { private int cur = 0; NumberedSetIterator() { seekNext(); } protected final void seekNext() { Numberable[] temp = NumberedSet.this.array; try { while (temp[cur] == null) { cur++; } } catch (ArrayIndexOutOfBoundsException e) { cur = -1; } } @Override public final boolean hasNext() { return cur != -1; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public final N next() { @SuppressWarnings("unchecked") N ret = (N) NumberedSet.this.array[cur]; cur++; seekNext(); return ret; } } }
4,691
22.46
71
java
soot
soot-master/src/main/java/soot/util/NumberedString.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% */ /** * A class that assigns integers to java.lang.Strings. * * @author Ondrej Lhotak */ public final class NumberedString implements Numberable { private final String s; private volatile int number; public NumberedString(String s) { this.s = s; } @Override public final void setNumber(int number) { this.number = number; } @Override public final int getNumber() { return number; } @Override public final String toString() { return getString(); } public final String getString() { if (number == 0) { throw new RuntimeException("oops"); } return s; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + number; result = prime * result + ((s == null) ? 0 : s.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } NumberedString other = (NumberedString) obj; if (this.number != other.number) { return false; } if (this.s == null) { return other.s == null; } else { return this.s.equals(other.s); } } }
2,067
22.235955
71
java
soot
soot-master/src/main/java/soot/util/Numberer.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 numberer converts objects to unique non-negative integers, and vice-versa. * * @author xiao, generalize the interface */ public interface Numberer<E> { /** Tells the numberer that a new object needs to be assigned a number. */ public void add(E o); /** * Removes the number for a given object. * * @param o * the element * @return true if the removal was successful, false when not */ public boolean remove(E o); /** * Should return the number that was assigned to object o that was previously passed as an argument to add(). */ public long get(E o); /** Should return the object that was assigned the number number. */ public E get(long number); /** Should return the number of objects that have been assigned numbers. */ public int size(); }
1,633
29.259259
111
java
soot
soot-master/src/main/java/soot/util/PhaseDumper.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 John Jorgensen * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.G; import soot.Printer; import soot.Scene; import soot.Singletons; import soot.SootClass; import soot.SootMethod; import soot.options.Options; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.ExceptionalGraph; import soot.util.cfgcmd.CFGToDotGraph; import soot.util.dot.DotGraph; /** * The <tt>PhaseDumper</tt> is a debugging aid. It maintains two lists of phases to be debugged. If a phase is on the * <code>bodyDumpingPhases</code> list, then the intermediate representation of the bodies being manipulated by the phase is * dumped before and after the phase is applied. If a phase is on the <code>cfgDumpingPhases</code> list, then whenever a CFG * is constructed during the phase, a dot file is dumped representing the CFG constructed. */ public class PhaseDumper { private static final Logger logger = LoggerFactory.getLogger(PhaseDumper.class); private static final String ALL_WILDCARD = "ALL"; private final PhaseStack phaseStack = new PhaseStack(); // As a minor optimization, we leave these lists null in the case were // no phases at all are to be dumped, which is the most likely case. private List<String> bodyDumpingPhases = null; private List<String> cfgDumpingPhases = null; // soot.Printer itself needs to create a BriefUnitGraph in order // to format the text for a method's instructions, so this flag is // a hack to avoid dumping graphs that we create in the course of // dumping bodies or other graphs. // // Note that this hack would not work if a PhaseDumper might be // accessed by multiple threads. So long as there is a single // active PhaseDumper accessed through soot.G, it seems // safe to assume it will be accessed by only a single thread. private boolean alreadyDumping = false; private class PhaseStack extends ArrayList<String> { // We eschew java.util.Stack to avoid synchronization overhead. private static final int initialCapacity = 4; private static final String EMPTY_STACK_PHASE_NAME = "NOPHASE"; PhaseStack() { super(initialCapacity); } String currentPhase() { if (this.isEmpty()) { return EMPTY_STACK_PHASE_NAME; } else { return this.get(this.size() - 1); } } String pop() { return this.remove(this.size() - 1); } String push(String phaseName) { this.add(phaseName); return phaseName; } } public PhaseDumper(Singletons.Global g) { List<String> bodyPhases = Options.v().dump_body(); if (!bodyPhases.isEmpty()) { bodyDumpingPhases = bodyPhases; } List<String> cfgPhases = Options.v().dump_cfg(); if (!cfgPhases.isEmpty()) { cfgDumpingPhases = cfgPhases; } } /** * Returns the single instance of <code>PhaseDumper</code>. * * @return Soot's <code>PhaseDumper</code>. */ public static PhaseDumper v() { return G.v().soot_util_PhaseDumper(); } private boolean isBodyDumpingPhase(String phaseName) { return ((bodyDumpingPhases != null) && (bodyDumpingPhases.contains(phaseName) || bodyDumpingPhases.contains(ALL_WILDCARD))); } private boolean isCFGDumpingPhase(String phaseName) { if (cfgDumpingPhases == null) { return false; } if (cfgDumpingPhases.contains(ALL_WILDCARD)) { return true; } else { while (true) { // loop exited by "return" or "break". if (cfgDumpingPhases.contains(phaseName)) { return true; } // Go on to check if phaseName is a subphase of a // phase in cfgDumpingPhases. int lastDot = phaseName.lastIndexOf('.'); if (lastDot < 0) { break; } else { phaseName = phaseName.substring(0, lastDot); } } return false; } } private static File makeDirectoryIfMissing(Body b) throws IOException { StringBuilder buf = new StringBuilder(soot.SourceLocator.v().getOutputDir()); buf.append(File.separatorChar); buf.append(b.getMethod().getDeclaringClass().getName()); buf.append(File.separatorChar); buf.append(b.getMethod().getSubSignature().replace('<', '[').replace('>', ']')); File dir = new File(buf.toString()); if (dir.exists()) { if (!dir.isDirectory()) { throw new IOException(dir.getPath() + " exists but is not a directory."); } } else { if (!dir.mkdirs()) { throw new IOException("Unable to mkdirs " + dir.getPath()); } } return dir; } private static PrintWriter openBodyFile(Body b, String baseName) throws IOException { File dir = makeDirectoryIfMissing(b); String filePath = dir.toString() + File.separatorChar + baseName; return new PrintWriter(new java.io.FileOutputStream(filePath)); } /** * Returns the next available name for a graph file. */ private static String nextGraphFileName(Body b, String baseName) throws IOException { // We number output files to allow multiple graphs per phase. File dir = makeDirectoryIfMissing(b); final String prefix = dir.toString() + File.separatorChar + baseName; File file = null; int fileNumber = 0; do { file = new File(prefix + fileNumber + DotGraph.DOT_EXTENSION); fileNumber++; } while (file.exists()); return file.toString(); } private static void deleteOldGraphFiles(final Body b, final String phaseName) { try { final File dir = makeDirectoryIfMissing(b); final File[] toDelete = dir.listFiles(new java.io.FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(phaseName) && name.endsWith(DotGraph.DOT_EXTENSION); } }); if (toDelete != null) { for (File element : toDelete) { element.delete(); } } } catch (IOException e) { // Don't abort execution because of an I/O error, but report the error. logger.debug("PhaseDumper.dumpBody() caught: " + e.toString()); logger.error(e.getMessage(), e); } } public void dumpBody(Body b, String baseName) { final Printer printer = Printer.v(); alreadyDumping = true; try (PrintWriter out = openBodyFile(b, baseName)) { printer.setOption(Printer.USE_ABBREVIATIONS); printer.printTo(b, out); } catch (IOException e) { // Don't abort execution because of an I/O error, but let // the user know. logger.debug("PhaseDumper.dumpBody() caught: " + e.toString()); logger.error(e.getMessage(), e); } finally { alreadyDumping = false; } } private void dumpAllBodies(String baseName, boolean deleteGraphFiles) { for (SootClass cls : Scene.v().getClasses(SootClass.BODIES)) { for (SootMethod method : cls.getMethods()) { if (method.hasActiveBody()) { Body body = method.getActiveBody(); if (deleteGraphFiles) { deleteOldGraphFiles(body, baseName); } dumpBody(body, baseName); } } } } /** * Tells the <code>PhaseDumper</code> that a {@link Body} transforming phase has started, so that it can dump the phases's * &ldquo;before&rdquo; file. If the phase is to be dumped, <code>dumpBefore</code> deletes any old graph files dumped * during previous runs of the phase. * * @param b * the {@link Body} being transformed. * @param phaseName * the name of the phase that has just started. */ public void dumpBefore(Body b, String phaseName) { phaseStack.push(phaseName); if (isBodyDumpingPhase(phaseName)) { deleteOldGraphFiles(b, phaseName); dumpBody(b, phaseName + ".in"); } } /** * Tells the <code>PhaseDumper</code> that a {@link Body} transforming phase has ended, so that it can dump the phases's * &ldquo;after&rdquo; file. * * @param b * the {@link Body} being transformed. * * @param phaseName * the name of the phase that has just ended. * * @throws IllegalArgumentException * if <code>phaseName</code> does not match the <code>PhaseDumper</code>'s record of the current phase. */ public void dumpAfter(Body b, String phaseName) { String poppedPhaseName = phaseStack.pop(); if (poppedPhaseName != phaseName) { throw new IllegalArgumentException("dumpAfter(" + phaseName + ") when poppedPhaseName == " + poppedPhaseName); } if (isBodyDumpingPhase(phaseName)) { dumpBody(b, phaseName + ".out"); } } /** * Tells the <code>PhaseDumper</code> that a {@link Scene} transforming phase has started, so that it can dump the phases's * &ldquo;before&rdquo; files. If the phase is to be dumped, <code>dumpBefore</code> deletes any old graph files dumped * during previous runs of the phase. * * @param phaseName * the name of the phase that has just started. */ public void dumpBefore(String phaseName) { phaseStack.push(phaseName); if (isBodyDumpingPhase(phaseName)) { dumpAllBodies(phaseName + ".in", true); } } /** * Tells the <code>PhaseDumper</code> that a {@link Scene} transforming phase has ended, so that it can dump the phases's * &ldquo;after&rdquo; files. * * @param phaseName * the name of the phase that has just ended. * * @throws IllegalArgumentException * if <code>phaseName</code> does not match the <code>PhaseDumper</code>'s record of the current phase. */ public void dumpAfter(String phaseName) { String poppedPhaseName = phaseStack.pop(); if (poppedPhaseName != phaseName) { throw new IllegalArgumentException("dumpAfter(" + phaseName + ") when poppedPhaseName == " + poppedPhaseName); } if (isBodyDumpingPhase(phaseName)) { dumpAllBodies(phaseName + ".out", false); } } /** * Asks the <code>PhaseDumper</code> to dump the passed {@link DirectedGraph} if the current phase is being dumped. * * @param g * the graph to dump. * @param b * the {@link Body} represented by <code>g</code>. */ public <N> void dumpGraph(DirectedGraph<N> g, Body b) { dumpGraph(g, b, false); } /** * Asks the <code>PhaseDumper</code> to dump the passed {@link DirectedGraph} if the current phase is being dumped or * {@code skipPhaseCheck == true}. * * @param g * the graph to dump. * @param b * the {@link Body} represented by <code>g</code>. * @param skipPhaseCheck */ public <N> void dumpGraph(DirectedGraph<N> g, Body b, boolean skipPhaseCheck) { if (!alreadyDumping) { try { alreadyDumping = true; String phaseName = phaseStack.currentPhase(); if (skipPhaseCheck || isCFGDumpingPhase(phaseName)) { try { String outputFile = nextGraphFileName(b, phaseName + '-' + getClassIdent(g) + '-'); CFGToDotGraph drawer = new CFGToDotGraph(); drawer.drawCFG(g, b).plot(outputFile); } catch (IOException e) { // Don't abort execution because of an I/O error, but // report the error. logger.debug("PhaseDumper.dumpBody() caught: " + e.toString()); logger.error(e.getMessage(), e); } } } finally { alreadyDumping = false; } } } /** * Asks the <code>PhaseDumper</code> to dump the passed {@link ExceptionalGraph} if the current phase is being dumped. * * @param g * the graph to dump. */ public <N> void dumpGraph(ExceptionalGraph<N> g) { dumpGraph(g, false); } /** * Asks the <code>PhaseDumper</code> to dump the passed {@link ExceptionalGraph} if the current phase is being dumped or * {@code skipPhaseCheck == true}. * * @param g * the graph to dump. * @param skipPhaseCheck */ public <N> void dumpGraph(ExceptionalGraph<N> g, boolean skipPhaseCheck) { if (!alreadyDumping) { try { alreadyDumping = true; String phaseName = phaseStack.currentPhase(); if (skipPhaseCheck || isCFGDumpingPhase(phaseName)) { try { String outputFile = nextGraphFileName(g.getBody(), phaseName + '-' + getClassIdent(g) + '-'); CFGToDotGraph drawer = new CFGToDotGraph(); drawer.setShowExceptions(Options.v().show_exception_dests()); drawer.drawCFG(g).plot(outputFile); } catch (IOException e) { // Don't abort execution because of an I/O error, but // report the error. logger.debug("PhaseDumper.dumpBody() caught: " + e.toString()); logger.error(e.getMessage(), e); } } } finally { alreadyDumping = false; } } } /** * A utility routine that returns the unqualified identifier naming the class of an object. * * @param obj * The object whose class name is to be returned. */ private String getClassIdent(Object obj) { String qualifiedName = obj.getClass().getName(); return qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1); } /** * Prints the current stack trace, as a brute force tool for program understanding. This method appeared in response to the * many times dumpGraph() was being called while the phase stack was empty. Turned out that the Printer needs to build a * BriefUnitGraph in order to print a graph. Doh! */ public void printCurrentStackTrace() { IOException e = new IOException("FAKE"); logger.error(e.getMessage(), e); } }
14,614
33.067599
125
java
soot
soot-master/src/main/java/soot/util/PriorityQueue.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.AbstractMap; import java.util.AbstractQueue; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A fixed size priority queue based on bitsets. The elements of the priority queue are ordered according to a given * universe. This priority queue does not permit {@code null} elements. Inserting of elements that are not part of the * universe is also permitted (doing so will result in a {@code NoSuchElementException}). * * @author Steven Lambeth * @param <E> * the type of elements held in the universe */ public abstract class PriorityQueue<E> extends AbstractQueue<E> { private static final Logger logger = LoggerFactory.getLogger(PriorityQueue.class); private final List<? extends E> universe; private final Map<E, Integer> ordinalMap; final int N; int min = Integer.MAX_VALUE; PriorityQueue(List<? extends E> universe, Map<E, Integer> ordinalMap) { assert ordinalMap.size() == universe.size(); this.universe = universe; this.ordinalMap = ordinalMap; this.N = universe.size(); } abstract class Itr implements Iterator<E> { long expected = getExpected(); int next = min; int now = Integer.MAX_VALUE; abstract long getExpected(); @Override public boolean hasNext() { return next < N; } @Override public E next() { if (expected != getExpected()) { throw new ConcurrentModificationException(); } if (next >= N) { throw new NoSuchElementException(); } now = next; next = nextSetBit(next + 1); return universe.get(now); } @Override public void remove() { if (now >= N) { throw new IllegalStateException(); } if (expected != getExpected()) { throw new ConcurrentModificationException(); } PriorityQueue.this.remove(now); expected = getExpected(); now = Integer.MAX_VALUE; } } int getOrdinal(Object o) { if (o == null) { throw new NullPointerException(); } Integer i = ordinalMap.get(o); if (i == null) { throw new NoSuchElementException(); } return i; } /** * Adds all elements of the universe to this queue. */ abstract void addAll(); /** * Returns the index of the first bit that is set to <code>true</code> that occurs on or after the specified starting * index. If no such bit exists then a value bigger that {@code N} is returned. * * @param fromIndex * the index to start checking from (inclusive). * @return the index of the next set bit. */ abstract int nextSetBit(int fromIndex); abstract boolean remove(int ordinal); abstract boolean add(int ordinal); abstract boolean contains(int ordinal); /** * {@inheritDoc} * */ @Override final public E peek() { return isEmpty() ? null : universe.get(min); } /** * {@inheritDoc} * */ @Override final public E poll() { if (isEmpty()) { return null; } E e = universe.get(min); remove(min); return e; } /** * {@inheritDoc} * * @throws NoSuchElementException * if e not part of the universe * @throws NullPointerException * if e is {@code null} */ @Override final public boolean add(E e) { return offer(e); } /** * {@inheritDoc} * * @throws NoSuchElementException * if e not part of the universe * @throws NullPointerException * if e is {@code null} */ @Override final public boolean offer(E e) { return add(getOrdinal(e)); } /** * {@inheritDoc} * */ @Override final public boolean remove(Object o) { if (o == null || isEmpty()) { return false; } try { if (o.equals(peek())) { remove(min); return true; } else { return remove(getOrdinal(o)); } } catch (NoSuchElementException e) { logger.debug(e.getMessage()); return false; } } /** * {@inheritDoc} * */ @Override final public boolean contains(Object o) { if (o == null) { return false; } try { if (o.equals(peek())) { return true; } else { return contains(getOrdinal(o)); } } catch (NoSuchElementException e) { logger.debug(e.getMessage()); return false; } } /** * {@inheritDoc} * */ @Override public boolean isEmpty() { return min >= N; } /** * Creates a new full priority queue * * @param <E> * @param universe * @return */ public static <E> PriorityQueue<E> of(E[] universe) { return of(Arrays.asList(universe)); } /** * Creates a new empty priority queue * * @param <E> * @param universe * @return */ public static <E> PriorityQueue<E> noneOf(E[] universe) { return noneOf(Arrays.asList(universe)); } /** * Creates a new full priority queue * * @param <E> * @param universe * @return */ public static <E> PriorityQueue<E> of(List<? extends E> universe) { PriorityQueue<E> q = noneOf(universe); q.addAll(); return q; } /** * Creates a new empty priority queue * * @param <E> * @param universe * @return */ public static <E> PriorityQueue<E> noneOf(List<? extends E> universe) { Map<E, Integer> ordinalMap = new HashMap<E, Integer>(2 * universe.size() / 3); int i = 0; for (E e : universe) { if (e == null) { throw new NullPointerException("null is not allowed"); } if (ordinalMap.put(e, i++) != null) { throw new IllegalArgumentException("duplicate key found"); } } return newPriorityQueue(universe, ordinalMap); } public static <E extends Numberable> PriorityQueue<E> of(List<? extends E> universe, boolean useNumberInterface) { PriorityQueue<E> q = noneOf(universe, useNumberInterface); q.addAll(); return q; } public static <E extends Numberable> PriorityQueue<E> noneOf(final List<? extends E> universe, boolean useNumberInterface) { if (!useNumberInterface) { return noneOf(universe); } int i = 0; for (E e : universe) { e.setNumber(i++); } return newPriorityQueue(universe, new AbstractMap<E, Integer>() { @SuppressWarnings("unchecked") @Override public Integer get(Object key) { return ((E) key).getNumber(); } @Override public int size() { return universe.size(); } @Override public Set<java.util.Map.Entry<E, Integer>> entrySet() { throw new UnsupportedOperationException(); } }); } private static <E> PriorityQueue<E> newPriorityQueue(List<? extends E> universe, Map<E, Integer> ordinalMap) { final int universeSize = universe.size(); if (universeSize <= SmallPriorityQueue.MAX_CAPACITY) { return new SmallPriorityQueue<E>(universe, ordinalMap); } else if (universeSize <= MediumPriorityQueue.MAX_CAPACITY) { return new MediumPriorityQueue<E>(universe, ordinalMap); } else { return new LargePriorityQueue<E>(universe, ordinalMap); } } }
8,249
23.052478
119
java
soot
soot-master/src/main/java/soot/util/SharedBitSet.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% */ public final class SharedBitSet { BitVector value; boolean own = true; public SharedBitSet(int i) { this.value = new BitVector(i); } public SharedBitSet() { this(32); } private void acquire() { if (own) { return; } own = true; value = (BitVector) value.clone(); } private void canonicalize() { value = SharedBitSetCache.v().canonicalize(value); own = false; } public boolean set(int bit) { acquire(); return value.set(bit); } public void clear(int bit) { acquire(); value.clear(bit); } public boolean get(int bit) { return value.get(bit); } public void and(SharedBitSet other) { if (own) { value.and(other.value); } else { value = BitVector.and(value, other.value); own = true; } canonicalize(); } public void or(SharedBitSet other) { if (own) { value.or(other.value); } else { value = BitVector.or(value, other.value); own = true; } canonicalize(); } public boolean orAndAndNot(SharedBitSet orset, SharedBitSet andset, SharedBitSet andnotset) { acquire(); boolean ret = value.orAndAndNot(orset.value, andset.value, andnotset.value); canonicalize(); return ret; } public boolean orAndAndNot(SharedBitSet orset, BitVector andset, SharedBitSet andnotset) { acquire(); boolean ret = value.orAndAndNot(orset.value, andset, andnotset == null ? null : andnotset.value); canonicalize(); return ret; } public BitSetIterator iterator() { return value.iterator(); } @Override public String toString() { StringBuilder b = new StringBuilder(); for (BitSetIterator it = iterator(); it.hasNext();) { int next = it.next(); b.append(next); if (it.hasNext()) { b.append(','); } } return b.toString(); } }
2,687
22.373913
101
java
soot
soot-master/src/main/java/soot/util/SharedBitSetCache.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% */ import soot.G; import soot.Singletons; public final class SharedBitSetCache { public SharedBitSetCache(Singletons.Global g) { } public static SharedBitSetCache v() { return G.v().soot_util_SharedBitSetCache(); } public static final int size = 32749; // a nice prime about 32k public BitVector[] cache = new BitVector[size]; public BitVector[] orAndAndNotCache = new BitVector[size]; public BitVector canonicalize(BitVector set) { int hash = set.hashCode(); if (hash < 0) { hash = -hash; } hash %= size; BitVector hashed = cache[hash]; if (hashed != null && hashed.equals(set)) { return hashed; } else { cache[hash] = set; return set; } } }
1,541
26.535714
71
java
soot
soot-master/src/main/java/soot/util/SingletonList.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% */ /** * A list containing exactly one object, immutable. * * @author Ondrej Lhotak */ @Deprecated public class SingletonList<E> extends java.util.AbstractList<E> { private E o; public SingletonList(E o) { this.o = o; } @Override public int size() { return 1; } @Override public boolean contains(Object other) { return other.equals(o); } @Override public E get(int index) { if (index != 0) { throw new IndexOutOfBoundsException("Singleton list; index = " + index); } return o; } }
1,358
23.267857
78
java
soot
soot-master/src/main/java/soot/util/SmallNumberedMap.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.lang.reflect.Array; import java.util.Iterator; /** * A java.util.Map with Numberable objects as the keys. * * @author Ondrej Lhotak */ public final class SmallNumberedMap<K extends Numberable, V> implements INumberedMap<K, V> { private K[] array = newArray(Numberable.class, 8); private V[] values = newArray(Object.class, 8); private int size = 0; public SmallNumberedMap() { } @SuppressWarnings("unchecked") private static <T> T[] newArray(Class<? super T> componentType, int length) { return (T[]) Array.newInstance(componentType, length); } @Override public boolean put(K key, V value) { int pos = findPosition(key); if (array[pos] == key) { if (values[pos] == value) { return false; } values[pos] = value; return true; } size++; if (size * 3 > array.length * 2) { doubleSize(); pos = findPosition(key); } array[pos] = key; values[pos] = value; return true; } @Override public V get(K key) { return values[findPosition(key)]; } @Override public void remove(K key) { int pos = findPosition(key); if (array[pos] == key) { array[pos] = null; values[pos] = null; size--; } } /** * Returns the number of non-null values in this map. */ public int nonNullSize() { int ret = 0; for (V element : values) { if (element != null) { ret++; } } return ret; } @Override public Iterator<K> keyIterator() { return new SmallNumberedMapIterator<K>(array); } /** * Returns an iterator over the non-null values. */ public Iterator<V> iterator() { return new SmallNumberedMapIterator<V>(values); } private class SmallNumberedMapIterator<C> implements Iterator<C> { private final C[] data; private int cur; SmallNumberedMapIterator(C[] data) { this.data = data; this.cur = 0; seekNext(); } protected final void seekNext() { V[] temp = SmallNumberedMap.this.values; try { while (temp[cur] == null) { cur++; } } catch (ArrayIndexOutOfBoundsException e) { cur = -1; } } @Override public final void remove() { SmallNumberedMap.this.array[cur - 1] = null; SmallNumberedMap.this.values[cur - 1] = null; } @Override public final boolean hasNext() { return cur != -1; } @Override public final C next() { C ret = data[cur]; cur++; seekNext(); return ret; } } private int findPosition(K o) { int number = o.getNumber(); if (number == 0) { throw new RuntimeException("unnumbered"); } number = number & (array.length - 1); while (true) { K key = array[number]; if (key == o || key == null) { return number; } number = (number + 1) & (array.length - 1); } } private void doubleSize() { K[] oldArray = array; V[] oldValues = values; final int oldLength = oldArray.length; final int newLength = oldLength * 2; array = newArray(Numberable.class, newLength); values = newArray(Object.class, newLength); for (int i = 0; i < oldLength; i++) { K element = oldArray[i]; if (element != null) { int pos = findPosition(element); array[pos] = element; values[pos] = oldValues[i]; } } } }
4,249
22.611111
92
java
soot
soot-master/src/main/java/soot/util/SmallPriorityQueue.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 static java.lang.Long.numberOfTrailingZeros; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @author Steven Lambeth * */ class SmallPriorityQueue<E> extends PriorityQueue<E> { final static int MAX_CAPACITY = Long.SIZE; private long queue = 0; SmallPriorityQueue(List<? extends E> universe, Map<E, Integer> ordinalMap) { super(universe, ordinalMap); assert universe.size() <= Long.SIZE; } @Override void addAll() { if (N == 0) { return; } queue = -1L >>> -N; min = 0; } @Override public void clear() { queue = 0L; min = Integer.MAX_VALUE; } @Override public Iterator<E> iterator() { return new Itr() { @Override long getExpected() { return queue; } }; } @Override public int size() { return Long.bitCount(queue); } @Override int nextSetBit(int fromIndex) { assert fromIndex >= 0; if (fromIndex > N) { return fromIndex; } long m0 = -1L << fromIndex; long t0 = queue & m0; if ((t0 & -m0) != 0) { return fromIndex; } return numberOfTrailingZeros(t0); } @Override boolean add(int ordinal) { long old = queue; queue |= (1L << ordinal); if (old == queue) { return false; } min = Math.min(min, ordinal); return true; } @Override boolean contains(int ordinal) { assert ordinal >= 0; assert ordinal < N; return ((queue >>> ordinal) & 1L) == 1L; } @Override boolean remove(int index) { assert index >= 0; assert index < N; long old = queue; queue &= ~(1L << index); if (old == queue) { return false; } if (min == index) { min = nextSetBit(min + 1); } return true; } @Override public boolean removeAll(Collection<?> c) { long mask = 0; for (Object o : c) { mask |= (1L << getOrdinal(o)); } long old = queue; queue &= ~mask; min = nextSetBit(min); return old != queue; } @Override public boolean retainAll(Collection<?> c) { long mask = 0; for (Object o : c) { mask |= (1L << getOrdinal(o)); } long old = queue; queue &= mask; min = nextSetBit(min); return old != queue; } @Override public boolean containsAll(Collection<?> c) { long mask = 0; for (Object o : c) { mask |= (1L << getOrdinal(o)); } return (mask & ~queue) == 0; } @Override public boolean addAll(Collection<? extends E> c) { long mask = 0; for (Object o : c) { mask |= (1L << getOrdinal(o)); } long old = queue; queue |= mask; if (old == queue) { return false; } min = nextSetBit(0); return true; } }
3,624
18.917582
78
java
soot
soot-master/src/main/java/soot/util/StationaryArrayList.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2000 Patrick Lam * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * This class implements an ArrayList where the equality and hashCode use object equality, not list equality. This is * important for putting Lists into HashMaps. * * The notation "Stationary" refers to the fact that the List stays "fixed" under list changes. */ public class StationaryArrayList<T> extends java.util.ArrayList<T> { @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object other) { return this == other; } }
1,325
30.571429
117
java
soot
soot-master/src/main/java/soot/util/StringNumberer.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 heros.ThreadSafe; import java.util.HashMap; import java.util.Map; /** * A class that numbers strings, so they can be placed in bitsets. * * @author Ondrej Lhotak */ @ThreadSafe public class StringNumberer extends ArrayNumberer<NumberedString> { private final Map<String, NumberedString> stringToNumbered = new HashMap<String, NumberedString>(1024); public synchronized NumberedString findOrAdd(String s) { NumberedString ret = stringToNumbered.get(s); if (ret == null) { ret = new NumberedString(s); stringToNumbered.put(s, ret); add(ret); } return ret; } public NumberedString find(String s) { return stringToNumbered.get(s); } }
1,513
27.037037
105
java
soot
soot-master/src/main/java/soot/util/StringTools.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.text.CharacterIterator; import java.text.StringCharacterIterator; /** Utility methods for string manipulations commonly used in Soot. */ public class StringTools { /** Convenience field storing the system line separator. */ public final static String lineSeparator = System.getProperty("line.separator"); /** * Returns fromString, but with non-isalpha() characters printed as <code>'\\unnnn'</code>. Used by SootClass to generate * output. */ public static String getEscapedStringOf(String fromString) { StringBuilder whole = new StringBuilder(); assert (!lineSeparator.isEmpty()); final int cr = lineSeparator.charAt(0); final int lf = (lineSeparator.length() == 2) ? lineSeparator.charAt(1) : -1; for (char ch : fromString.toCharArray()) { int asInt = ch; if (asInt != '\\' && ((asInt >= 32 && asInt <= 126) || asInt == cr || asInt == lf)) { whole.append(ch); } else { whole.append(getUnicodeStringFromChar(ch)); } } return whole.toString(); } /** * Returns fromString, but with certain characters printed as if they were in a Java string literal. Used by * StringConstant.toString() */ public static String getQuotedStringOf(String fromString) { final int fromStringLen = fromString.length(); // We definitely need fromStringLen + 2, but let's have some additional space StringBuilder toStringBuffer = new StringBuilder(fromStringLen + 20); toStringBuffer.append("\""); for (int i = 0; i < fromStringLen; i++) { char ch = fromString.charAt(i); switch (ch) { case '\\': toStringBuffer.append("\\\\"); break; case '\'': toStringBuffer.append("\\\'"); break; case '\"': toStringBuffer.append("\\\""); break; case '\n': toStringBuffer.append("\\n"); break; case '\t': toStringBuffer.append("\\t"); break; case '\r': /* * 04.04.2006 mbatch added handling of \r, as compilers throw error if unicode */ toStringBuffer.append("\\r"); break; case '\f': /* * 10.04.2006 Nomait A Naeem added handling of \f, as compilers throw error if unicode */ toStringBuffer.append("\\f"); break; default: if (ch >= 32 && ch <= 126) { toStringBuffer.append(ch); } else { toStringBuffer.append(getUnicodeStringFromChar(ch)); } break; } } toStringBuffer.append("\""); return toStringBuffer.toString(); } /** * Returns a String containing the escaped <code>\\unnnn</code> representation for <code>ch</code>. */ public static String getUnicodeStringFromChar(char ch) { String s = Integer.toHexString(ch); switch (s.length()) { case 1: return "\\u" + "000" + s; case 2: return "\\u" + "00" + s; case 3: return "\\u" + "0" + s; case 4: return "\\u" + "" + s; default: // hex value of a char never exceeds 4 characters since char is 2 bytes throw new AssertionError("invalid hex string '" + s + "' from char '" + ch + "'"); } } /** * Returns a String de-escaping the <code>\\unnnn</code> representation for any escaped characters in the string. */ public static String getUnEscapedStringOf(String str) { StringBuilder buf = new StringBuilder(); CharacterIterator iter = new StringCharacterIterator(str); for (char ch = iter.first(); ch != CharacterIterator.DONE; ch = iter.next()) { if (ch != '\\') { buf.append(ch); } else { // enter escaped mode ch = iter.next(); char format; if (ch == '\\') { buf.append(ch); } else if ((format = getCFormatChar(ch)) != '\0') { buf.append(format); } else if (ch == 'u') { // enter unicode mode StringBuilder mini = new StringBuilder(4); for (int i = 0; i < 4; i++) { mini.append(iter.next()); } buf.append((char) Integer.parseInt(mini.toString(), 16)); } else { throw new RuntimeException("Unexpected char: " + ch); } } } return buf.toString(); } /** Returns the canonical C-string representation of c. */ public static char getCFormatChar(char c) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'b': return '\b'; case 'f': return '\f'; case '\"': return '\"'; case '\'': return '\''; default: return '\0'; } } }
5,620
30.055249
123
java
soot
soot-master/src/main/java/soot/util/Switch.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Etienne Gagnon * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** Basic interface used in the implementation of the Visitor design pattern. */ public interface Switch { }
935
32.428571
80
java
soot
soot-master/src/main/java/soot/util/Switchable.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Etienne Gagnon * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** Basic interface used for visited objects in the Visitor design pattern. */ public interface Switchable { /** Called when this object is visited. */ void apply(Switch sw); }
1,007
32.6
78
java
soot
soot-master/src/main/java/soot/util/UnitMap.java
package soot.util; /*- * #%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.Map; import java.util.Set; import soot.Body; import soot.Unit; import soot.toolkits.graph.UnitGraph; /** * Maps each unit to the result of <code>mapTo</code>. */ public abstract class UnitMap<T> implements Map<Unit, T> { private final Map<Unit, T> unitToResult; /** * maps each unit of this body to the result of <code>mapTo</code>.<br> * before the mapping the method <code>init</code> is called.<br> * the internal map is initialized without any parameter. * * @param b * a Body */ public UnitMap(Body b) { this.unitToResult = new HashMap<Unit, T>(); map(b); } /** * maps each unit of the graph to the result of <code>mapTo</code>.<br> * before the mapping the method <code>init</code> is called.<br> * the internal map is initialized without any parameter. * * @param g * a UnitGraph */ public UnitMap(UnitGraph g) { this(g.getBody()); } /** * maps each unit of this body to the result of <code>mapTo</code>.<br> * before the mapping the method <code>init</code> is called.<br> * the internal map is initialized to <code>initialCapacity</code>. * * @param b * a Body * @param initialCapacity * the initialCapacity of the internal map. */ public UnitMap(Body b, int initialCapacity) { this.unitToResult = new HashMap<Unit, T>(initialCapacity); map(b); } /** * maps each unit of the graph to the result of <code>mapTo</code>.<br> * before the mapping the method <code>init</code> is called.<br> * the internal map is initialized to <code>initialCapacity</code>. * * @param g * a UnitGraph * @param initialCapacity * the initialCapacity of the internal map. */ public UnitMap(UnitGraph g, int initialCapacity) { this(g.getBody(), initialCapacity); } /** * maps each unit of this body to the result of <code>mapTo</code>.<br> * before the mapping the method <code>init</code> is called.<br> * the internal map is initialized to <code>initialCapacity</code> and <code>loadFactor</code>. * * @param b * a Body * @param initialCapacity * the initialCapacity of the internal map. * @param loadFactor * the loadFactor of the internal map. */ public UnitMap(Body b, int initialCapacity, float loadFactor) { this.unitToResult = new HashMap<Unit, T>(initialCapacity); init(); map(b); } /** * maps each unit of the graph to the result of <code>mapTo</code>.<br> * before the mapping the method <code>init</code> is called.<br> * the internal map is initialized to <code>initialCapacity</code> and <code>loadFactor</code>. * * @param g * a UnitGraph * @param initialCapacity * the initialCapacity of the internal map. * @param loadFactor * the loadFactor of the internal map. */ public UnitMap(UnitGraph g, int initialCapacity, float loadFactor) { this(g.getBody(), initialCapacity); } /** * does the actual mapping. assumes, that the map is already initialized. */ private void map(Body b) { for (Unit currentUnit : b.getUnits()) { T o = mapTo(currentUnit); if (o != null) { unitToResult.put(currentUnit, o); } } } /** * allows one-time initialization before any mapping. This method is called before any mapping of a unit (but only once in * the beginning).<br> * If not overwritten does nothing. */ protected void init() { }; /** * maps a unit to an object. This method is called for every unit. If the returned object is <code>null</code> no object * will be mapped.<br> * * @param unit * Unit to which <code>o</code> should be mapped. * @return an object that is mapped to the unit, or <code>null</code>. */ protected abstract T mapTo(Unit unit); /* ====== the Map-interface. all methods are deleguated to the hashmap====== */ @Override public void clear() { unitToResult.clear(); } @Override public boolean containsKey(Object key) { return unitToResult.containsKey(key); } @Override public boolean containsValue(Object value) { return unitToResult.containsValue(value); } @Override public Set<Map.Entry<Unit, T>> entrySet() { return unitToResult.entrySet(); } @Override public boolean equals(Object o) { return unitToResult.equals(o); } @Override public T get(Object key) { return unitToResult.get(key); } @Override public int hashCode() { return unitToResult.hashCode(); } @Override public boolean isEmpty() { return unitToResult.isEmpty(); } @Override public Set<Unit> keySet() { return unitToResult.keySet(); } @Override public T put(Unit key, T value) { return unitToResult.put(key, value); } @Override public void putAll(Map<? extends Unit, ? extends T> t) { unitToResult.putAll(t); } @Override public T remove(Object key) { return unitToResult.remove(key); } @Override public int size() { return unitToResult.size(); } @Override public Collection<T> values() { return unitToResult.values(); } }
6,105
25.4329
124
java
soot
soot-master/src/main/java/soot/util/UnmodifiableIterableSet.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% */ /** * An unmodifiable version of the IterableSet class * * @author Steven Arzt * * @param <E> */ public class UnmodifiableIterableSet<E> extends IterableSet<E> { public UnmodifiableIterableSet() { super(); } /** * Creates a new unmodifiable iterable set as a copy of an existing one * * @param original * The original set to copy */ public UnmodifiableIterableSet(IterableSet<E> original) { for (E e : original) { super.add(e); } } @Override public boolean add(E o) { throw new RuntimeException("This set cannot be modified"); } @Override public boolean remove(Object o) { throw new RuntimeException("This set cannot be modified"); } public boolean forceRemove(Object o) { return super.remove(o); } }
1,633
24.53125
73
java
soot
soot-master/src/main/java/soot/util/WeakMapNumberer.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2019 William Bonnaventure * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.ref.WeakReference; import java.util.Iterator; import java.util.Map; import java.util.WeakHashMap; /** * A class that numbers objects but keeps weak references for garbage collection * * @author William Bonnaventure * * @param <T> */ public class WeakMapNumberer<T extends Numberable> implements IterableNumberer<T> { final Map<T, Integer> map = new WeakHashMap<T, Integer>(); final Map<Integer, WeakReference<T>> rmap = new WeakHashMap<Integer, WeakReference<T>>(); int nextIndex = 1; public WeakMapNumberer() { } @Override public synchronized void add(T o) { if (o.getNumber() != 0) { return; } if (!map.containsKey(o)) { Integer key = nextIndex; map.put(o, key); rmap.put(key, new WeakReference<T>(o)); o.setNumber(nextIndex++); } } @Override public boolean remove(T o) { if (o == null) { return false; } int num = o.getNumber(); if (num == 0) { return false; } o.setNumber(0); Integer i = map.remove(o); if (i == null) { return false; } rmap.remove(i); return true; } @Override public long get(T o) { if (o == null) { return 0; } Integer i = map.get(o); if (i == null) { throw new RuntimeException("couldn't find " + o); } return i; } @Override public T get(long number) { if (number == 0) { return null; } return rmap.get((int)number).get(); } @Override public int size() { return nextIndex - 1; } public boolean contains(T o) { return map.containsKey(o); } @Override public Iterator<T> iterator() { return map.keySet().iterator(); } }
2,526
21.765766
91
java
soot
soot-master/src/main/java/soot/util/annotations/AnnotationElemSwitch.java
package soot.util.annotations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.tagkit.AbstractAnnotationElemTypeSwitch; import soot.tagkit.AnnotationAnnotationElem; import soot.tagkit.AnnotationArrayElem; import soot.tagkit.AnnotationBooleanElem; import soot.tagkit.AnnotationClassElem; import soot.tagkit.AnnotationDoubleElem; import soot.tagkit.AnnotationElem; import soot.tagkit.AnnotationEnumElem; import soot.tagkit.AnnotationFloatElem; import soot.tagkit.AnnotationIntElem; import soot.tagkit.AnnotationLongElem; import soot.tagkit.AnnotationStringElem; /** * * An {@link AbstractAnnotationElemTypeSwitch} that converts an {@link AnnotationElem} to a mapping of element name and the * actual result. * * @author Florian Kuebler * */ public class AnnotationElemSwitch extends AbstractAnnotationElemTypeSwitch<AnnotationElemSwitch.AnnotationElemResult<?>> { /** * * A helper class to map method name and result. * * @author Florian Kuebler * * @param <V> * the result type. */ public static class AnnotationElemResult<V> { private final String name; private final V value; public AnnotationElemResult(String name, V value) { this.name = name; this.value = value; } public String getKey() { return name; } public V getValue() { return value; } } @Override public void caseAnnotationAnnotationElem(AnnotationAnnotationElem v) { AnnotationInstanceCreator aic = new AnnotationInstanceCreator(); Object result = aic.create(v.getValue()); setResult(new AnnotationElemResult<Object>(v.getName(), result)); } @Override public void caseAnnotationArrayElem(AnnotationArrayElem v) { /* * for arrays, apply a new AnnotationElemSwitch to every array element and collect the results. Note that the component * type of the result is unknown here, s.t. object has to be used. */ Object[] result = new Object[v.getNumValues()]; int i = 0; for (AnnotationElem elem : v.getValues()) { AnnotationElemSwitch sw = new AnnotationElemSwitch(); elem.apply(sw); result[i] = sw.getResult().getValue(); i++; } setResult(new AnnotationElemResult<Object[]>(v.getName(), result)); } @Override public void caseAnnotationBooleanElem(AnnotationBooleanElem v) { setResult(new AnnotationElemResult<Boolean>(v.getName(), v.getValue())); } @Override public void caseAnnotationClassElem(AnnotationClassElem v) { try { Class<?> clazz = ClassLoaderUtils.loadClass(v.getDesc().replace('/', '.')); setResult(new AnnotationElemResult<Class<?>>(v.getName(), clazz)); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load class: " + v.getDesc()); } } @Override public void caseAnnotationDoubleElem(AnnotationDoubleElem v) { setResult(new AnnotationElemResult<Double>(v.getName(), v.getValue())); } @Override public void caseAnnotationEnumElem(AnnotationEnumElem v) { try { Class<?> clazz = ClassLoaderUtils.loadClass(v.getTypeName().replace('/', '.')); // find out which enum constant is used. Enum<?> result = null; for (Object o : clazz.getEnumConstants()) { try { Enum<?> t = (Enum<?>) o; if (t.name().equals(v.getConstantName())) { result = t; break; } } catch (ClassCastException e) { throw new RuntimeException("Class " + v.getTypeName() + " is no Enum"); } } if (result == null) { throw new RuntimeException(v.getConstantName() + " is not a EnumConstant of " + v.getTypeName()); } setResult(new AnnotationElemResult<Enum<?>>(v.getName(), result)); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load class: " + v.getTypeName()); } } @Override public void caseAnnotationFloatElem(AnnotationFloatElem v) { setResult(new AnnotationElemResult<Float>(v.getName(), v.getValue())); } @Override public void caseAnnotationIntElem(AnnotationIntElem v) { setResult(new AnnotationElemResult<Integer>(v.getName(), v.getValue())); } @Override public void caseAnnotationLongElem(AnnotationLongElem v) { setResult(new AnnotationElemResult<Long>(v.getName(), v.getValue())); } @Override public void caseAnnotationStringElem(AnnotationStringElem v) { setResult(new AnnotationElemResult<String>(v.getName(), v.getValue())); } @Override public void defaultCase(Object object) { throw new RuntimeException("Unexpected AnnotationElem"); } }
5,409
29.223464
123
java
soot
soot-master/src/main/java/soot/util/annotations/AnnotationInstanceCreator.java
package soot.util.annotations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import com.google.common.reflect.AbstractInvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import soot.tagkit.AnnotationElem; import soot.tagkit.AnnotationEnumElem; import soot.tagkit.AnnotationTag; import soot.util.annotations.AnnotationElemSwitch.AnnotationElemResult; /** * * A simple helper class with the ability to create an instance of {@link Proxy} implementing the annotation interface * represented by the given {@link AnnotationTag}. * * * @author Florian Kuebler * */ public class AnnotationInstanceCreator { /** * Creates an instance of the Annotation represented by <code>tag</code>. * * @param tag * the soot internal representation of the annotation to be created. * @return an Object extending {@link Proxy} and implementing the type of <code>tag</code> * @throws RuntimeException * if * <ul> * <li>the class defined in {@link AnnotationTag#getType()} of <code>tag</code> could not be loaded.</li> * * <li><code>tag</code> does not define all required methods of the annotation loaded.</li> * * <li>a class defined within a {@link AnnotationElem} could not be loaded.</li> * * <li>the enum defined in {@link AnnotationEnumElem} is no instance of {@link Enum}.</li> * </ul> */ public Object create(AnnotationTag tag) { ClassLoader cl = this.getClass().getClassLoader(); try { // load the class of the annotation to be created final Class<?> clazz = ClassLoaderUtils.loadClass(tag.getType().replace('/', '.')); final Map<String, Object> map = new HashMap<String, Object>(); // for every element generate the result for (AnnotationElem elem : tag.getElems()) { AnnotationElemSwitch sw = new AnnotationElemSwitch(); elem.apply(sw); @SuppressWarnings("unchecked") AnnotationElemResult<Object> result = (AnnotationElemResult<Object>) sw.getResult(); map.put(result.getKey(), result.getValue()); } // create the instance Object result = Proxy.newProxyInstance(cl, new Class[] { clazz }, new AbstractInvocationHandler() { @SuppressWarnings("unchecked") @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); Class<?> retType = method.getReturnType(); // if the method being called is #annotationType return the // clazz of the annotation if (name.equals("annotationType")) { return clazz; } // get the precomputed result for the method being called. Object result = map.get(name); if (result != null) { // if the result is an Object[], the array has to be // transformed to an array of the return type. if (result instanceof Object[]) { Object[] oa = (Object[]) result; return Arrays.copyOf(oa, oa.length, (Class<? extends Object[]>) retType); } // java bytecode does not know boolean types. if ((retType.equals(boolean.class) || retType.equals(Boolean.class)) && (result instanceof Integer)) { return ((Integer) result) != 0; } return result; } else { // if the AnnotationTag does not define a method, try to // use the default value. result = method.getDefaultValue(); if (result != null) { return result; } } throw new RuntimeException("No value for " + name + " declared in the annotation " + clazz); } }); return result; } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load class: " + tag.getType()); } } }
4,853
33.183099
118
java
soot
soot-master/src/main/java/soot/util/annotations/ClassLoaderUtils.java
package soot.util.annotations; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * Copyright (C) 2004 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.lang.reflect.Array; /** * Loads classes without relying on JBoss. * * A general note on dynamically loading classes based on information from * target programs: You don't want that. It's a horrible idea, can lead to * severe security vulnerabilities, and is bad style. Trust me. But people seem * to need it, so this class makes it at least slightly less horrible than the * old way. It's still insane, but now it's insanity with style. Somehow. * * @author Steven Arzt * */ public class ClassLoaderUtils { /** * Don't call me. Just don't. * * @param className * @return * @throws ClassNotFoundException */ public static Class<?> loadClass(String className) throws ClassNotFoundException { return loadClass(className, true); } /** * Don't call me. Just don't. * * @param className * @return * @throws ClassNotFoundException */ public static Class<?> loadClass(String className, boolean allowPrimitives) throws ClassNotFoundException { // Do we have a primitive class if (allowPrimitives) { switch (className) { case "B": case "byte": return Byte.TYPE; case "C": case "char": return Character.TYPE; case "D": case "double": return Double.TYPE; case "F": case "float": return Float.TYPE; case "I": case "int": return Integer.TYPE; case "J": case "long": return Long.TYPE; case "S": case "short": return Short.TYPE; case "Z": case "boolean": return Boolean.TYPE; case "V": case "void": return Void.TYPE; } } // JNI format if (className.startsWith("L") && className.endsWith(";")) { return loadClass(className.substring(1, className.length() - 1), false); } int arrayDimension = 0; while (className.charAt(arrayDimension) == '[') { arrayDimension++; } // If this isn't an array after all if (arrayDimension == 0) { return Class.forName(className); } // Load the array Class<?> baseClass = loadClass(className.substring(arrayDimension)); return Array.newInstance(baseClass, new int[arrayDimension]).getClass(); } }
3,196
26.8
109
java
soot
soot-master/src/main/java/soot/util/backend/ASMBackendUtils.java
package soot.util.backend; import java.util.List; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.objectweb.asm.ByteVector; import org.objectweb.asm.ClassWriter; import soot.ArrayType; import soot.BooleanType; import soot.ByteType; import soot.CharType; import soot.DoubleType; import soot.FloatType; import soot.IntType; import soot.LongType; import soot.RefType; import soot.ShortType; import soot.SootClass; import soot.SootField; import soot.SootMethodRef; import soot.Type; import soot.TypeSwitch; import soot.VoidType; import soot.baf.DoubleWordType; import soot.options.Options; import soot.tagkit.Attribute; import soot.tagkit.DoubleConstantValueTag; import soot.tagkit.FloatConstantValueTag; import soot.tagkit.IntegerConstantValueTag; import soot.tagkit.LongConstantValueTag; import soot.tagkit.StringConstantValueTag; import soot.tagkit.Tag; /** * Utility class for ASM-based back-ends. * * @author Tobias Hamann, Florian Kuebler, Dominik Helm, Lukas Sommer * */ public class ASMBackendUtils { /** * Convert class identifiers and signatures by replacing dots by slashes. * * @param s * String to convert * @return Converted identifier */ public static String slashify(String s) { if (s == null) { return null; } return s.replace('.', '/'); } /** * Compute type description for methods, comprising parameter types and return type. * * @param m * Method to determine type description * @return Method type description */ public static String toTypeDesc(SootMethodRef m) { return toTypeDesc(m.parameterTypes(), m.returnType()); } /** * Compute type description for methods, comprising parameter types and return type. * * @param parameterTypes * The parameters for some method * @param returnType * The return type for some method * @return Method type description */ public static String toTypeDesc(List<Type> parameterTypes, Type returnType) { StringBuilder sb = new StringBuilder(); sb.append('('); for (Type t : parameterTypes) { sb.append(toTypeDesc(t)); } sb.append(')'); sb.append(toTypeDesc(returnType)); return sb.toString(); } /** * Convert type to JVM style type description * * @param type * Type to convert * @return JVM style type description */ public static String toTypeDesc(Type type) { final StringBuilder sb = new StringBuilder(1); type.apply(new TypeSwitch() { @Override public void defaultCase(Type t) { throw new RuntimeException("Invalid type " + t.toString()); } @Override public void caseDoubleType(DoubleType t) { sb.append('D'); } @Override public void caseFloatType(FloatType t) { sb.append('F'); } @Override public void caseIntType(IntType t) { sb.append('I'); } @Override public void caseByteType(ByteType t) { sb.append('B'); } @Override public void caseShortType(ShortType t) { sb.append('S'); } @Override public void caseCharType(CharType t) { sb.append('C'); } @Override public void caseBooleanType(BooleanType t) { sb.append('Z'); } @Override public void caseLongType(LongType t) { sb.append('J'); } @Override public void caseArrayType(ArrayType t) { sb.append('['); t.getElementType().apply(this); } @Override public void caseRefType(RefType t) { sb.append('L'); sb.append(slashify(t.getClassName())); sb.append(';'); } @Override public void caseVoidType(VoidType t) { sb.append('V'); } }); return sb.toString(); } /** * Get default value of a field for constant pool * * @param field * Field to get default value for * @return Default value or <code>null</code> if there is no default value. */ public static Object getDefaultValue(SootField field) { for (Tag t : field.getTags()) { switch (t.getName()) { case IntegerConstantValueTag.NAME: return ((IntegerConstantValueTag) t).getIntValue(); case LongConstantValueTag.NAME: return ((LongConstantValueTag) t).getLongValue(); case FloatConstantValueTag.NAME: return ((FloatConstantValueTag) t).getFloatValue(); case DoubleConstantValueTag.NAME: return ((DoubleConstantValueTag) t).getDoubleValue(); case StringConstantValueTag.NAME: // Default value for string may only be returned if the field is of type String or a sub-type. if (acceptsStringInitialValue(field)) { return ((StringConstantValueTag) t).getStringValue(); } } } return null; } /** * Determine if the field accepts a string default value, this is only true for fields of type String or a sub-type of * String * * @param field * Field * @return <code>true</code> if the field is of type String or sub-type, <code>false</code> otherwise. */ public static boolean acceptsStringInitialValue(SootField field) { if (field.getType() instanceof RefType) { SootClass fieldClass = ((RefType) field.getType()).getSootClass(); return fieldClass.getName().equals("java.lang.String"); } return false; } /** * Get the size in words for a type. * * @param t * Type * @return Size in words */ public static int sizeOfType(Type t) { if (t instanceof DoubleWordType || t instanceof LongType || t instanceof DoubleType) { return 2; } else if (t instanceof VoidType) { return 0; } else { return 1; } } /** * Create an ASM attribute from an Soot attribute * * @param attr * Soot attribute * @return ASM attribute */ public static org.objectweb.asm.Attribute createASMAttribute(Attribute attr) { final Attribute a = attr; return new org.objectweb.asm.Attribute(attr.getName()) { @Override protected ByteVector write(final ClassWriter cw, final byte[] code, final int len, final int maxStack, final int maxLocals) { ByteVector result = new ByteVector(); result.putByteArray(a.getValue(), 0, a.getValue().length); return result; } }; } /** * Translate internal numbering of java versions to real version for debug messages. * * @param javaVersion * Internal java version number * @return Java version in the format "1.7" */ public static String translateJavaVersion(int javaVersion) { if (javaVersion == Options.java_version_default) { return "1.0"; } else { return "1." + (javaVersion - 1); } } }
7,660
26.166667
120
java
soot
soot-master/src/main/java/soot/util/backend/SootASMClassWriter.java
package soot.util.backend; /*- * #%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 static soot.util.backend.ASMBackendUtils.slashify; import org.objectweb.asm.ClassWriter; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.Type; /** * ASM class writer with soot-specific resolution of common superclasses * * @author Tobias Hamann, Florian Kuebler, Dominik Helm, Lukas Sommer * */ public class SootASMClassWriter extends ClassWriter { /** * Constructs a new {@link ClassWriter} object. * * @param flags * option flags that can be used to modify the default behavior of this class. See {@link #COMPUTE_MAXS}, * {@link #COMPUTE_FRAMES}. */ public SootASMClassWriter(int flags) { super(flags); } /* * We need to overwrite this method here, as we are generating multiple classes that might reference each other. See * asm4-guide, top of page 45 for more information. */ /* * (non-Javadoc) * * @see org.objectweb.asm.ClassWriter#getCommonSuperClass(java.lang.String, java.lang.String) */ @Override protected String getCommonSuperClass(String type1, String type2) { String typeName1 = type1.replace('/', '.'); String typeName2 = type2.replace('/', '.'); SootClass s1 = Scene.v().getSootClass(typeName1); SootClass s2 = Scene.v().getSootClass(typeName2); // If these two classes haven't been loaded yet or are phantom, we take // java.lang.Object as the common superclass final Type mergedType; if (s1.isPhantom() || s2.isPhantom() || s1.resolvingLevel() == SootClass.DANGLING || s2.resolvingLevel() == SootClass.DANGLING) { mergedType = Scene.v().getObjectType(); } else { Type t1 = s1.getType(); Type t2 = s2.getType(); mergedType = t1.merge(t2, Scene.v()); } if (mergedType instanceof RefType) { return slashify(((RefType) mergedType).getClassName()); } else { throw new RuntimeException("Could not find common super class"); } } }
2,810
29.89011
118
java
soot
soot-master/src/main/java/soot/util/cfgcmd/AltClassLoader.java
package soot.util.cfgcmd; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 John Jorgensen * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.io.FileInputStream; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.G; import soot.Singletons; /** * <p> * A {@link ClassLoader} that loads specified classes from a different class path than that given by the value of * <code>java.class.path</code> in {@link System#getProperties()}. * </p> * * <p> * This class is part of Soot's test infrastructure. It allows loading multiple implementations of a class with a given name, * and was written to compare different implementations of Soot's CFG representations. * </p> */ public class AltClassLoader extends ClassLoader { private static final Logger logger = LoggerFactory.getLogger(AltClassLoader.class); private final static boolean DEBUG = false; /** * Locations in the alternate classpath. */ private String[] locations; /** * Maps from already loaded classnames to their Class objects. */ private final Map<String, Class<?>> alreadyFound = new HashMap<String, Class<?>>(); /** * Maps from the names of classes to be loaded from the alternate classpath to mangled names to use for them. */ private final Map<String, String> nameToMangledName = new HashMap<String, String>(); /** * Maps from the mangled names of classes back to their original names. */ private final Map<String, String> mangledNameToName = new HashMap<String, String>(); /** * Constructs an <code>AltClassLoader</code> for inclusion in Soot's global variable manager, {@link G}. * * @param g * guarantees that the constructor may only be called from {@link Singletons}. */ public AltClassLoader(Singletons.Global g) { } /** * Returns the single instance of <code>AltClassLoader</code>, which loads classes from the classpath set by the most * recent call to its {@link #setAltClassPath}. * * @return Soot's <code>AltClassLoader</code>. */ public static AltClassLoader v() { return G.v().soot_util_cfgcmd_AltClassLoader(); } /** * Sets the list of locations in the alternate classpath. * * @param altClassPath * A list of directories and jar files to search for class files, delimited by {@link File#pathSeparator}. */ public void setAltClassPath(String altClassPath) { List<String> locationList = new LinkedList<String>(); for (StringTokenizer tokens = new StringTokenizer(altClassPath, File.pathSeparator, false); tokens.hasMoreTokens();) { String location = tokens.nextToken(); locationList.add(location); } locations = locationList.toArray(new String[locationList.size()]); } /** * Specifies the set of class names that the <code>AltClassLoader</code> should load from the alternate classpath instead * of the regular classpath. * * @param classNames[] * an array containing the names of classes to be loaded from the AltClassLoader. */ public void setAltClasses(String[] classNames) { nameToMangledName.clear(); for (String origName : classNames) { String mangledName = mangleName(origName); nameToMangledName.put(origName, mangledName); mangledNameToName.put(mangledName, origName); } } /** * Mangles a classname so that it will not be found on the system classpath by our parent class loader, even if there is a * class with the original name there. We use a crude heuristic to do this that happens to work with the names we have * needed to mangle to date. The heuristic requires that <code>origName</code> include at least two dots (i.e., the class * must be in a package, where the package name has at least two components). More sophisticated possibilities certainly * exist, but they would require more thorough parsing of the class file. * * @param origName * the name to be mangled. * @return the mangled name. * @throws IllegalArgumentException * if <code>origName</code> is not amenable to our crude mangling. */ private static String mangleName(String origName) throws IllegalArgumentException { final char dot = '.'; final char dotReplacement = '_'; final int lastDot = origName.lastIndexOf(dot); StringBuilder mangledName = new StringBuilder(origName); int replacements = 0; for (int nextDot = lastDot; (nextDot = origName.lastIndexOf(dot, nextDot - 1)) >= 0;) { mangledName.setCharAt(nextDot, dotReplacement); replacements++; } if (replacements <= 0) { throw new IllegalArgumentException( "AltClassLoader.mangleName()'s crude classname mangling cannot deal with " + origName); } return mangledName.toString(); } /** * <p> * Loads a class from either the regular classpath, or the alternate classpath, depending on whether it looks like we have * already mangled its name. * </p> * * <p> * This method follows the steps provided by * <a href="http://www.javaworld.com/javaworld/jw-03-2000/jw-03-classload.html#resources">Ken McCrary's ClasssLoader * tutorial</a>. * </p> * * @param maybeMangledName * A string from which the desired class's name can be determined. It may have been mangled by * {@link AltClassLoader#loadClass(String) AltClassLoader.loadClass()} so that the regular * <code>ClassLoader</code> to which we are delegating won't load the class from the regular classpath. * @return the loaded class. * @throws ClassNotFoundException * if the class cannot be loaded. * */ @Override protected Class<?> findClass(String maybeMangledName) throws ClassNotFoundException { if (DEBUG) { logger.debug("AltClassLoader.findClass(" + maybeMangledName + ')'); } Class<?> result = alreadyFound.get(maybeMangledName); if (result != null) { return result; } String name = mangledNameToName.get(maybeMangledName); if (name == null) { name = maybeMangledName; } String pathTail = "/" + name.replace('.', File.separatorChar) + ".class"; for (String element : locations) { String path = element + pathTail; try (FileInputStream stream = new FileInputStream(path)) { byte[] classBytes = new byte[stream.available()]; stream.read(classBytes); replaceAltClassNames(classBytes); result = defineClass(maybeMangledName, classBytes, 0, classBytes.length); alreadyFound.put(maybeMangledName, result); return result; } catch (java.io.IOException e) { // Try the next location. } catch (ClassFormatError e) { if (DEBUG) { logger.error(e.getMessage(), e); } // Try the next location. } } throw new ClassNotFoundException("Unable to find class" + name + " in alternate classpath"); } /** * <p> * Loads a class, from the alternate classpath if the class's name has been included in the list of alternate classes with * {@link #setAltClasses(String[]) setAltClasses()}, from the regular system classpath otherwise. When a alternate class is * loaded, its references to other alternate classes are also resolved to the alternate classpath. * * @param name * the name of the class to load. * @return the loaded class. * @throws ClassNotFoundException * if the class cannot be loaded. */ @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (DEBUG) { logger.debug("AltClassLoader.loadClass(" + name + ")"); } String nameForParent = nameToMangledName.get(name); if (nameForParent == null) { // This is not an alternate class nameForParent = name; } if (DEBUG) { logger.debug("AltClassLoader.loadClass asking parent for " + nameForParent); } return super.loadClass(nameForParent, false); } /** * Replaces any occurrences in <code>classBytes</code> of classnames to be loaded from the alternate class path with the * corresponding mangled names. Of course we should really parse the class pool properly, since the simple-minded, brute * force replacment done here could produce problems with some combinations of classnames and class contents. But we've got * away with this so far! */ private void replaceAltClassNames(byte[] classBytes) { for (Map.Entry<String, String> entry : nameToMangledName.entrySet()) { String origName = entry.getKey().replace('.', '/'); String mangledName = entry.getValue().replace('.', '/'); findAndReplace(classBytes, stringToUtf8Pattern(origName), stringToUtf8Pattern(mangledName)); findAndReplace(classBytes, stringToTypeStringPattern(origName), stringToTypeStringPattern(mangledName)); } } /** * Returns the bytes that correspond to a CONSTANT_Utf8 constant pool entry containing the passed string. */ private static byte[] stringToUtf8Pattern(String s) { byte[] origBytes = s.getBytes(); int length = origBytes.length; final byte CONSTANT_Utf8 = 1; byte[] result = new byte[length + 3]; result[0] = CONSTANT_Utf8; result[1] = (byte) (length & 0xff00); result[2] = (byte) (length & 0x00ff); System.arraycopy(origBytes, 0, result, 3, length); return result; } /** * Returns the bytes that correspond to a type signature string containing the passed string. */ private static byte[] stringToTypeStringPattern(String s) { byte[] origBytes = s.getBytes(); int length = origBytes.length; byte[] result = new byte[length + 2]; result[0] = (byte) 'L'; System.arraycopy(origBytes, 0, result, 1, length); result[length + 1] = (byte) ';'; return result; } /** * Replaces all occurrences of the <code>pattern</code> in <code>text</code> with <code>replacement</code>. * * @throws IllegalArgumentException * if the lengths of <code>text</code> and <code>replacement</code> differ. */ private static void findAndReplace(byte[] text, byte[] pattern, byte[] replacement) throws IllegalArgumentException { int patternLength = pattern.length; if (patternLength != replacement.length) { throw new IllegalArgumentException("findAndReplace(): The lengths of the pattern and replacement must match."); } int match = 0; while ((match = findMatch(text, pattern, match)) >= 0) { replace(text, replacement, match); match += patternLength; } } /** * A naive string-searching algorithm for finding a pattern in a byte array. * * @param text * the array to search in. * @param pattern * the string of bytes to search for. * @param start * the first position in text to search (0-based). * @return the index in text where the first occurrence of <code>pattern</code> in <code>text</code> after * <code>start</code> begins. Returns -1 if <code>pattern</code> does not occur in <code>text</code> after * <code>start</code>. */ private static int findMatch(byte[] text, byte[] pattern, int start) { int textLength = text.length; int patternLength = pattern.length; nextBase: for (int base = start; base < textLength; base++) { for (int t = base, p = 0; p < patternLength; t++, p++) { if (text[t] != pattern[p]) { continue nextBase; } } return base; } return -1; } /** * Replace the <code>replacement.length</code> bytes in <code>text</code> starting at <code>start</code> with the bytes in * <code>replacement</code>. * * @throws ArrayIndexOutOfBounds * if there are not <code>replacement.length</code> remaining after <code>text[start]</code>. */ private static void replace(byte[] text, byte[] replacement, int start) { for (int t = start, p = 0; p < replacement.length; t++, p++) { text[t] = replacement[p]; } } /** * <p> * A main() entry for basic unit testing. * </p> * * <p> * Usage: path class ... * </p> */ public static void main(String[] argv) throws ClassNotFoundException { AltClassLoader.v().setAltClassPath(argv[0]); for (int i = 1; i < argv.length; i++) { AltClassLoader.v().setAltClasses(new String[] { argv[i] }); logger.debug("main() loadClass(" + argv[i] + ")"); AltClassLoader.v().loadClass(argv[i]); } } }
13,350
35.678571
125
java
soot
soot-master/src/main/java/soot/util/cfgcmd/CFGGraphType.java
package soot.util.cfgcmd; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 John Jorgensen * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.toolkits.graph.ArrayRefBlockGraph; import soot.toolkits.graph.BriefBlockGraph; import soot.toolkits.graph.BriefUnitGraph; import soot.toolkits.graph.ClassicCompleteBlockGraph; import soot.toolkits.graph.ClassicCompleteUnitGraph; import soot.toolkits.graph.CompleteBlockGraph; import soot.toolkits.graph.CompleteUnitGraph; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.ExceptionalBlockGraph; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.graph.TrapUnitGraph; import soot.toolkits.graph.ZonedBlockGraph; import soot.util.dot.DotGraph; /** * An enumeration type for representing the varieties of control flow graph available, for use in tools that compare or * display CFGs. */ public abstract class CFGGraphType extends CFGOptionMatcher.CFGOption { private static final Logger logger = LoggerFactory.getLogger(CFGGraphType.class); private static final boolean DEBUG = true; /** * Method that will build a graph of this type. * * @param b * The method <code>Body</code> from which to build the graph. * * @return The control flow graph corresponding to <code>b</code> */ public abstract DirectedGraph<?> buildGraph(Body b); /** * Method that will draw a {@link DotGraph} representation of the control flow in this type of graph. This method is * intended for use within {@link soot.tools.CFGViewer CFGViewer}. * * @param drawer * The {@link CFGToDotGraph} object that will draw the graph. * * @param g * The graph to draw. * * @param b * The body associated with the graph, <code>g</code>. * * @return a <code>DotGraph</code> visualizing the control flow in <code>g</code>. */ public abstract DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b); private CFGGraphType(String name) { super(name); } /** * Returns the <code>CFGGraphType</code> identified by the passed name. * * @param option * A {@link String} identifying the graph type. * * @return A {@link CFGGraphType} object whose {@link #buildGraph()} method will create the desired sort of control flow * graph and whose {@link #drawGraph} method will produce a {@link DotGraph} corresponding to the graph. */ public static CFGGraphType getGraphType(String option) { return (CFGGraphType) graphTypeOptions.match(option); } /** * Returns a string containing the names of all the available {@link CFGGraphType}s, separated by '|' characters. * * @param initialIndent * The number of blank spaces to insert at the beginning of the returned string. Ignored if negative. * * @param rightMargin * If positive, newlines will be inserted to try to keep the length of each line in the returned string less than * or equal to <code>rightMargin</code>. * * @param hangingIndent * If positive, this number of spaces will be inserted immediately after each newline inserted to respect the * <code>rightMargin</code>. */ public static String help(int initialIndent, int rightMargin, int hangingIndent) { return graphTypeOptions.help(initialIndent, rightMargin, hangingIndent); } public static final CFGGraphType BRIEF_UNIT_GRAPH = new CFGGraphType("BriefUnitGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new BriefUnitGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType EXCEPTIONAL_UNIT_GRAPH = new CFGGraphType("ExceptionalUnitGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG((ExceptionalUnitGraph) g); } }; public static final CFGGraphType COMPLETE_UNIT_GRAPH = new CFGGraphType("CompleteUnitGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new CompleteUnitGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG((CompleteUnitGraph) g); } }; public static final CFGGraphType TRAP_UNIT_GRAPH = new CFGGraphType("TrapUnitGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new TrapUnitGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType CLASSIC_COMPLETE_UNIT_GRAPH = new CFGGraphType("ClassicCompleteUnitGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new ClassicCompleteUnitGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType BRIEF_BLOCK_GRAPH = new CFGGraphType("BriefBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new BriefBlockGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType EXCEPTIONAL_BLOCK_GRAPH = new CFGGraphType("ExceptionalBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new ExceptionalBlockGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG((ExceptionalBlockGraph) g); } }; public static final CFGGraphType COMPLETE_BLOCK_GRAPH = new CFGGraphType("CompleteBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new CompleteBlockGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType CLASSIC_COMPLETE_BLOCK_GRAPH = new CFGGraphType("ClassicCompleteBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new ClassicCompleteBlockGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType ARRAY_REF_BLOCK_GRAPH = new CFGGraphType("ArrayRefBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new ArrayRefBlockGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType ZONED_BLOCK_GRAPH = new CFGGraphType("ZonedBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return new ZonedBlockGraph(b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; private static DirectedGraph<?> loadAltGraph(String className, Body b) { try { Class<?> graphClass = AltClassLoader.v().loadClass(className); Constructor<?> constructor = graphClass.getConstructor(Body.class); DirectedGraph<?> result = (DirectedGraph<?>) constructor.newInstance(b); return result; } // Turn class loading exceptions into RuntimeExceptions, so callers // don't need to declare them: perhaps a shoddy tactic. catch (ClassNotFoundException e) { if (DEBUG) { logger.error(e.getMessage(), e); } throw new IllegalArgumentException("Unable to find " + className + " in alternate classpath: " + e.getMessage()); } catch (NoSuchMethodException e) { if (DEBUG) { logger.error(e.getMessage(), e); } throw new IllegalArgumentException("There is no " + className + "(Body) constructor: " + e.getMessage()); } catch (InstantiationException e) { if (DEBUG) { logger.error(e.getMessage(), e); } throw new IllegalArgumentException( "Unable to instantiate " + className + " in alternate classpath: " + e.getMessage()); } catch (IllegalAccessException e) { if (DEBUG) { logger.error(e.getMessage(), e); } throw new IllegalArgumentException( "Unable to access " + className + "(Body) in alternate classpath: " + e.getMessage()); } catch (InvocationTargetException e) { if (DEBUG) { logger.error(e.getMessage(), e); } throw new IllegalArgumentException( "Unable to invoke " + className + "(Body) in alternate classpath: " + e.getMessage()); } } public static final CFGGraphType ALT_BRIEF_UNIT_GRAPH = new CFGGraphType("AltBriefUnitGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return loadAltGraph("soot.toolkits.graph.BriefUnitGraph", b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType ALT_COMPLETE_UNIT_GRAPH = new CFGGraphType("AltCompleteUnitGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return loadAltGraph("soot.toolkits.graph.CompleteUnitGraph", b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType ALT_TRAP_UNIT_GRAPH = new CFGGraphType("AltTrapUnitGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return loadAltGraph("soot.toolkits.graph.TrapUnitGraph", b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType ALT_ARRAY_REF_BLOCK_GRAPH = new CFGGraphType("AltArrayRefBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return loadAltGraph("soot.toolkits.graph.ArrayRefBlockGraph", b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType ALT_BRIEF_BLOCK_GRAPH = new CFGGraphType("AltBriefBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return loadAltGraph("soot.toolkits.graph.BriefBlockGraph", b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType ALT_COMPLETE_BLOCK_GRAPH = new CFGGraphType("AltCompleteBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return loadAltGraph("soot.toolkits.graph.CompleteBlockGraph", b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; public static final CFGGraphType ALT_ZONED_BLOCK_GRAPH = new CFGGraphType("AltZonedBlockGraph") { @Override public DirectedGraph<?> buildGraph(Body b) { return loadAltGraph("soot.toolkits.graph.ZonedBlockGraph", b); } @Override public DotGraph drawGraph(CFGToDotGraph drawer, DirectedGraph<?> g, Body b) { return drawer.drawCFG(g, b); } }; private final static CFGOptionMatcher graphTypeOptions = new CFGOptionMatcher(new CFGGraphType[] { BRIEF_UNIT_GRAPH, EXCEPTIONAL_UNIT_GRAPH, COMPLETE_UNIT_GRAPH, TRAP_UNIT_GRAPH, CLASSIC_COMPLETE_UNIT_GRAPH, BRIEF_BLOCK_GRAPH, EXCEPTIONAL_BLOCK_GRAPH, COMPLETE_BLOCK_GRAPH, CLASSIC_COMPLETE_BLOCK_GRAPH, ARRAY_REF_BLOCK_GRAPH, ZONED_BLOCK_GRAPH, ALT_ARRAY_REF_BLOCK_GRAPH, ALT_BRIEF_UNIT_GRAPH, ALT_COMPLETE_UNIT_GRAPH, ALT_TRAP_UNIT_GRAPH, ALT_BRIEF_BLOCK_GRAPH, ALT_COMPLETE_BLOCK_GRAPH, ALT_ZONED_BLOCK_GRAPH, }); }
13,192
33.718421
124
java
soot
soot-master/src/main/java/soot/util/cfgcmd/CFGIntermediateRep.java
package soot.util.cfgcmd; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 John Jorgensen * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.baf.Baf; import soot.grimp.Grimp; import soot.jimple.JimpleBody; import soot.shimple.Shimple; /** * An enumeration type for representing the varieties of intermediate representation available, for use in tools that compare * or display control flow graphs. */ public abstract class CFGIntermediateRep extends CFGOptionMatcher.CFGOption { private CFGIntermediateRep(String name) { super(name); } /** * Converts a <code>JimpleBody</code> into the corresponding <code>Body</code> in this intermediate representation. * * @param b * The Jimple body to be represented. * * @return a {@link Body} in this intermediate representation which represents the same method as <code>b</code>. */ public abstract Body getBody(JimpleBody b); public static final CFGIntermediateRep JIMPLE_IR = new CFGIntermediateRep("jimple") { @Override public Body getBody(JimpleBody b) { return b; } }; public static final CFGIntermediateRep BAF_IR = new CFGIntermediateRep("baf") { @Override public Body getBody(JimpleBody b) { return Baf.v().newBody(b); } }; public static final CFGIntermediateRep GRIMP_IR = new CFGIntermediateRep("grimp") { @Override public Body getBody(JimpleBody b) { return Grimp.v().newBody(b, "gb"); } }; public static final CFGIntermediateRep SHIMPLE_IR = new CFGIntermediateRep("shimple") { @Override public Body getBody(JimpleBody b) { return Shimple.v().newBody(b); } }; public static final CFGIntermediateRep VIA_SHIMPLE_JIMPLE_IR = new CFGIntermediateRep("viaShimpleJimple") { @Override public Body getBody(JimpleBody b) { return Shimple.v().newJimpleBody(Shimple.v().newBody(b)); } }; private final static CFGOptionMatcher irOptions = new CFGOptionMatcher(new CFGIntermediateRep[] { JIMPLE_IR, BAF_IR, GRIMP_IR, SHIMPLE_IR, VIA_SHIMPLE_JIMPLE_IR, }); /** * Returns the <code>CFGIntermediateRep</code> identified by the passed name. * * @param name * A {@link String} identifying the intermediate representation. * * @return A <code>CFGIntermediateRep</code> object whose {@link #getBody(JimpleBody)} method will create the desired * intermediate representation. */ public static CFGIntermediateRep getIR(String name) { return (CFGIntermediateRep) irOptions.match(name); } /** * Returns a string containing the names of all the available <code>CFGIntermediateRep</code>s, separated by '|' * characters. * * @param initialIndent * The number of blank spaces to insert at the beginning of the returned string. Ignored if negative. * * @param rightMargin * If positive, newlines will be inserted to try to keep the length of each line in the returned string less than * or equal to *<code>rightMargin</code>. * * @param hangingIndent * If positive, this number of spaces will be inserted immediately after each newline inserted to respect the * <code>rightMargin</code>. */ public static String help(int initialIndent, int rightMargin, int hangingIndent) { return irOptions.help(initialIndent, rightMargin, hangingIndent); } }
4,104
32.92562
125
java
soot
soot-master/src/main/java/soot/util/cfgcmd/CFGOptionMatcher.java
package soot.util.cfgcmd; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 John Jorgensen * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.CompilationDeathException; /** * A class used by CFG utilities that need to match different option strings with classes that implement those options. * * A <code>CFGOptionMatcher</code> maintains a set of named options, and provides a means for matching abbreviated option * values against those names. */ public class CFGOptionMatcher { private static final Logger logger = LoggerFactory.getLogger(CFGOptionMatcher.class); /** * The type stored within a <code>CFGOptionMatcher</code>. Options to be stored in a <code>CFGOptionMatcher</code> must * extend this class. */ public static abstract class CFGOption { private final String name; protected CFGOption(String name) { this.name = name; } public String name() { return name; } }; private final CFGOption[] options; /** * Creates a CFGOptionMatcher. * * @param options * The set of command options to be stored. */ public CFGOptionMatcher(CFGOption[] options) { this.options = options; } /** * Searches the options in this <code>CFGOptionMatcher</code> looking for one whose name begins with the passed string * (ignoring the case of letters in the string). * * @param quarry * The string to be matched against the stored option names. * * @return The matching {@link CFGOption}, if exactly one of the stored option names begins with <code>quarry</code>. * * @throws soot.CompilationDeathException * if <code>quarry</code> matches none of the option names, or if it matches more than one. */ public CFGOption match(String quarry) throws soot.CompilationDeathException { String uncasedQuarry = quarry.toLowerCase(); int match = -1; for (int i = 0; i < options.length; i++) { String uncasedName = options[i].name().toLowerCase(); if (uncasedName.startsWith(uncasedQuarry)) { if (match == -1) { match = i; } else { logger.debug("" + quarry + " is ambiguous; it matches " + options[match].name() + " and " + options[i].name()); throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED, "Option parse error"); } } } if (match == -1) { logger.debug("\"" + quarry + "\"" + " does not match any value."); throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED, "Option parse error"); } else { return options[match]; } } /** * Returns a string containing the names of all the options in this <code>CFGOptionMatcher</code>, separated by '|' * characters. The string is intended for use in help messages. * * @param initialIndent * The number of blank spaces to insert at the beginning of the returned string. Ignored if negative. * * @param rightMargin * If positive, newlines will be inserted to try to keep the length of each line in the returned string less than * or equal to <code>rightMargin</code>. * * @param hangingIndent * If positive, this number of spaces will be inserted immediately after each newline inserted to respect the * <code>rightMargin</code>. */ public String help(int initialIndent, int rightMargin, int hangingIndent) { StringBuilder newLineBuf = new StringBuilder(2 + rightMargin); newLineBuf.append('\n'); if (hangingIndent < 0) { hangingIndent = 0; } for (int i = 0; i < hangingIndent; i++) { newLineBuf.append(' '); } String newLine = newLineBuf.toString(); StringBuilder result = new StringBuilder(); int lineLength = 0; for (int i = 0; i < initialIndent; i++) { lineLength++; result.append(' '); } for (int i = 0; i < options.length; i++) { if (i > 0) { result.append('|'); lineLength++; } String name = options[i].name(); int nameLength = name.length(); if ((lineLength + nameLength) > rightMargin) { result.append(newLine); lineLength = hangingIndent; } result.append(name); lineLength += nameLength; } return result.toString(); } }
5,090
32.493421
124
java
soot
soot-master/src/main/java/soot/util/cfgcmd/CFGToDotGraph.java
package soot.util.cfgcmd; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 John Jorgensen * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.Comparator; import java.util.HashMap; import java.util.Iterator; import soot.Body; import soot.BriefUnitPrinter; import soot.LabeledUnitPrinter; import soot.Unit; import soot.toolkits.exceptions.ThrowableSet; import soot.toolkits.graph.Block; import soot.toolkits.graph.BlockGraph; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.DominatorNode; import soot.toolkits.graph.ExceptionalGraph; import soot.toolkits.graph.ExceptionalGraph.ExceptionDest; import soot.toolkits.graph.UnitGraph; import soot.util.dot.DotGraph; import soot.util.dot.DotGraphAttribute; import soot.util.dot.DotGraphConstants; import soot.util.dot.DotGraphEdge; import soot.util.dot.DotGraphNode; /** * Class that creates a {@link DotGraph} visualization of a control flow graph. */ public class CFGToDotGraph { private boolean onePage; // in one or several 8.5x11 pages. private boolean isBrief; private boolean showExceptions; private DotGraphAttribute unexceptionalControlFlowAttr; private DotGraphAttribute exceptionalControlFlowAttr; private DotGraphAttribute exceptionEdgeAttr; private DotGraphAttribute headAttr; private DotGraphAttribute tailAttr; /** * <p> * Returns a CFGToDotGraph converter which will draw the graph as a single arbitrarily-sized page, with full-length node * labels. * </p> * * <p> * If asked to draw a <code>ExceptionalGraph</code>, the converter will identify the exceptions that will be thrown. By * default, it will distinguish different edges by coloring regular control flow edges black, exceptional control flow * edges red, and thrown exception edges light gray. Head and tail nodes are filled in, head nodes with gray, and tail * nodes with light gray. * </p> */ public CFGToDotGraph() { setOnePage(true); setBriefLabels(false); setShowExceptions(true); setUnexceptionalControlFlowAttr("color", "black"); setExceptionalControlFlowAttr("color", "red"); setExceptionEdgeAttr("color", "lightgray"); setHeadAttr("fillcolor", "gray"); setTailAttr("fillcolor", "lightgray"); } /** * Specify whether to split the graph into pages. * * @param onePage * indicates whether to produce the graph as a single, arbitrarily-sized page (if <code>onePage</code> is * <code>true</code>) or several 8.5x11-inch pages (if <code>onePage</code> is <code>false</code>). */ public void setOnePage(boolean onePage) { this.onePage = onePage; } /** * Specify whether to abbreviate the text in node labels. This is most relevant when the nodes represent basic blocks: * abbreviated node labels contain only a numeric label for the block, while unabbreviated labels contain the code of its * instructions. * * @param useBrief * indicates whether to abbreviate the text of node labels. */ public void setBriefLabels(boolean useBrief) { this.isBrief = useBrief; } /** * Specify whether the graph should depict the exceptions which each node may throw, in the form of an edge from the * throwing node to the handler (if any), labeled with the possible exception types. This parameter has an effect only when * drawing <code>ExceptionalGraph</code>s. * * @param showExceptions * indicates whether to show possible exceptions and their handlers. */ public void setShowExceptions(boolean showExceptions) { this.showExceptions = showExceptions; } /** * Specify the dot graph attribute to use for regular control flow edges. This parameter has an effect only when drawing * <code>ExceptionalGraph</code>s. * * @param id * The attribute name, for example "style" or "color". * * @param value * The attribute value, for example "solid" or "black". * * @see <a href="http://www.research.att.com/sw/tools/graphviz/dotguide.pdf">"Drawing graphs with dot"</a> */ public void setUnexceptionalControlFlowAttr(String id, String value) { unexceptionalControlFlowAttr = new DotGraphAttribute(id, value); } /** * Specify the dot graph attribute to use for exceptional control flow edges. This parameter has an effect only when * drawing <code>ExceptionalGraph</code>s. * * @param id * The attribute name, for example "style" or "color". * * @param value * The attribute value, for example "dashed" or "red". * * @see <a href="http://www.research.att.com/sw/tools/graphviz/dotguide.pdf">"Drawing graphs with dot"</a> */ public void setExceptionalControlFlowAttr(String id, String value) { exceptionalControlFlowAttr = new DotGraphAttribute(id, value); } /** * Specify the dot graph attribute to use for edges depicting the exceptions each node may throw, and their handlers. This * parameter has an effect only when drawing <code>ExceptionalGraph</code>s. * * @param id * The attribute name, for example "style" or "color". * * @param value * The attribute value, for example "dotted" or "lightgray". * * @see <a href="http://www.research.att.com/sw/tools/graphviz/dotguide.pdf">"Drawing graphs with dot"</a> */ public void setExceptionEdgeAttr(String id, String value) { exceptionEdgeAttr = new DotGraphAttribute(id, value); } /** * Specify the dot graph attribute to use for head nodes (in addition to filling in the nodes). * * @param id * The attribute name, for example "fillcolor". * * @param value * The attribute value, for example "gray". * * @see <a href="http://www.research.att.com/sw/tools/graphviz/dotguide.pdf">"Drawing graphs with dot"</a> */ public void setHeadAttr(String id, String value) { headAttr = new DotGraphAttribute(id, value); } /** * Specify the dot graph attribute to use for tail nodes (in addition to filling in the nodes). * * @param id * The attribute name, for example "fillcolor". * * @param value * The attribute value, for example "lightgray". * * @see <a href="http://www.research.att.com/sw/tools/graphviz/dotguide.pdf">"Drawing graphs with dot"</a> */ public void setTailAttr(String id, String value) { tailAttr = new DotGraphAttribute(id, value); } /** * Returns an {@link Iterator} over a {@link Collection} which iterates over its elements in a specified order. Used to * order lists of destination nodes consistently before adding the corresponding edges to the graph. (Maintaining a * consistent ordering of edges makes it easier to diff the dot files output for different graphs of a given method.) * * @param coll * The collection to iterator over. * * @param comp * The comparator for the ordering. * * @return An iterator which presents the elements of <code>coll</code> in the order specified by <code>comp</code>. */ private static <T> Iterator<T> sortedIterator(Collection<T> coll, Comparator<? super T> comp) { if (coll.size() <= 1) { return coll.iterator(); } else { ArrayList<T> list = new ArrayList<T>(coll); Collections.sort(list, comp); return list.iterator(); } } /** * Comparator used to order a list of nodes by the order in which they were labeled. */ private static class NodeComparator<T> implements Comparator<T> { private final DotNamer<T> namer; NodeComparator(DotNamer<T> namer) { this.namer = namer; } @Override public int compare(T o1, T o2) { return (namer.getNumber(o1) - namer.getNumber(o2)); } public boolean equal(T o1, T o2) { return (namer.getNumber(o1) == namer.getNumber(o2)); } } /** * Comparator used to order a list of ExceptionDests by the order in which their handler nodes were labeled. */ private static class ExceptionDestComparator<T> implements Comparator<ExceptionDest<T>> { private final DotNamer<T> namer; ExceptionDestComparator(DotNamer<T> namer) { this.namer = namer; } private int getValue(ExceptionDest<T> o) { T handler = o.getHandlerNode(); if (handler == null) { return Integer.MAX_VALUE; } else { return namer.getNumber(handler); } } @Override public int compare(ExceptionDest<T> o1, ExceptionDest<T> o2) { return (getValue(o1) - getValue(o2)); } public boolean equal(ExceptionDest<T> o1, ExceptionDest<T> o2) { return (getValue(o1) == getValue(o2)); } } /** * Create a <code>DotGraph</code> whose nodes and edges depict a control flow graph without distinguished exceptional * edges. * * @param graph * a <code>DirectedGraph</code> representing a CFG (probably an instance of {@link UnitGraph}, {@link BlockGraph}, * or one of their subclasses). * * @param body * the <code>Body</code> represented by <code>graph</code> (used to format the text within nodes). If no body is * available, pass <code>null</code>. * * @return a visualization of <code>graph</code>. */ public <N> DotGraph drawCFG(DirectedGraph<N> graph, Body body) { DotGraph canvas = initDotGraph(body); DotNamer<N> namer = new DotNamer<N>((int) (graph.size() / 0.7f), 0.7f); NodeComparator<N> comparator = new NodeComparator<N>(namer); // To facilitate comparisons between different graphs of the same // method, prelabel the nodes in the order they appear // in the iterator, rather than the order that they appear in the // graph traversal (so that corresponding nodes are more likely // to have the same label in different graphs of a given method). for (N node : graph) { namer.getName(node); } for (N node : graph) { canvas.drawNode(namer.getName(node)); for (Iterator<N> succsIt = sortedIterator(graph.getSuccsOf(node), comparator); succsIt.hasNext();) { N succ = succsIt.next(); canvas.drawEdge(namer.getName(node), namer.getName(succ)); } } setStyle(graph.getHeads(), canvas, namer, DotGraphConstants.NODE_STYLE_FILLED, headAttr); setStyle(graph.getTails(), canvas, namer, DotGraphConstants.NODE_STYLE_FILLED, tailAttr); if (!isBrief) { formatNodeText(body, canvas, namer); } return canvas; } /** * Create a <code>DotGraph</code> whose nodes and edges depict the control flow in a <code>ExceptionalGraph</code>, with * distinguished edges for exceptional control flow. * * @param graph * the control flow graph * * @return a visualization of <code>graph</code>. */ public <N> DotGraph drawCFG(ExceptionalGraph<N> graph) { Body body = graph.getBody(); DotGraph canvas = initDotGraph(body); DotNamer<Object> namer = new DotNamer<Object>((int) (graph.size() / 0.7f), 0.7f); @SuppressWarnings("unchecked") NodeComparator<N> nodeComparator = new NodeComparator<N>((DotNamer<N>) namer); // Prelabel nodes in iterator order, to facilitate // comparisons between graphs of a given method. for (N node : graph) { namer.getName(node); } for (N node : graph) { canvas.drawNode(namer.getName(node)); for (Iterator<N> succsIt = sortedIterator(graph.getUnexceptionalSuccsOf(node), nodeComparator); succsIt.hasNext();) { N succ = succsIt.next(); DotGraphEdge edge = canvas.drawEdge(namer.getName(node), namer.getName(succ)); edge.setAttribute(unexceptionalControlFlowAttr); } for (Iterator<N> succsIt = sortedIterator(graph.getExceptionalSuccsOf(node), nodeComparator); succsIt.hasNext();) { N succ = succsIt.next(); DotGraphEdge edge = canvas.drawEdge(namer.getName(node), namer.getName(succ)); edge.setAttribute(exceptionalControlFlowAttr); } if (showExceptions) { Collection<? extends ExceptionDest<N>> exDests = graph.getExceptionDests(node); if (exDests != null) { @SuppressWarnings("unchecked") ExceptionDestComparator<N> comp = new ExceptionDestComparator<>((DotNamer<N>) namer); for (Iterator<? extends ExceptionDest<N>> destsIt = sortedIterator(exDests, comp); destsIt.hasNext();) { ExceptionDest<N> dest = destsIt.next(); Object handlerStart = dest.getHandlerNode(); if (handlerStart == null) { // Giving each escaping exception its own, invisible // exceptional exit node produces a less cluttered // graph. handlerStart = new Object() { @Override public String toString() { return "Esc"; } }; DotGraphNode escapeNode = canvas.drawNode(namer.getName(handlerStart)); escapeNode.setStyle(DotGraphConstants.NODE_STYLE_INVISIBLE); } DotGraphEdge edge = canvas.drawEdge(namer.getName(node), namer.getName(handlerStart)); edge.setAttribute(exceptionEdgeAttr); edge.setLabel(formatThrowableSet(dest.getThrowables())); } } } } setStyle(graph.getHeads(), canvas, namer, DotGraphConstants.NODE_STYLE_FILLED, headAttr); setStyle(graph.getTails(), canvas, namer, DotGraphConstants.NODE_STYLE_FILLED, tailAttr); if (!isBrief) { formatNodeText(graph.getBody(), canvas, namer); } return canvas; } /** * A utility method that initializes a DotGraph object for use in any variety of drawCFG(). * * @param body * The <code>Body</code> that the graph will represent (used in the graph's title). If no <code>Body</code> is * available, pass <code>null</code>. * * @return a <code>DotGraph</code> for visualizing <code>body</code>. */ private DotGraph initDotGraph(Body body) { String graphname = "cfg"; if (body != null) { graphname = body.getMethod().getSubSignature(); } DotGraph canvas = new DotGraph(graphname); canvas.setGraphLabel(graphname); if (!onePage) { canvas.setPageSize(8.5, 11.0); } if (isBrief) { canvas.setNodeShape(DotGraphConstants.NODE_SHAPE_CIRCLE); } else { canvas.setNodeShape(DotGraphConstants.NODE_SHAPE_BOX); } return canvas; } /** * A utility class for assigning unique names to DotGraph entities. It maintains a mapping from CFG <code>Object</code>s to * strings identifying the corresponding nodes in generated dot source. */ @SuppressWarnings("serial") private static class DotNamer<N> extends HashMap<N, Integer> { private int nodecount = 0; DotNamer(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } String getName(N node) { Integer index = this.get(node); if (index == null) { index = nodecount++; this.put(node, index); } return index.toString(); } int getNumber(N node) { Integer index = this.get(node); if (index == null) { index = nodecount++; this.put(node, index); } return index; } } /** * A utility method which formats the text for each node in a <code>DotGraph</code> representing a CFG. * * @param body * the <code>Body</code> whose control flow is visualized in <code>canvas</code>. * * @param canvas * the <code>DotGraph</code> for visualizing the CFG. * * @param namer * provides a mapping from CFG objects to identifiers in generated dot source. */ private <N> void formatNodeText(Body body, DotGraph canvas, DotNamer<N> namer) { LabeledUnitPrinter printer = null; if (body != null) { printer = new BriefUnitPrinter(body); printer.noIndent(); } for (N node : namer.keySet()) { DotGraphNode dotnode = canvas.getNode(namer.getName(node)); if (node instanceof DominatorNode<?>) { @SuppressWarnings("unchecked") DominatorNode<N> n = (DominatorNode<N>) node; node = n.getGode(); } String nodeLabel; if (printer == null) { nodeLabel = node.toString(); } else if (node instanceof Unit) { final Unit nodeUnit = (Unit) node; nodeUnit.toString(printer); String targetLabel = printer.labels().get(nodeUnit); if (targetLabel == null) { nodeLabel = printer.toString(); } else { nodeLabel = targetLabel + ": " + printer.toString(); } } else if (node instanceof Block) { Block block = (Block) node; StringBuilder buffer = new StringBuilder(); buffer.append(block.toShortString()).append("\\n"); for (Unit unit : block) { String targetLabel = printer.labels().get(unit); if (targetLabel != null) { buffer.append(targetLabel).append(":\\n"); } unit.toString(printer); buffer.append(printer.toString()).append("\\l"); } nodeLabel = buffer.toString(); } else { nodeLabel = node.toString(); } dotnode.setLabel(nodeLabel); } } /** * Utility routine for setting some common formatting style for the {@link DotGraphNode}s corresponding to some collection * of objects. * * @param objects * is the collection of {@link Object}s whose nodes are to be styled. * @param canvas * the {@link DotGraph} containing nodes corresponding to the collection. * @param namer * maps from {@link Object} to the strings used to identify corresponding {@link DotGraphNode}s. * @param style * the style to set for each of the nodes. * @param attrib * if non-null, an additional attribute to associate with each of the nodes. */ private <N> void setStyle(Collection<? extends N> objects, DotGraph canvas, DotNamer<N> namer, String style, DotGraphAttribute attrib) { // Fill the entry and exit nodes. for (N object : objects) { DotGraphNode objectNode = canvas.getNode(namer.getName(object)); objectNode.setStyle(style); objectNode.setAttribute(attrib); } } /** * Utility routine to format the list of names in a ThrowableSet into a label for the edge showing where those Throwables * are handled. */ private String formatThrowableSet(ThrowableSet set) { String input = set.toAbbreviatedString(); // Insert line breaks between individual Throwables (dot seems to // orient these edges more or less vertically, most of the time). int inputLength = input.length(); StringBuilder result = new StringBuilder(inputLength + 5); for (int i = 0; i < inputLength; i++) { char c = input.charAt(i); if (c == '+' || c == '-') { result.append("\\l"); } result.append(c); } return result.toString(); } }
19,856
34.907776
125
java
soot
soot-master/src/main/java/soot/util/dot/AbstractDotGraphElement.java
package soot.util.dot; /*- * #%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.Collections; import java.util.LinkedHashMap; /** * @author Timothy Hoffman */ public abstract class AbstractDotGraphElement { private LinkedHashMap<String, DotGraphAttribute> attributes; /** * Sets an attribute for this dot element. * * @param id * the attribute id to be set * @param value * the attribute value */ public void setAttribute(String id, String value) { this.setAttribute(new DotGraphAttribute(id, value)); } /** * Sets an attribute for this dot element. * * @param attr * {@link DotGraphAttribute} specifying the attribute name and value */ public void setAttribute(DotGraphAttribute attr) { LinkedHashMap<String, DotGraphAttribute> attrs = this.attributes; if (attrs == null) { this.attributes = attrs = new LinkedHashMap<String, DotGraphAttribute>(); } attrs.put(attr.getID(), attr); } /** * @return unmodifiable {@link Collection} of {@link DotGraphAttribute} for this {@link AbstractDotGraphElement} */ public Collection<DotGraphAttribute> getAttributes() { LinkedHashMap<String, DotGraphAttribute> attrs = this.attributes; return attrs == null ? Collections.emptyList() : Collections.unmodifiableCollection(attrs.values()); } /** * @param id * @return the {@link DotGraphAttribute} with the given {@code id} */ public DotGraphAttribute getAttribute(String id) { LinkedHashMap<String, DotGraphAttribute> attrs = this.attributes; return attrs == null ? null : attrs.get(id); } /** * @param id * @return the value for the {@link DotGraphAttribute} with the given {@code id} */ public String getAttributeValue(String id) { DotGraphAttribute attr = getAttribute(id); return attr == null ? null : attr.getValue(); } /** * Removes the attribute with the given {@link id} from this dot element. * * @param id */ public void removeAttribute(String id) { LinkedHashMap<String, DotGraphAttribute> attrs = this.attributes; if (attrs != null) { attrs.remove(id); } } /** * Removes the given attribute from this dot element. * * @param attr * {@link DotGraphAttribute} specifying the attribute to remove */ public void removeAttribute(DotGraphAttribute attr) { LinkedHashMap<String, DotGraphAttribute> attrs = this.attributes; if (attrs != null) { attrs.remove(attr.getID(), attr); } } /** * Removes all attributes from this dot element. */ public void removeAllAttributes() { this.attributes = null; } /** * Sets the label for this dot element. * * @param label * a label string */ public void setLabel(String label) { label = DotGraphUtility.replaceQuotes(label); label = DotGraphUtility.replaceReturns(label); this.setAttribute("label", "\"" + label + "\""); } /** * @return the label for this dot element */ public String getLabel() { return this.getAttributeValue("label"); } }
3,910
27.136691
114
java
soot
soot-master/src/main/java/soot/util/dot/DotGraph.java
package soot.util.dot; /*- * #%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.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Allow a serialized drawing, following steps: * <ol> * <li>new DotGraph</li> * <li>draw(Directed/Undirected)Edge, attachAttributes, addNode</li> * <li>plot</li> * </ol> */ public class DotGraph extends AbstractDotGraphElement implements Renderable { private static final Logger logger = LoggerFactory.getLogger(DotGraph.class); /** * The extension added to output files, exported so that clients can search for the filenames. */ public static final String DOT_EXTENSION = ".dot"; private final HashMap<String, DotGraphNode> nodes; /* draw elements are sub graphs, edges, commands */ private final List<Renderable> drawElements; private final boolean isSubGraph; private boolean dontQuoteNodeNames; private String graphname; private DotGraph(String graphname, boolean isSubGraph) { this.graphname = graphname; this.isSubGraph = isSubGraph; this.nodes = new HashMap<String, DotGraphNode>(100); this.drawElements = new LinkedList<Renderable>(); this.dontQuoteNodeNames = false; } /** * Creates a new graph for drawing. * * @param graphname, * the name used to identify the graph in the dot source. */ public DotGraph(String graphname) { this(graphname, false); } /** * Generates the drawing on canvas to the dot file. * * @param filename * the name for the output file. By convention, it should end with DOT_EXTENSION, but this is not enforced. */ public void plot(String filename) { try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename))) { render(out, 0); } catch (IOException ioe) { logger.debug(ioe.getMessage()); } } /** * Draws a directed edge (including the source and end nodes, if they have not already been drawn). * * @param from, * the source node * @param to, * the end node * @return a directed graph edge connecting {@code from} with {@code to} */ public DotGraphEdge drawEdge(String from, String to) { return drawEdge(from, to, true); } /** * Draws a undirected edge (including the nodes, if they have not already been drawn). * * @param node1 * @param node2 * * @return an undirected graph edge connecting {@code node1} with {@code node2} */ public DotGraphEdge drawUndirectedEdge(String node1, String node2) { return drawEdge(node1, node2, false); } private DotGraphEdge drawEdge(String from, String to, boolean directed) { DotGraphNode src = drawNode(from); DotGraphNode dst = drawNode(to); DotGraphEdge edge = new DotGraphEdge(src, dst, directed); this.drawElements.add(edge); return edge; } /** * Draws a node. * * @param name, * the node to draw. * @return the {@link DotGraphNode} corresponding to the specified name. */ public DotGraphNode drawNode(String name) { DotGraphNode node = getNode(name); if (node == null) { throw new RuntimeException("Assertion failed."); } if (!this.drawElements.contains(node)) { this.drawElements.add(node); } return node; } /** * Gets the graph node by name. * * @param name, * unique name of the node. * @return the node with the specified name, adding a new node to the graph if there is no such node. */ public DotGraphNode getNode(String name) { if (name == null) { return null; } DotGraphNode node = nodes.get(name); if (node == null) { node = new DotGraphNode(name, dontQuoteNodeNames); nodes.put(name, node); } return node; } /** * Checks if the graph already contains the node with the specified name. * * @param name, * unique name of the node. * * @return true if the node with the specified name is already in the graph, false otherwise */ public boolean containsNode(String name) { return name != null && nodes.containsKey(name); } /** * Checks if the graph already contains the given {@link DotGraphNode}. * * @param node * * @return true if the node is already in the graph, false otherwise */ public boolean containsNode(DotGraphNode node) { return this.drawElements.contains(node); } /** * NOTE: default is true * * @param value */ public void quoteNodeNames(boolean value) { this.dontQuoteNodeNames = !value; } /** * Sets all node shapes, see the list of node shapes in DotGraphConstants. * * @param shape, * the node shape */ public void setNodeShape(String shape) { String command = "node [shape=" + shape + "];"; this.drawElements.add(new DotGraphCommand(command)); } /** * Sets all node styles * * @param style, * the node style */ public void setNodeStyle(String style) { String command = "node [style=" + style + "];"; this.drawElements.add(new DotGraphCommand(command)); } /** * sets the size of drawing area, in inches */ public void setGraphSize(double width, double height) { String size = "\"" + width + "," + height + "\""; this.setAttribute("size", size); } /** * sets the pages size, once this is set, the generated graph will be broken into several pages. */ public void setPageSize(double width, double height) { String size = "\"" + width + ", " + height + "\""; this.setAttribute("page", size); } /** * sets the graph rotation angles */ public void setOrientation(String orientation) { this.setAttribute("orientation", orientation); } /** * sets the graph name */ public void setGraphName(String name) { this.graphname = name; } /** * NOTE: Alias for {@link #setLabel(java.lang.String)}. */ public void setGraphLabel(String label) { this.setLabel(label); } /** * sets any general attributes * * NOTE: Alias for {@link #setAttribute(java.lang.String, java.lang.String)}. * * @param id * is the attribute name. * @param value * is the attribute value. */ public void setGraphAttribute(String id, String value) { this.setAttribute(id, value); } /** * sets any general attributes * * NOTE: Alias for {@link #setAttribute(soot.util.dot.DotGraphAttribute)}. * * @param attr * a {@link DotGraphAttribute} specifying the attribute name and value. */ public void setGraphAttribute(DotGraphAttribute attr) { this.setAttribute(attr); } /** * creates a sub graph. * * NOTE: Some renderers require subgraph labels to start with "cluster". * * @return the newly created sub graph. */ public DotGraph createSubGraph(String label) { // file name is used as label of sub graph. DotGraph subgraph = new DotGraph(label, true); this.drawElements.add(subgraph); return subgraph; } /* implements renderable interface. */ @Override public void render(OutputStream out, int indent) throws IOException { // header if (!isSubGraph) { DotGraphUtility.renderLine(out, "digraph \"" + this.graphname + "\" {", indent); } else { DotGraphUtility.renderLine(out, "subgraph \"" + this.graphname + "\" {", indent); } /* render graph attributes */ for (DotGraphAttribute attr : this.getAttributes()) { DotGraphUtility.renderLine(out, attr.toString() + ';', indent + 4); } /* render elements */ for (Renderable element : this.drawElements) { element.render(out, indent + 4); } // close the description DotGraphUtility.renderLine(out, "}", indent); } }
8,740
25.730887
118
java
soot
soot-master/src/main/java/soot/util/dot/DotGraphAttribute.java
package soot.util.dot; /*- * #%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% */ /** * A class for specifying Dot graph attributes. * * @author Feng Qian */ public class DotGraphAttribute { private final String id; private final String value; public DotGraphAttribute(String id, String v) { this.id = id; this.value = v; } @Override public String toString() { return this.id + '=' + this.value; } public String getID() { return this.id; } public String getValue() { return this.value; } }
1,288
23.320755
71
java
soot
soot-master/src/main/java/soot/util/dot/DotGraphCommand.java
package soot.util.dot; /*- * #%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.IOException; import java.io.OutputStream; /** * Encodes general Dot commands. */ public class DotGraphCommand implements Renderable { private final String command; /** * @param cmd * a dot dommand string */ public DotGraphCommand(String cmd) { this.command = cmd; } /** * Implements Renderable interface. * * @param out * the output stream * @param indent * the number of indent space * @see Renderable */ @Override public void render(OutputStream out, int indent) throws IOException { DotGraphUtility.renderLine(out, command, indent); } }
1,475
24.894737
71
java
soot
soot-master/src/main/java/soot/util/dot/DotGraphConstants.java
package soot.util.dot; /*- * #%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% */ /** * Defines several constants used to generate a Dot graph. * * @author Feng Qian */ public interface DotGraphConstants { public static final String NODE_SHAPE_BOX = "box"; public static final String NODE_SHAPE_ELLIPSE = "ellipse"; public static final String NODE_SHAPE_CIRCLE = "circle"; public static final String NODE_SHAPE_DIAMOND = "diamond"; public static final String NODE_SHAPE_PLAINTEXT = "plaintext"; public static final String NODE_STYLE_SOLID = "solid"; public static final String NODE_STYLE_DASHED = "dashed"; public static final String NODE_STYLE_DOTTED = "dotted"; public static final String NODE_STYLE_BOLD = "bold"; public static final String NODE_STYLE_INVISIBLE = "invis"; public static final String NODE_STYLE_FILLED = "filled"; public static final String NODE_STYLE_DIAGONALS = "diagonals"; public static final String NODE_STYLE_ROUNDED = "rounded"; public static final String EDGE_STYLE_DOTTED = "dotted"; public static final String EDGE_STYLE_SOLID = "solid"; public static final String GRAPH_ORIENT_PORTRAIT = "portrait"; public static final String GRAPH_ORIENT_LANDSCAPE = "landscape"; }
1,987
35.814815
71
java
soot
soot-master/src/main/java/soot/util/dot/DotGraphEdge.java
package soot.util.dot; /*- * #%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.IOException; import java.io.OutputStream; import java.util.Collection; /** * Graph edges are the major elements of a graph * * @author Feng Qian */ public class DotGraphEdge extends AbstractDotGraphElement implements Renderable { private final DotGraphNode start; private final DotGraphNode end; private final boolean isDirected; /** * Draws a directed edge. * * @param src, * the source node * @param dst, * the end node */ public DotGraphEdge(DotGraphNode src, DotGraphNode dst) { this.start = src; this.end = dst; this.isDirected = true; } /** * Draws a graph edge by specifying directed or undirected. * * @param src, * the source node * @param dst, * the end node * @param directed, * the edge is directed or not */ public DotGraphEdge(DotGraphNode src, DotGraphNode dst, boolean directed) { this.start = src; this.end = dst; this.isDirected = directed; } /** * Sets the edge style. * * @param style, * a style of edge * @see DotGraphConstants */ public void setStyle(String style) { this.setAttribute("style", style); } @Override public void render(OutputStream out, int indent) throws IOException { StringBuilder line = new StringBuilder(); line.append(this.start.getName()); line.append(this.isDirected ? "->" : "--"); line.append(this.end.getName()); Collection<DotGraphAttribute> attrs = this.getAttributes(); if (!attrs.isEmpty()) { line.append(" ["); for (DotGraphAttribute attr : attrs) { line.append(attr.toString()).append(','); } line.append(']'); } line.append(';'); DotGraphUtility.renderLine(out, line.toString(), indent); } }
2,652
25.267327
81
java
soot
soot-master/src/main/java/soot/util/dot/DotGraphNode.java
package soot.util.dot; /*- * #%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.IOException; import java.io.OutputStream; import java.util.Collection; /** * A Dot graph node with various attributes. */ public class DotGraphNode extends AbstractDotGraphElement implements Renderable { private final String name; public DotGraphNode(String name) { // make any illegal name to be legal this.name = '"' + DotGraphUtility.replaceQuotes(name) + '"'; } public DotGraphNode(String name, boolean dontQuoteName) { this.name = dontQuoteName ? DotGraphUtility.replaceQuotes(name) : '"' + DotGraphUtility.replaceQuotes(name) + '"'; } public String getName() { return this.name; } public void setHTMLLabel(String label) { label = DotGraphUtility.replaceReturns(label); this.setAttribute("label", label); } public void setShape(String shape) { this.setAttribute("shape", shape); } public void setStyle(String style) { this.setAttribute("style", style); } @Override public void render(OutputStream out, int indent) throws IOException { StringBuilder line = new StringBuilder(); line.append(this.getName()); Collection<DotGraphAttribute> attrs = this.getAttributes(); if (!attrs.isEmpty()) { line.append(" ["); for (DotGraphAttribute attr : attrs) { line.append(attr.toString()).append(','); } line.append(']'); } line.append(';'); DotGraphUtility.renderLine(out, line.toString(), indent); } }
2,278
27.4875
118
java
soot
soot-master/src/main/java/soot/util/dot/DotGraphUtility.java
package soot.util.dot; /*- * #%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.IOException; import java.io.OutputStream; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DotGraphUtility { private static final Logger logger = LoggerFactory.getLogger(DotGraphUtility.class); /** * Replace any {@code "} with {@code \"}. If the {@code "} character was already escaped (i.e. {@code \"}), then the escape * character is also escaped (i.e. {@code \\\"}). * * @param original * * @return */ public static String replaceQuotes(String original) { byte[] ord = original.getBytes(); int quotes = 0; boolean escapeActive = false; for (byte element : ord) { switch (element) { case '\\': escapeActive = true; break; case '\"': quotes++; if (escapeActive) { quotes++; } // fallthrough default: escapeActive = false; break; } } if (quotes == 0) { return original; } byte[] newsrc = new byte[ord.length + quotes]; for (int i = 0, j = 0, n = ord.length; i < n; i++, j++) { if (ord[i] == '\"') { if (i > 0 && ord[i - 1] == '\\') { newsrc[j++] = (byte) '\\'; } newsrc[j++] = (byte) '\\'; } newsrc[j] = ord[i]; } /* * logger.debug("before "+original); logger.debug("after "+(new String(newsrc))); */ return new String(newsrc); } /** * Replace any return ({@code \n}) with {@code \\n}. * * @param original * * @return */ public static String replaceReturns(String original) { byte[] ord = original.getBytes(); int quotes = 0; for (byte element : ord) { if (element == '\n') { quotes++; } } if (quotes == 0) { return original; } byte[] newsrc = new byte[ord.length + quotes]; for (int i = 0, j = 0, n = ord.length; i < n; i++, j++) { if (ord[i] == '\n') { newsrc[j++] = (byte) '\\'; newsrc[j] = (byte) 'n'; } else { newsrc[j] = ord[i]; } } /* * logger.debug("before "+original); logger.debug("after "+(new String(newsrc))); */ return new String(newsrc); } public static void renderLine(OutputStream out, String content, int indent) throws IOException { char[] indentChars = new char[indent]; Arrays.fill(indentChars, ' '); StringBuilder sb = new StringBuilder(); sb.append(indentChars).append(content).append('\n'); out.write(sb.toString().getBytes()); } }
3,402
25.379845
125
java
soot
soot-master/src/main/java/soot/util/dot/Renderable.java
package soot.util.dot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 Feng Qian * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.IOException; import java.io.OutputStream; public interface Renderable { public void render(OutputStream device, int indent) throws IOException; }
982
30.709677
73
java
soot
soot-master/src/main/java/soot/util/queue/ChunkedQueue.java
package soot.util.queue; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2003 Ondrej Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * A queue of Object's. One can add objects to the queue, and they are later read by a QueueReader. One can create arbitrary * numbers of QueueReader's for a queue, and each one receives all the Object's that are added. Only objects that have not * been read by all the QueueReader's are kept. A QueueReader only receives the Object's added to the queue <b>after</b> the * QueueReader was created. * * @author Ondrej Lhotak */ @SuppressWarnings("unchecked") public class ChunkedQueue<E> { protected static final Object NULL_CONST = new Object(); protected static final Object DELETED_CONST = new Object(); protected static final int LENGTH = 60; protected Object[] q; protected int index; public ChunkedQueue() { q = new Object[LENGTH]; index = 0; } /** Add an object to the queue. */ public void add(E o) { if (o == null) { o = (E) NULL_CONST; } if (index == LENGTH - 1) { Object[] temp = new Object[LENGTH]; q[index] = temp; q = temp; index = 0; } q[index++] = o; } /** Create reader which will read objects from the queue. */ public QueueReader<E> reader() { return new QueueReader<E>((E[]) q, index); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); boolean isFirst = true; int idx = index; Object[] curArray = q; while (idx < curArray.length) { Object curObj = curArray[idx]; if (curObj == null) { break; } if (isFirst) { isFirst = false; } else { sb.append(", "); } if (curObj instanceof Object[]) { curArray = (Object[]) curObj; idx = 0; } else { sb.append(curObj.toString()); idx++; } } sb.append("]"); return sb.toString(); } }
2,665
26.204082
124
java
soot
soot-master/src/main/java/soot/util/queue/QueueReader.java
package soot.util.queue; import java.util.Collection; import java.util.Collections; /*- * #%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.NoSuchElementException; import soot.util.Invalidable; /** * A queue of Object's. One can add objects to the queue, and they are later read by a QueueReader. One can create arbitrary * numbers of QueueReader's for a queue, and each one receives all the Object's that are added. Only objects that have not * been read by all the QueueReader's are kept. A QueueReader only receives the Object's added to the queue <b>after</b> the * QueueReader was created. * * @author Ondrej Lhotak */ public class QueueReader<E> implements java.util.Iterator<E> { protected E[] q; protected int index; protected QueueReader(E[] q, int index) { this.q = q; this.index = index; } /** * Returns (and removes) the next object in the queue, or null if there are none. */ @SuppressWarnings("unchecked") public E next() { Object ret = null; do { if (q[index] == null) { throw new NoSuchElementException(); } if (index == q.length - 1) { q = (E[]) q[index]; index = 0; if (q[index] == null) { throw new NoSuchElementException(); } } ret = q[index]; if (ret == ChunkedQueue.NULL_CONST) { ret = null; } index++; } while (skip(ret)); return (E) ret; } protected boolean skip(Object ret) { if (ret instanceof Invalidable) { final Invalidable invalidable = (Invalidable) ret; if (invalidable.isInvalid()) { return true; } } return ret == ChunkedQueue.DELETED_CONST; } /** Returns true iff there is currently another object in the queue. */ @SuppressWarnings("unchecked") public boolean hasNext() { do { E ret = q[index]; if (ret == null) { return false; } if (index == q.length - 1) { q = (E[]) ret; index = 0; if (q[index] == null) { return false; } } if (skip(ret)) { index++; } else { return true; } } while (true); } /** * Removes an element from the underlying queue. This operation can only delete elements that have not yet been consumed by * this reader. * * @param o * The element to remove */ public void remove(E o) { if (o instanceof Invalidable) { ((Invalidable) o).invalidate(); return; } remove(Collections.singleton(o)); } /** * Removes elements from the underlying queue. This operation can only delete elements that have not yet been consumed by * this reader. * * @param toRemove * The elements to remove */ @SuppressWarnings("unchecked") public void remove(Collection<E> toRemove) { boolean allInvalidable = true; for (E o : toRemove) { if (!(o instanceof Invalidable)) { allInvalidable = false; continue; } ((Invalidable) o).invalidate(); } if (allInvalidable) { return; } int idx = 0; Object[] curQ = q; while (curQ[idx] != null) { // Do we need to switch to a new list? if (idx == curQ.length - 1) { curQ = (E[]) curQ[idx]; idx = 0; } // Is this the element to delete? if (toRemove.contains(curQ[idx])) { curQ[idx] = ChunkedQueue.DELETED_CONST; } // Next element idx++; } } @SuppressWarnings("unchecked") public void remove() { q[index - 1] = (E) ChunkedQueue.DELETED_CONST; } public QueueReader<E> clone() { return new QueueReader<E>(q, index); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); boolean isFirst = true; int idx = index; Object[] curArray = q; while (idx < curArray.length) { Object curObj = curArray[idx]; if (curObj == null) { break; } if (isFirst) { isFirst = false; } else { sb.append(", "); } if (curObj instanceof Object[]) { curArray = (Object[]) curObj; idx = 0; } else { sb.append(curObj.toString()); idx++; } } sb.append("]"); return sb.toString(); } }
5,075
24.004926
125
java
soot
soot-master/src/main/java/soot/validation/BodyValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Body; /** * Implement this interface if you want to provide your own body Validator */ public interface BodyValidator extends Validator<Body> { /** * Validates the given body and saves all validation errors in the given list. * * @param body * the body to check * @param exceptions * the list of exceptions */ @Override public void validate(Body body, List<ValidationException> exceptions); /** * Basic validators run essential checks and are run always if validate is called.<br> * If this method returns false and the caller of the validator respects this property,<br> * the checks will only be run if the debug or validation option is activated. * * @return whether this validator is a basic validator */ @Override public boolean isBasicValidator(); }
1,711
30.703704
93
java
soot
soot-master/src/main/java/soot/validation/CheckEscapingValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Body; import soot.SootMethodRef; import soot.Type; import soot.Unit; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; public enum CheckEscapingValidator implements BodyValidator { INSTANCE; public static CheckEscapingValidator v() { return INSTANCE; } @Override public void validate(Body body, List<ValidationException> exception) { for (Unit u : body.getUnits()) { if (u instanceof Stmt) { Stmt stmt = (Stmt) u; if (stmt.containsInvokeExpr()) { InvokeExpr iexpr = stmt.getInvokeExpr(); SootMethodRef ref = iexpr.getMethodRef(); if (ref.name().contains("'") || ref.declaringClass().getName().contains("'")) { exception.add(new ValidationException(stmt, "Escaped name found in signature")); } for (Type paramType : ref.parameterTypes()) { if (paramType.toString().contains("'")) { exception.add(new ValidationException(stmt, "Escaped name found in signature")); } } } } } } @Override public boolean isBasicValidator() { return false; } }
2,008
28.985075
94
java
soot
soot-master/src/main/java/soot/validation/CheckInitValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Body; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.toolkits.exceptions.ThrowAnalysisFactory; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.scalar.FlowSet; import soot.toolkits.scalar.InitAnalysis; public enum CheckInitValidator implements BodyValidator { INSTANCE; public static CheckInitValidator v() { return INSTANCE; } @Override public void validate(Body body, List<ValidationException> exception) { ExceptionalUnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, ThrowAnalysisFactory.checkInitThrowAnalysis(), false); InitAnalysis analysis = new InitAnalysis(g); for (Unit s : body.getUnits()) { FlowSet<Local> init = analysis.getFlowBefore(s); for (ValueBox vBox : s.getUseBoxes()) { Value v = vBox.getValue(); if (v instanceof Local) { Local l = (Local) v; if (!init.contains(l)) { exception.add( new ValidationException(s, "Local variable " + l.getName() + " is not definitively defined at this point", "Warning: Local variable " + l + " not definitely defined at " + s + " in " + body.getMethod())); } } } } } @Override public boolean isBasicValidator() { return false; } }
2,285
30.75
125
java
soot
soot-master/src/main/java/soot/validation/CheckTypesValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.ArrayType; import soot.Body; import soot.DoubleType; import soot.FloatType; import soot.IntType; import soot.LongType; import soot.NullType; import soot.PrimType; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethodRef; import soot.Type; import soot.Unit; import soot.jimple.CaughtExceptionRef; import soot.jimple.DefinitionStmt; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; public enum CheckTypesValidator implements BodyValidator { INSTANCE; public static CheckTypesValidator v() { return INSTANCE; } @Override public void validate(Body body, List<ValidationException> exception) { final String methodSuffix = " in " + body.getMethod(); for (Unit u : body.getUnits()) { String errorSuffix = " at " + u + methodSuffix; if (u instanceof DefinitionStmt) { DefinitionStmt astmt = (DefinitionStmt) u; if (!(astmt.getRightOp() instanceof CaughtExceptionRef)) { Type leftType = Type.toMachineType(astmt.getLeftOp().getType()); Type rightType = Type.toMachineType(astmt.getRightOp().getType()); checkCopy(astmt, exception, leftType, rightType, errorSuffix); } } if (u instanceof Stmt) { Stmt stmt = (Stmt) u; if (stmt.containsInvokeExpr()) { InvokeExpr iexpr = stmt.getInvokeExpr(); SootMethodRef called = iexpr.getMethodRef(); if (iexpr instanceof InstanceInvokeExpr) { InstanceInvokeExpr iiexpr = (InstanceInvokeExpr) iexpr; checkCopy(stmt, exception, called.getDeclaringClass().getType(), iiexpr.getBase().getType(), " in receiver of call" + errorSuffix); } final int argCount = iexpr.getArgCount(); if (called.getParameterTypes().size() != argCount) { exception.add(new ValidationException(stmt, "Argument count does not match the signature of the called function", "Warning: Argument count doesn't match up with signature in call" + errorSuffix)); } else { for (int i = 0; i < argCount; i++) { checkCopy(stmt, exception, Type.toMachineType(called.getParameterType(i)), Type.toMachineType(iexpr.getArg(i).getType()), " in argument " + i + " of call" + errorSuffix + " (Note: Parameters are zero-indexed)"); } } } } } } private void checkCopy(Unit stmt, List<ValidationException> exception, Type leftType, Type rightType, String errorSuffix) { if (leftType instanceof PrimType || rightType instanceof PrimType) { if (leftType instanceof IntType && rightType instanceof IntType) { return; } if (leftType instanceof LongType && rightType instanceof LongType) { return; } if (leftType instanceof FloatType && rightType instanceof FloatType) { return; } if (leftType instanceof DoubleType && rightType instanceof DoubleType) { return; } exception.add(new ValidationException(stmt, "Warning: Bad use of primitive type" + errorSuffix)); return; } if (rightType instanceof NullType) { return; } if (leftType instanceof RefType && "java.lang.Object".equals(((RefType) leftType).getClassName())) { return; } if (leftType instanceof ArrayType || rightType instanceof ArrayType) { if (leftType instanceof ArrayType && rightType instanceof ArrayType) { return; } // it is legal to assign arrays to variables of type Serializable, Cloneable or Object if (rightType instanceof ArrayType) { if (leftType.equals(RefType.v("java.io.Serializable")) || leftType.equals(RefType.v("java.lang.Cloneable")) || leftType.equals(RefType.v("java.lang.Object"))) { return; } } exception.add(new ValidationException(stmt, "Warning: Bad use of array type" + errorSuffix)); return; } if (leftType instanceof RefType && rightType instanceof RefType) { SootClass leftClass = ((RefType) leftType).getSootClass(); SootClass rightClass = ((RefType) rightType).getSootClass(); if (leftClass.isPhantom() || rightClass.isPhantom()) { return; } if (leftClass.isInterface()) { if (rightClass.isInterface()) { if (!(leftClass.getName().equals(rightClass.getName()) || Scene.v().getActiveHierarchy().isInterfaceSubinterfaceOf(rightClass, leftClass))) { exception.add(new ValidationException(stmt, "Warning: Bad use of interface type" + errorSuffix)); } } else { // No quick way to check this for now. } } else if (rightClass.isInterface()) { exception.add(new ValidationException(stmt, "Warning: trying to use interface type where non-Object class expected" + errorSuffix)); } else if (!Scene.v().getActiveHierarchy().isClassSubclassOfIncluding(rightClass, leftClass)) { exception.add(new ValidationException(stmt, "Warning: Bad use of class type" + errorSuffix)); } return; } exception.add(new ValidationException(stmt, "Warning: Bad types" + errorSuffix)); } @Override public boolean isBasicValidator() { return false; } }
6,237
35.057803
125
java
soot
soot-master/src/main/java/soot/validation/CheckVoidLocalesValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Body; import soot.Local; import soot.VoidType; public enum CheckVoidLocalesValidator implements BodyValidator { INSTANCE; public static CheckVoidLocalesValidator v() { return INSTANCE; } @Override public void validate(Body body, List<ValidationException> exception) { for (Local l : body.getLocals()) { if (l.getType() instanceof VoidType) { exception.add(new ValidationException(l, "Local " + l + " in " + body.getMethod() + " defined with void type")); } } } @Override public boolean isBasicValidator() { return false; } }
1,463
27.153846
120
java
soot
soot-master/src/main/java/soot/validation/ClassFlagsValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.SootClass; /** * Validator that checks for impossible combinations of class flags * * @author Steven Arzt * */ public enum ClassFlagsValidator implements ClassValidator { INSTANCE; public static ClassFlagsValidator v() { return INSTANCE; } @Override public void validate(SootClass sc, List<ValidationException> exceptions) { if (sc.isInterface() && sc.isEnum()) { exceptions.add(new ValidationException(sc, "Class is both an interface and an enum")); } if (sc.isSynchronized()) { exceptions.add(new ValidationException(sc, "Classes cannot be synchronized")); } } @Override public boolean isBasicValidator() { return true; } }
1,570
26.561404
92
java
soot
soot-master/src/main/java/soot/validation/ClassValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.SootClass; /** * Implement this interface if you want to provide your own class validator */ public interface ClassValidator extends Validator<SootClass> { /** * Validates the given class and saves all validation errors in the given list. * * @param sc * the class to check * @param exceptions * the list of exceptions */ @Override public void validate(SootClass sc, List<ValidationException> exceptions); /** * Basic validators run essential checks and are run always if validate is called.<br> * If this method returns false and the caller of the validator respects this property,<br> * the checks will only be run if the debug or validation option is activated. * * @return whether this validator is a basic validator */ @Override public boolean isBasicValidator(); }
1,726
30.981481
93
java
soot
soot-master/src/main/java/soot/validation/LocalsValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Body; import soot.Local; import soot.Value; import soot.ValueBox; public enum LocalsValidator implements BodyValidator { INSTANCE; public static LocalsValidator v() { return INSTANCE; } @Override /** Verifies that each Local of getUseAndDefBoxes() is in this body's locals Chain. */ public void validate(Body body, List<ValidationException> exception) { for (ValueBox vb : body.getUseBoxes()) { validateLocal(body, vb, exception); } for (ValueBox vb : body.getDefBoxes()) { validateLocal(body, vb, exception); } } private void validateLocal(Body body, ValueBox vb, List<ValidationException> exception) { Value value = vb.getValue(); if (value instanceof Local) { if (!body.getLocals().contains((Local) value)) { exception.add(new ValidationException(value, "Local not in chain : " + value + " in " + body.getMethod())); } } } @Override public boolean isBasicValidator() { return true; } }
1,866
28.171875
115
java
soot
soot-master/src/main/java/soot/validation/MethodDeclarationValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.VoidType; /** * Validates classes to make sure that all method signatures are valid * * @author Steven Arzt */ public enum MethodDeclarationValidator implements ClassValidator { INSTANCE; public static MethodDeclarationValidator v() { return INSTANCE; } @Override public void validate(SootClass sc, List<ValidationException> exceptions) { if (sc.isConcrete()) { for (SootMethod sm : sc.getMethods()) { for (Type tp : sm.getParameterTypes()) { if (tp == null) { exceptions.add(new ValidationException(sm, "Null parameter types are invalid")); } else { if (tp instanceof VoidType) { exceptions.add(new ValidationException(sm, "Void parameter types are invalid")); } if (!tp.isAllowedInFinalCode()) { exceptions.add(new ValidationException(sm, "Parameter type not allowed in final code")); } } } } } } @Override public boolean isBasicValidator() { return true; } }
1,996
27.942029
102
java
soot
soot-master/src/main/java/soot/validation/OuterClassValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashSet; import java.util.List; import java.util.Set; import soot.SootClass; /** * Validates classes to make sure that the outer class chain is not recursive * * @author Steven Arzt */ public enum OuterClassValidator implements ClassValidator { INSTANCE; public static OuterClassValidator v() { return INSTANCE; } @Override public void validate(SootClass sc, List<ValidationException> exceptions) { Set<SootClass> outerClasses = new HashSet<SootClass>(); for (SootClass curClass = sc; curClass != null;) { if (!outerClasses.add(curClass)) { exceptions.add(new ValidationException(curClass, "Circular outer class chain")); break; } curClass = curClass.hasOuterClass() ? curClass.getOuterClass() : null; } } @Override public boolean isBasicValidator() { return true; } }
1,712
27.55
88
java
soot
soot-master/src/main/java/soot/validation/TrapsValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Body; import soot.PatchingChain; import soot.Trap; import soot.Unit; public enum TrapsValidator implements BodyValidator { INSTANCE; public static TrapsValidator v() { return INSTANCE; } @Override /** Verifies that the begin, end and handler units of each trap are in this body. */ public void validate(Body body, List<ValidationException> exception) { PatchingChain<Unit> units = body.getUnits(); for (Trap t : body.getTraps()) { if (!units.contains(t.getBeginUnit())) { exception.add(new ValidationException(t.getBeginUnit(), "begin not in chain" + " in " + body.getMethod())); } if (!units.contains(t.getEndUnit())) { exception.add(new ValidationException(t.getEndUnit(), "end not in chain" + " in " + body.getMethod())); } if (!units.contains(t.getHandlerUnit())) { exception.add(new ValidationException(t.getHandlerUnit(), "handler not in chain" + " in " + body.getMethod())); } } } @Override public boolean isBasicValidator() { return true; } }
1,938
29.296875
119
java
soot
soot-master/src/main/java/soot/validation/UnitBoxesValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Body; import soot.UnitBox; public enum UnitBoxesValidator implements BodyValidator { INSTANCE; public static UnitBoxesValidator v() { return INSTANCE; } @Override /** Verifies that the UnitBoxes of this Body all point to a Unit contained within this body. */ public void validate(Body body, List<ValidationException> exception) { for (UnitBox ub : body.getAllUnitBoxes()) { if (!body.getUnits().contains(ub.getUnit())) { exception.add(new ValidationException(ub, "UnitBox points outside unitChain! to unit: " + ub.getUnit() + " in " + body.getMethod())); } } } @Override public boolean isBasicValidator() { return true; } }
1,576
28.754717
103
java
soot
soot-master/src/main/java/soot/validation/UnitValidationException.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Body; import soot.Unit; /** * This kind of validation exception can be used if a unit is the cause of an validation error. */ public class UnitValidationException extends ValidationException { private static final long serialVersionUID = 1L; /** * Creates a new ValidationException. * * @param concerned * the unit which is concerned and could be highlighted in an IDE * @param body * the body which contains the concerned unit * @param strMessage * the message to display in an IDE supporting the concerned feature * @param isWarning * whether the exception can be considered as a warning message */ public UnitValidationException(Unit concerned, Body body, String strMessage, boolean isWarning) { super(concerned, strMessage, formatMsg(strMessage, concerned, body), isWarning); } /** * Creates a new ValidationException, treated as an error. * * @param body * the body which contains the concerned unit * @param concerned * the object which is concerned and could be highlighted in an IDE; for example an unit, a SootMethod, a * SootClass or a local. * @param strMessage * the message to display in an IDE supporting the concerned feature */ public UnitValidationException(Unit concerned, Body body, String strMessage) { super(concerned, strMessage, formatMsg(strMessage, concerned, body), false); } private static String formatMsg(String s, Unit u, Body b) { StringBuilder sb = new StringBuilder(); sb.append(s).append('\n'); sb.append("in unit: ").append(u).append('\n'); sb.append("in body: \n ").append(b).append('\n'); return sb.toString(); } }
2,596
34.094595
116
java
soot
soot-master/src/main/java/soot/validation/UsesValidator.java
package soot.validation; /*- * #%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.List; import soot.Body; import soot.G; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.toolkits.exceptions.PedanticThrowAnalysis; import soot.toolkits.exceptions.ThrowAnalysis; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.LocalDefs; public enum UsesValidator implements BodyValidator { INSTANCE; public static UsesValidator v() { return INSTANCE; } @Override /** Verifies that each use in this Body has a def. */ public void validate(Body body, List<ValidationException> exception) { // Conservative validation of uses: add edges to exception handlers // even if they are not reachable. // // class C { // int a; // public void m() { // try { // a = 2; // } catch (Exception e) { // System.out.println("a: "+ a); // } // } // } // // In a graph generated from the Jimple representation there would // be no edge from "a = 2;" to "catch..." because "a = 2" can only // generate an Error, a subclass of Throwable and not of Exception. // Use of 'a' in "System.out.println" would thus trigger a 'no defs // for value' RuntimeException. // To avoid this we create an ExceptionalUnitGraph that considers all // exception handlers (even unreachable ones as the one in the code // snippet above) by using a PedanticThrowAnalysis and setting the // parameter 'omitExceptingUnitEdges' to false. // // Note that unreachable traps can be removed by setting jb.uce's // "remove-unreachable-traps" option to true. ThrowAnalysis throwAnalysis = PedanticThrowAnalysis.v(); UnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis, false); LocalDefs ld = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(g, true); Collection<Local> locals = body.getLocals(); for (Unit u : body.getUnits()) { for (ValueBox box : u.getUseBoxes()) { Value v = box.getValue(); if (v instanceof Local) { Local l = (Local) v; if (!locals.contains(l)) { String msg = "Local " + v + " is referenced here but not in body's local-chain. (" + body.getMethod() + ")"; exception.add(new ValidationException(u, msg, msg)); } if (ld.getDefsOfAt(l, u).isEmpty()) { // abroken graph is also a possible reason for undefined locals! assert graphEdgesAreValid(g, u) : "broken graph found: " + u; exception.add(new ValidationException(u, "There is no path from a definition of " + v + " to this statement.", "(" + body.getMethod() + ") no defs for value: " + l + "!")); } } } } } private boolean graphEdgesAreValid(UnitGraph g, Unit u) { for (Unit p : g.getPredsOf(u)) { if (!g.getSuccsOf(p).contains(u)) { return false; } } return true; } @Override public boolean isBasicValidator() { return false; } }
3,967
32.344538
122
java
soot
soot-master/src/main/java/soot/validation/ValidationException.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class ValidationException extends RuntimeException { private Object concerned; private String strMessage; private String strCompatibilityMessage; private boolean warning; /** * Creates a new ValidationException. * * @param concerned * the object which is concerned and could be highlighted in an IDE; for example an unit, a SootMethod, a * SootClass or a local. * @param strMessage * the message to display in an IDE supporting the concerned feature * @param strCompatibilityMessage * the compatibility message containing useful information without supporting the concerned object * @param isWarning * whether the exception can be considered as a warning message */ public ValidationException(Object concerned, String strMessage, String strCompatibilityMessage, boolean isWarning) { super(strMessage); this.strCompatibilityMessage = strCompatibilityMessage; this.strMessage = strMessage; this.concerned = concerned; this.warning = isWarning; } /** * Creates a new ValidationException, treated as an error. * * @param concerned * the object which is concerned and could be highlighted in an IDE; for example an unit, a SootMethod, a * SootClass or a local. * @param strMessage * the message to display in an IDE supporting the concerned feature * @param strCompatibilityMessage * the compatibility message containing useful information without supporting the concerned object */ public ValidationException(Object concerned, String strMessage, String strCompatibilityMessage) { this(concerned, strMessage, strCompatibilityMessage, false); } /** * Creates a new ValidationException, treated as an error. * * @param concerned * the object which is concerned and could be highlighted in an IDE; for example an unit, a SootMethod, a * SootClass or a local. * @param strCompatibilityMessage * the compatibility message containing useful information without supporting the concerned object */ public ValidationException(Object concerned, String strCompatibilityMessage) { this(concerned, strCompatibilityMessage, strCompatibilityMessage, false); } public boolean isWarning() { return warning; } public String getRawMessage() { return strMessage; } public Object getConcerned() { return concerned; } @Override public String toString() { return strCompatibilityMessage; } private static final long serialVersionUID = 1L; }
3,461
33.62
118
java
soot
soot-master/src/main/java/soot/validation/Validator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; /** * Generic interface for all types of Validators. * * @param <E> */ public interface Validator<E> { /** * Validates the given object and saves all validation errors in the given list. * * @param obj * the object to check * @param exceptions * the list of exceptions */ public void validate(E obj, List<ValidationException> exceptions); /** * Basic validators run essential checks and are run always if validate is called.<br> * If this method returns false and the caller of the validator respects this property,<br> * the checks will only be run if the debug or validation option is activated. * * @return whether this validator is a basic validator */ public boolean isBasicValidator(); }
1,635
30.461538
93
java
soot
soot-master/src/main/java/soot/validation/ValueBoxesValidator.java
package soot.validation; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.PrintStream; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; import soot.Body; import soot.Unit; import soot.ValueBox; /** * Verifies that a {@link ValueBox} is not used in more than one place. */ public enum ValueBoxesValidator implements BodyValidator { INSTANCE; public static ValueBoxesValidator v() { return INSTANCE; } @Override public void validate(Body body, List<ValidationException> exception) { boolean foundProblem = false; Set<ValueBox> set = Collections.newSetFromMap(new IdentityHashMap<ValueBox, Boolean>()); for (ValueBox vb : body.getUseAndDefBoxes()) { if (!set.add(vb)) { foundProblem = true; exception.add(new ValidationException(vb, "Aliased value box : " + vb + " in " + body.getMethod())); } } if (foundProblem) { final PrintStream err = System.err; err.println("Found a ValueBox used more than once in body of " + body.getMethod() + ":"); for (Unit u : body.getUnits()) { err.println("\t" + u); } } } @Override public boolean isBasicValidator() { return false; } }
2,028
27.985714
108
java
soot
soot-master/src/main/java/soot/xml/Attribute.java
package soot.xml; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.PrintWriter; import java.util.ArrayList; import soot.tagkit.ColorTag; import soot.tagkit.Host; import soot.tagkit.JimpleLineNumberTag; import soot.tagkit.LineNumberTag; import soot.tagkit.LinkTag; import soot.tagkit.PositionTag; import soot.tagkit.SourceLnPosTag; import soot.tagkit.StringTag; import soot.tagkit.Tag; public class Attribute { private ArrayList<ColorAttribute> colors; private ArrayList<StringAttribute> texts; private ArrayList<LinkAttribute> links; private int jimpleStartPos; private int jimpleEndPos; private int javaStartPos; private int javaEndPos; private int javaStartLn; private int javaEndLn; private int jimpleStartLn; private int jimpleEndLn; public ArrayList<ColorAttribute> colors() { return colors; } public void addColor(ColorAttribute ca) { ArrayList<ColorAttribute> colors = this.colors; if (colors == null) { this.colors = colors = new ArrayList<ColorAttribute>(); } colors.add(ca); } public void addText(StringAttribute s) { ArrayList<StringAttribute> texts = this.texts; if (texts == null) { this.texts = texts = new ArrayList<StringAttribute>(); } texts.add(s); } public void addLink(LinkAttribute la) { ArrayList<LinkAttribute> links = this.links; if (links == null) { this.links = links = new ArrayList<LinkAttribute>(); } links.add(la); } public int jimpleStartPos() { return this.jimpleStartPos; } public void jimpleStartPos(int x) { this.jimpleStartPos = x; } public int jimpleEndPos() { return this.jimpleEndPos; } public void jimpleEndPos(int x) { this.jimpleEndPos = x; } public int javaStartPos() { return this.javaStartPos; } public void javaStartPos(int x) { this.javaStartPos = x; } public int javaEndPos() { return this.javaEndPos; } public void javaEndPos(int x) { this.javaEndPos = x; } public int jimpleStartLn() { return this.jimpleStartLn; } public void jimpleStartLn(int x) { this.jimpleStartLn = x; } public int jimpleEndLn() { return this.jimpleEndLn; } public void jimpleEndLn(int x) { this.jimpleEndLn = x; } public int javaStartLn() { return this.javaStartLn; } public void javaStartLn(int x) { this.javaStartLn = x; } public int javaEndLn() { return this.javaEndLn; } public void javaEndLn(int x) { this.javaEndLn = x; } public boolean hasColor() { return this.colors != null; } public void addTag(Tag t) { if (t instanceof LineNumberTag) { int lnNum = ((LineNumberTag) t).getLineNumber(); javaStartLn(lnNum); javaEndLn(lnNum); } else if (t instanceof JimpleLineNumberTag) { JimpleLineNumberTag jlnTag = (JimpleLineNumberTag) t; jimpleStartLn(jlnTag.getStartLineNumber()); jimpleEndLn(jlnTag.getEndLineNumber()); } else if (t instanceof SourceLnPosTag) { SourceLnPosTag jlnTag = (SourceLnPosTag) t; javaStartLn(jlnTag.startLn()); javaEndLn(jlnTag.endLn()); javaStartPos(jlnTag.startPos()); javaEndPos(jlnTag.endPos()); } else if (t instanceof LinkTag) { LinkTag lt = (LinkTag) t; Host h = lt.getLink(); addLink(new LinkAttribute(lt.getInfo(), getJimpleLnOfHost(h), getJavaLnOfHost(h), lt.getClassName(), lt.getAnalysisType())); } else if (t instanceof StringTag) { StringTag st = (StringTag) t; addText(new StringAttribute(formatForXML(st.getInfo()), st.getAnalysisType())); } else if (t instanceof PositionTag) { PositionTag pt = (PositionTag) t; jimpleStartPos(pt.getStartOffset()); jimpleEndPos(pt.getEndOffset()); } else if (t instanceof ColorTag) { ColorTag ct = (ColorTag) t; addColor(new ColorAttribute(ct.getRed(), ct.getGreen(), ct.getBlue(), ct.isForeground(), ct.getAnalysisType())); } /* * else if (t instanceof SourcePositionTag){ } else if (t instanceof SourceLineNumberTag){ } */ else { addText(new StringAttribute(t.toString(), t.getName())); } } private String formatForXML(String in) { in = in.replaceAll("<", "&lt;"); in = in.replaceAll(">", "&gt;"); in = in.replaceAll("&", "&amp;"); in = in.replaceAll("\"", "&quot;"); return in; } private int getJavaLnOfHost(Host h) { for (Tag t : h.getTags()) { if (t instanceof SourceLnPosTag) { return ((SourceLnPosTag) t).startLn(); } else if (t instanceof LineNumberTag) { return ((LineNumberTag) t).getLineNumber(); } } return 0; } private int getJimpleLnOfHost(Host h) { for (Tag t : h.getTags()) { if (t instanceof JimpleLineNumberTag) { return ((JimpleLineNumberTag) t).getStartLineNumber(); } } return 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("<srcPos sline=\"").append(javaStartLn()); sb.append("\" eline=\"").append(javaEndLn()); sb.append("\" spos=\"").append(javaStartPos()); sb.append("\" epos=\"").append(javaEndPos()).append("\"/>"); sb.append("<jmpPos sline=\"").append(jimpleStartLn()); sb.append("\" eline=\"").append(jimpleEndLn()); sb.append("\" spos=\"").append(jimpleStartPos()); sb.append("\" epos=\"").append(jimpleEndPos()).append("\"/>"); return sb.toString(); } public boolean isEmpty() { return colors == null && texts == null && links == null; } public void print(PrintWriter writerOut) { if (isEmpty()) { // System.out.println("no data found for: "); // System.out.println("<srcPos sline=\""+javaStartLn()+"\" eline=\""+javaEndLn()+"\" spos=\""+javaStartPos()+"\" // epos=\""+javaEndPos()+"\"/>"); // System.out.println("<jmpPos sline=\""+jimpleStartLn()+"\" eline=\""+jimpleEndLn()+"\" spos=\""+jimpleStartPos()+"\" // epos=\""+jimpleEndPos()+"\"/>"); return; } writerOut.println("<attribute>"); writerOut.println("<srcPos sline=\"" + javaStartLn() + "\" eline=\"" + javaEndLn() + "\" spos=\"" + javaStartPos() + "\" epos=\"" + javaEndPos() + "\"/>"); writerOut.println("<jmpPos sline=\"" + jimpleStartLn() + "\" eline=\"" + jimpleEndLn() + "\" spos=\"" + jimpleStartPos() + "\" epos=\"" + jimpleEndPos() + "\"/>"); if (colors != null) { for (ColorAttribute ca : colors) { writerOut.println("<color r=\"" + ca.red() + "\" g=\"" + ca.green() + "\" b=\"" + ca.blue() + "\" fg=\"" + ca.fg() + "\" aType=\"" + ca.analysisType() + "\"/>"); } } if (texts != null) { for (StringAttribute sa : texts) { writerOut.println("<text info=\"" + sa.info() + "\" aType=\"" + sa.analysisType() + "\"/>"); } } if (links != null) { for (LinkAttribute la : links) { writerOut.println("<link label=\"" + formatForXML(la.info()) + "\" jmpLink=\"" + la.jimpleLink() + "\" srcLink=\"" + la.javaLink() + "\" clssNm=\"" + la.className() + "\" aType=\"" + la.analysisType() + "\"/>"); } } writerOut.println("</attribute>"); } }
7,965
28.835206
124
java
soot
soot-master/src/main/java/soot/xml/ColorAttribute.java
package soot.xml; /*- * #%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 ColorAttribute { private final int red; private final int green; private final int blue; private final int fg; private final String analysisType; public ColorAttribute(int red, int green, int blue, boolean fg, String type) { this.red = red; this.green = green; this.blue = blue; this.fg = fg ? 1 : 0; this.analysisType = type; } public int red() { return this.red; } public int green() { return this.green; } public int blue() { return this.blue; } public int fg() { return this.fg; } public String analysisType() { return this.analysisType; } }
1,459
22.934426
80
java
soot
soot-master/src/main/java/soot/xml/JavaAttribute.java
package soot.xml; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.PrintWriter; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.tagkit.ColorTag; import soot.tagkit.Host; import soot.tagkit.JimpleLineNumberTag; import soot.tagkit.LineNumberTag; import soot.tagkit.LinkTag; import soot.tagkit.PositionTag; import soot.tagkit.SourceLnPosTag; import soot.tagkit.SourcePositionTag; import soot.tagkit.StringTag; import soot.tagkit.Tag; public class JavaAttribute { private static final Logger logger = LoggerFactory.getLogger(JavaAttribute.class); private int startLn; private ArrayList<Tag> tags; private ArrayList<PosColorAttribute> vbAttrs; public PrintWriter writerOut; public JavaAttribute() { } public int startLn() { return this.startLn; } public void startLn(int x) { this.startLn = x; } public ArrayList<Tag> tags() { return this.tags; } public void addTag(Tag t) { ArrayList<Tag> tags = this.tags; if (tags == null) { this.tags = tags = new ArrayList<Tag>(); } tags.add(t); } public ArrayList<PosColorAttribute> vbAttrs() { return this.vbAttrs; } public void addVbAttr(PosColorAttribute vbAttr) { ArrayList<PosColorAttribute> vbAttrs = this.vbAttrs; if (vbAttrs == null) { this.vbAttrs = vbAttrs = new ArrayList<PosColorAttribute>(); } vbAttrs.add(vbAttr); } public boolean hasColorTag() { if (tags != null) { for (Tag t : tags) { if (t instanceof ColorTag) { return true; } } } if (vbAttrs != null) { for (PosColorAttribute t : vbAttrs) { if (t.hasColor()) { return true; } } } return false; } private void printAttributeTag(Tag t) { if (t instanceof LineNumberTag) { int lnNum = ((LineNumberTag) t).getLineNumber(); printJavaLnAttr(lnNum, lnNum); } else if (t instanceof JimpleLineNumberTag) { JimpleLineNumberTag jlnTag = (JimpleLineNumberTag) t; printJimpleLnAttr(jlnTag.getStartLineNumber(), jlnTag.getEndLineNumber()); } /* * else if (t instanceof SourceLineNumberTag) { SourceLineNumberTag jlnTag = (SourceLineNumberTag)t; * printJavaLnAttr(jlnTag.getStartLineNumber(), jlnTag.getEndLineNumber()); } */ else if (t instanceof LinkTag) { LinkTag lt = (LinkTag) t; Host h = lt.getLink(); printLinkAttr(formatForXML(lt.toString()), getJimpleLnOfHost(h), getJavaLnOfHost(h), lt.getClassName()); } else if (t instanceof StringTag) { printTextAttr(formatForXML(((StringTag) t).toString())); } else if (t instanceof SourcePositionTag) { SourcePositionTag pt = (SourcePositionTag) t; printSourcePositionAttr(pt.getStartOffset(), pt.getEndOffset()); } else if (t instanceof PositionTag) { PositionTag pt = (PositionTag) t; printJimplePositionAttr(pt.getStartOffset(), pt.getEndOffset()); } else if (t instanceof ColorTag) { ColorTag ct = (ColorTag) t; printColorAttr(ct.getRed(), ct.getGreen(), ct.getBlue(), ct.isForeground()); } else { printTextAttr(t.toString()); } } private void printJavaLnAttr(int start_ln, int end_ln) { writerOut.println("<javaStartLn>" + start_ln + "</javaStartLn>"); writerOut.println("<javaEndLn>" + end_ln + "</javaEndLn>"); } private void printJimpleLnAttr(int start_ln, int end_ln) { writerOut.println("<jimpleStartLn>" + start_ln + "</jimpleStartLn>"); writerOut.println("<jimpleEndLn>" + end_ln + "</jimpleEndLn>"); } private void printTextAttr(String text) { writerOut.println("<text>" + text + "</text>"); } private void printLinkAttr(String label, int jimpleLink, int javaLink, String className) { writerOut.println("<link_attribute>"); writerOut.println("<link_label>" + label + "</link_label>"); writerOut.println("<jimple_link>" + jimpleLink + "</jimple_link>"); writerOut.println("<java_link>" + javaLink + "</java_link>"); writerOut.println("<className>" + className + "</className>"); writerOut.println("</link_attribute>"); } private void startPrintValBoxAttr() { writerOut.println("<value_box_attribute>"); } private void printSourcePositionAttr(int start, int end) { writerOut.println("<javaStartPos>" + start + "</javaStartPos>"); writerOut.println("<javaEndPos>" + end + "</javaEndPos>"); } private void printJimplePositionAttr(int start, int end) { writerOut.println("<jimpleStartPos>" + start + "</jimpleStartPos>"); writerOut.println("<jimpleEndPos>" + end + "</jimpleEndPos>"); } private void printColorAttr(int r, int g, int b, boolean fg) { writerOut.println("<red>" + r + "</red>"); writerOut.println("<green>" + g + "</green>"); writerOut.println("<blue>" + b + "</blue>"); writerOut.println(fg ? "<fg>1</fg>" : "<fg>0</fg>"); } private void endPrintValBoxAttr() { writerOut.println("</value_box_attribute>"); } // prints all tags public void printAllTags(PrintWriter writer) { this.writerOut = writer; if (tags != null) { for (Tag t : tags) { printAttributeTag(t); } } if (vbAttrs != null) { for (PosColorAttribute attr : vbAttrs) { if (attr.hasColor()) { startPrintValBoxAttr(); printSourcePositionAttr(attr.javaStartPos(), attr.javaEndPos()); printJimplePositionAttr(attr.jimpleStartPos(), attr.jimpleEndPos()); // printColorAttr(attr.color().red(), attr.color().green(), attr.color().blue(), attr.color().fg()); endPrintValBoxAttr(); } } } } // prints only tags related to strings and links (no pos tags) public void printInfoTags(PrintWriter writer) { this.writerOut = writer; for (Tag t : tags) { printAttributeTag(t); } } private String formatForXML(String in) { in = in.replaceAll("<", "&lt;"); in = in.replaceAll(">", "&gt;"); in = in.replaceAll("&", "&amp;"); return in; } private int getJavaLnOfHost(Host h) { for (Tag t : h.getTags()) { if (t instanceof SourceLnPosTag) { return ((SourceLnPosTag) t).startLn(); } else if (t instanceof LineNumberTag) { return ((LineNumberTag) t).getLineNumber(); } } return 0; } private int getJimpleLnOfHost(Host h) { for (Tag t : h.getTags()) { if (t instanceof JimpleLineNumberTag) { return ((JimpleLineNumberTag) t).getStartLineNumber(); } } return 0; } }
7,330
29.67364
110
java
soot
soot-master/src/main/java/soot/xml/Key.java
package soot.xml; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.PrintWriter; public class Key { private final int red; private final int green; private final int blue; private final String key; private String aType; public Key(int r, int g, int b, String k) { this.red = r; this.green = g; this.blue = b; this.key = k; } public int red() { return this.red; } public int green() { return this.green; } public int blue() { return this.blue; } public String key() { return this.key; } public String aType() { return this.aType; } public void aType(String s) { this.aType = s; } public void print(PrintWriter writerOut) { writerOut.println("<key red=\"" + red() + "\" green=\"" + green() + "\" blue=\"" + blue() + "\" key=\"" + key() + "\" aType=\"" + aType() + "\"/>"); } }
1,645
22.183099
115
java
soot
soot-master/src/main/java/soot/xml/LinkAttribute.java
package soot.xml; /*- * #%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 LinkAttribute { private final String info; private final int jimpleLink; private final int javaLink; private final String className; private final boolean isJimpleLink; private final boolean isJavaLink; private final String analysisType; public LinkAttribute(String info, int jimpleLink, int javaLink, String className, String type) { this.info = info; this.jimpleLink = jimpleLink; this.javaLink = javaLink; this.className = className; this.isJimpleLink = true; this.isJavaLink = true; this.analysisType = type; } public String info() { return this.info; } public int jimpleLink() { return this.jimpleLink; } public int javaLink() { return this.javaLink; } public String className() { return this.className; } public boolean isJimpleLink() { return this.isJimpleLink; } public boolean isJavaLink() { return this.isJavaLink; } public String analysisType() { return this.analysisType; } }
1,831
24.09589
98
java
soot
soot-master/src/main/java/soot/xml/PosColorAttribute.java
package soot.xml; /*- * #%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 PosColorAttribute { private ColorAttribute color; private int jimpleStartPos; private int jimpleEndPos; private int javaStartPos; private int javaEndPos; private int javaStartLn; private int javaEndLn; private int jimpleStartLn; private int jimpleEndLn; public PosColorAttribute() { } public ColorAttribute color() { return this.color; } public void color(ColorAttribute c) { this.color = c; } public int jimpleStartPos() { return this.jimpleStartPos; } public void jimpleStartPos(int x) { this.jimpleStartPos = x; } public int jimpleEndPos() { return this.jimpleEndPos; } public void jimpleEndPos(int x) { this.jimpleEndPos = x; } public int javaStartPos() { return this.javaStartPos; } public void javaStartPos(int x) { this.javaStartPos = x; } public int javaEndPos() { return this.javaEndPos; } public void javaEndPos(int x) { this.javaEndPos = x; } public int jimpleStartLn() { return this.jimpleStartLn; } public void jimpleStartLn(int x) { this.jimpleStartLn = x; } public int jimpleEndLn() { return this.jimpleEndLn; } public void jimpleEndLn(int x) { this.jimpleEndLn = x; } public int javaStartLn() { return this.javaStartLn; } public void javaStartLn(int x) { this.javaStartLn = x; } public int javaEndLn() { return this.javaEndLn; } public void javaEndLn(int x) { this.javaEndLn = x; } public boolean hasColor() { return color() != null; } }
2,381
19.534483
71
java
soot
soot-master/src/main/java/soot/xml/StringAttribute.java
package soot.xml; /*- * #%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 StringAttribute { private final String info; private final String analysisType; public StringAttribute(String info, String type) { this.info = info; this.analysisType = type; } public String info() { return this.info; } public String analysisType() { return this.analysisType; } }
1,149
25.744186
71
java
soot
soot-master/src/main/java/soot/xml/TagCollector.java
package soot.xml; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import soot.Body; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Unit; import soot.ValueBox; import soot.tagkit.Host; import soot.tagkit.JimpleLineNumberTag; import soot.tagkit.KeyTag; import soot.tagkit.SourceFileTag; import soot.tagkit.Tag; public class TagCollector { private final ArrayList<Attribute> attributes; private final ArrayList<Key> keys; public TagCollector() { this.attributes = new ArrayList<Attribute>(); this.keys = new ArrayList<Key>(); } public boolean isEmpty() { return attributes.isEmpty() && keys.isEmpty(); } /** * Convenience function for <code>collectTags(sc, true)</code>. * * @param sc */ public void collectTags(SootClass sc) { collectTags(sc, true); } /** * Collect tags from all fields and methods of <code>sc</code>. If <code>includeBodies</code> is true, then tags are also * collected from method bodies. * * @param sc * The class from which to collect the tags. * @param includeBodies */ public void collectTags(SootClass sc, boolean includeBodies) { // tag the class collectClassTags(sc); // tag fields for (SootField sf : sc.getFields()) { collectFieldTags(sf); } // tag methods for (SootMethod sm : sc.getMethods()) { collectMethodTags(sm); if (includeBodies && sm.hasActiveBody()) { collectBodyTags(sm.getActiveBody()); } } } public void collectKeyTags(SootClass sc) { for (Tag next : sc.getTags()) { if (next instanceof KeyTag) { KeyTag kt = (KeyTag) next; Key k = new Key(kt.red(), kt.green(), kt.blue(), kt.key()); k.aType(kt.analysisType()); keys.add(k); } } } public void printKeys(PrintWriter writerOut) { for (Key k : keys) { k.print(writerOut); } } private void addAttribute(Attribute a) { if (!a.isEmpty()) { attributes.add(a); } } private void collectHostTags(Host h) { collectHostTags(h, t -> true); } private void collectHostTags(Host h, Predicate<Tag> include) { List<Tag> tags = h.getTags(); if (!tags.isEmpty()) { Attribute a = new Attribute(); for (Tag t : tags) { if (include.test(t)) { a.addTag(t); } } addAttribute(a); } } public void collectClassTags(SootClass sc) { // All classes are tagged with their source files which // is not worth outputing because it can be inferred from // other information (like the name of the XML file). collectHostTags(sc, t -> !(t instanceof SourceFileTag)); } public void collectFieldTags(SootField sf) { collectHostTags(sf); } public void collectMethodTags(SootMethod sm) { if (sm.hasActiveBody()) { collectHostTags(sm); } } public synchronized void collectBodyTags(Body b) { for (Unit u : b.getUnits()) { Attribute ua = new Attribute(); JimpleLineNumberTag jlnt = null; for (Tag t : u.getTags()) { ua.addTag(t); if (t instanceof JimpleLineNumberTag) { jlnt = (JimpleLineNumberTag) t; } // System.out.println("adding unit tag: "+t); } addAttribute(ua); for (ValueBox vb : u.getUseAndDefBoxes()) { // PosColorAttribute attr = new PosColorAttribute(); if (!vb.getTags().isEmpty()) { Attribute va = new Attribute(); for (Tag t : vb.getTags()) { // System.out.println("adding vb tag: "+t); va.addTag(t); // System.out.println("vb: "+vb.getValue()+" tag: "+t); if (jlnt != null) { va.addTag(jlnt); } } // also here add line tags of the unit addAttribute(va); // System.out.println("added att: "+va); } } } } public void printTags(PrintWriter writerOut) { for (Attribute a : attributes) { // System.out.println("will print attr: "+a); a.print(writerOut); } } }
4,977
25.620321
123
java
soot
soot-master/src/main/java/soot/xml/XMLNode.java
package soot.xml; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 David Eng * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** XML helper */ public class XMLNode extends XMLRoot { // constants public static final int TAG_STRING_BUFFER = 4096; // node pointers public XMLNode next = null; // -> to next node public XMLNode prev = null; // -> to previous node public XMLNode parent = null; // -> to parent node public XMLNode child = null; // -> to child node public XMLRoot root = null; // -> to root node public XMLNode(String in_name, String in_value, String[] in_attributes, String[] in_values) { this.name = in_name; this.value = in_value; this.attributes = in_attributes; this.values = in_values; } public XMLNode(XMLNode node) { if (node != null) { this.name = node.name; this.value = node.value; this.attributes = node.attributes; this.values = node.values; if (node.child != null) { this.child = (XMLNode) node.child.clone(); } if (node.next != null) { this.next = (XMLNode) node.next.clone(); } } } @Override public Object clone() { return new XMLNode(this); } public String toPostString() { return toPostString(""); } public String toPostString(String indent) { if (next != null) { return this.toString(indent) + next.toPostString(indent); } else { return this.toString(indent); } } // returns the number of children public int getNumberOfChildren() { int count = 0; for (XMLNode current = child; current != null; current = current.next) { count++; } return count; } // adds an attribute to an element public XMLNode addAttribute(String attribute, String value) { { String[] oldAttrs = this.attributes; int oldAttrsLen = oldAttrs.length; String[] newAttrs = new String[oldAttrsLen + 1]; System.arraycopy(oldAttrs, 0, newAttrs, 0, oldAttrsLen); newAttrs[oldAttrsLen] = attribute.trim(); this.attributes = newAttrs; } { String[] oldValues = this.values; final int oldValuesLen = oldValues.length; String[] newValues = new String[oldValuesLen + 1]; System.arraycopy(oldValues, 0, newValues, 0, oldValuesLen); newValues[oldValuesLen] = value.trim(); this.values = newValues; } return this; } // XML Printing and formatting // @Override public String toString() { return toString(""); } public String toString(String indent) { final String xmlName = eliminateSpaces(name); // <tag StringBuilder beginTag = new StringBuilder(TAG_STRING_BUFFER); beginTag.append(indent); beginTag.append('<').append(xmlName); if (attributes != null) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].length() > 0) { // <tag attr=" String attributeName = eliminateSpaces(attributes[i].trim()); // TODO: attribute name should be one word! squish it? beginTag.append(' ').append(attributeName).append("=\""); // <tag attr="val" // if there is no value associated with this attribute, // consider it a <hr NOSHADE> style attribute; // use the default: <hr NOSHADE="NOSHADE"> if (values != null) { if (i < values.length) { beginTag.append(values[i].trim()).append('"'); } else { beginTag.append(attributeName.trim()).append('"'); } } } } } // <tag attr="val"...> or <tag attr="val".../> // if there is no value in this element AND this element has no children, it can be a single tag <.../> final String endTag; if (child == null && value.isEmpty()) { beginTag.append(" />\n"); endTag = null; } else { beginTag.append('>'); // endTag = new StringBuilder(TAG_STRING_BUFFER); endTag = "</" + xmlName + ">\n"; } if (!value.isEmpty()) { beginTag.append(value); } if (child != null) { beginTag.append('\n'); beginTag.append(child.toPostString(indent + " ")); beginTag.append(indent); } if (endTag != null) { beginTag.append(endTag); } return beginTag.toString(); } // CONSTRUCTION ROUTINES // // // insert element before the node here public XMLNode insertElement(String name) { return insertElement(name, "", "", ""); } public XMLNode insertElement(String name, String value) { return insertElement(name, value, "", ""); } public XMLNode insertElement(String name, String value, String[] attributes) { return insertElement(name, value, attributes, null); } public XMLNode insertElement(String name, String[] attributes, String[] values) { return insertElement(name, "", attributes, values); } public XMLNode insertElement(String name, String value, String attribute, String attributeValue) { return insertElement(name, value, new String[] { attribute }, new String[] { attributeValue }); } public XMLNode insertElement(String name, String value, String[] attributes, String[] values) { XMLNode newnode = new XMLNode(name, value, attributes, values); if (this.parent != null) { // check if this node is the first of a chain if (this.parent.child.equals(this)) { this.parent.child = newnode; } } else { // if it has no parent it might be a root's child if (this.prev == null) { this.root.child = newnode; } } newnode.child = null; newnode.parent = this.parent; newnode.prev = this.prev; if (newnode.prev != null) { newnode.prev.next = newnode; } this.prev = newnode; newnode.next = this; return newnode; } // add element to end of tree @Override public XMLNode addElement(String name) { return addElement(name, "", "", ""); } @Override public XMLNode addElement(String name, String value) { return addElement(name, value, "", ""); } @Override public XMLNode addElement(String name, String value, String[] attributes) { return addElement(name, value, attributes, null); } @Override public XMLNode addElement(String name, String[] attributes, String[] values) { return addElement(name, "", attributes, values); } @Override public XMLNode addElement(String name, String value, String attribute, String attributeValue) { return addElement(name, value, new String[] { attribute }, new String[] { attributeValue }); } @Override public XMLNode addElement(String name, String value, String[] attributes, String[] values) { XMLNode newnode = new XMLNode(name, value, attributes, values); return addElement(newnode); } public XMLNode addElement(XMLNode node) { XMLNode current = this; while (current.next != null) { current = current.next; } current.next = node; node.prev = current; return node; } // add one level of children public XMLNode addChildren(XMLNode children) { XMLNode current = children; while (current != null) { current.parent = this; current = current.next; } if (this.child == null) { this.child = children; } else { current = this.child; while (current.next != null) { current = current.next; } current.next = children; } return this; } // add element to end of tree public XMLNode addChild(String name) { return addChild(name, "", "", ""); } public XMLNode addChild(String name, String value) { return addChild(name, value, "", ""); } public XMLNode addChild(String name, String value, String[] attributes) { return addChild(name, value, attributes, null); } public XMLNode addChild(String name, String[] attributes, String[] values) { return addChild(name, "", attributes, values); } public XMLNode addChild(String name, String value, String attribute, String attributeValue) { return addChild(name, value, new String[] { attribute }, new String[] { attributeValue }); } public XMLNode addChild(String name, String value, String[] attributes, String[] values) { XMLNode newnode = new XMLNode(name, value, attributes, values); return addChild(newnode); } public XMLNode addChild(XMLNode node) { if (this.child == null) { this.child = node; node.parent = this; } else { XMLNode current = this.child; while (current.next != null) { current = current.next; } current.next = node; node.prev = current; node.parent = this; } return node; } private String eliminateSpaces(String str) { return str.trim().replace(' ', '_'); } }
9,468
27.781155
107
java
soot
soot-master/src/main/java/soot/xml/XMLPrinter.java
package soot.xml; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 David Eng * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.G; import soot.LabeledUnitPrinter; import soot.Local; import soot.Main; import soot.Modifier; import soot.NormalUnitPrinter; import soot.Scene; import soot.Singletons; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Trap; import soot.Type; import soot.Unit; import soot.ValueBox; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.scalar.LiveLocals; import soot.toolkits.scalar.SimpleLiveLocals; import soot.util.Chain; /** XML printing routines all XML output comes through here */ public class XMLPrinter { private static final Logger logger = LoggerFactory.getLogger(XMLPrinter.class); // xml and dtd header public static final String xmlHeader = "<?xml version=\"1.0\" ?>\n"; public static final String dtdHeader = "<!DOCTYPE jil SYSTEM \"http://www.sable.mcgill.ca/~flynn/jil/jil10.dtd\">\n"; // xml tree public XMLRoot root; public XMLPrinter(Singletons.Global g) { } public static XMLPrinter v() { return G.v().soot_xml_XMLPrinter(); } // returns the buffer - this is the XML output @Override public String toString() { if (root != null) { return root.toString(); } else { throw new RuntimeException("Error generating XML!"); } } // add single element <...>...</...> public XMLNode addElement(String name) { return addElement(name, "", "", ""); } public XMLNode addElement(String name, String value) { return addElement(name, value, "", ""); } public XMLNode addElement(String name, String value, String[] attributes) { return addElement(name, value, attributes, null); } public XMLNode addElement(String name, String value, String attribute, String attributeValue) { return addElement(name, value, new String[] { attribute }, new String[] { attributeValue }); } public XMLNode addElement(String name, String value, String[] attributes, String[] values) { return root.addElement(name, value, attributes, values); } /** * Prints out an XML representation of the given SootClass with each method Body printed in the textual format * corresponding to the IR used to encode the Body. * * @param cl * @param out * a PrintWriter instance to print to. */ public void printJimpleStyleTo(SootClass cl, PrintWriter out) { this.root = new XMLRoot(); final Scene sc = Scene.v(); final XMLNode xmlClassNode; // Print XML class output { // add header nodes XMLNode xmlRootNode = root.addElement("jil"); // add history node // TODO: grab the software version and command line StringBuilder cmdlineStr = new StringBuilder(); for (String element : Main.v().cmdLineArgs) { cmdlineStr.append(element).append(' '); } String dateStr = new Date().toString(); XMLNode xmlHistoryNode = xmlRootNode.addChild("history"); xmlHistoryNode.addAttribute("created", dateStr); xmlHistoryNode.addChild("soot", new String[] { "version", "command", "timestamp" }, new String[] { Main.versionString, cmdlineStr.toString().trim(), dateStr }); // add class root node xmlClassNode = xmlRootNode.addChild("class", new String[] { "name" }, new String[] { sc.quotedNameOf(cl.getName()) }); if (!cl.getPackageName().isEmpty()) { xmlClassNode.addAttribute("package", cl.getPackageName()); } if (cl.hasSuperclass()) { xmlClassNode.addAttribute("extends", sc.quotedNameOf(cl.getSuperclass().getName())); } // add modifiers subnode XMLNode xmlTempNode = xmlClassNode.addChild("modifiers"); for (StringTokenizer st = new StringTokenizer(Modifier.toString(cl.getModifiers())); st.hasMoreTokens();) { xmlTempNode.addChild("modifier", new String[] { "name" }, new String[] { st.nextToken() }); } xmlTempNode.addAttribute("count", String.valueOf(xmlTempNode.getNumberOfChildren())); } // Print interfaces { XMLNode xmlTempNode = xmlClassNode.addChild("interfaces", "", new String[] { "count" }, new String[] { String.valueOf(cl.getInterfaceCount()) }); for (SootClass next : cl.getInterfaces()) { xmlTempNode.addChild("implements", "", new String[] { "class" }, new String[] { sc.quotedNameOf(next.getName()) }); } } // Print fields { XMLNode xmlTempNode = xmlClassNode.addChild("fields", "", new String[] { "count" }, new String[] { String.valueOf(cl.getFieldCount()) }); int i = 0; for (SootField f : cl.getFields()) { if (!f.isPhantom()) { // add the field node XMLNode xmlFieldNode = xmlTempNode.addChild("field", "", new String[] { "id", "name", "type" }, new String[] { String.valueOf(i++), f.getName(), f.getType().toString() }); XMLNode xmlModifiersNode = xmlFieldNode.addChild("modifiers"); for (StringTokenizer st = new StringTokenizer(Modifier.toString(f.getModifiers())); st.hasMoreTokens();) { xmlModifiersNode.addChild("modifier", new String[] { "name" }, new String[] { st.nextToken() }); } xmlModifiersNode.addAttribute("count", String.valueOf(xmlModifiersNode.getNumberOfChildren())); } } } // Print methods { XMLNode methodsNode = xmlClassNode.addChild("methods", new String[] { "count" }, new String[] { String.valueOf(cl.getMethodCount()) }); for (Iterator<SootMethod> methodIt = cl.methodIterator(); methodIt.hasNext();) { SootMethod method = methodIt.next(); if (!method.isPhantom()) { if (!Modifier.isAbstract(method.getModifiers()) && !Modifier.isNative(method.getModifiers())) { if (!method.hasActiveBody()) { throw new RuntimeException("method " + method.getName() + " has no active body!"); } else { Body body = method.getActiveBody(); body.validate(); printStatementsInBody(body, methodsNode); } } } } } out.println(toString()); } private void printStatementsInBody(Body body, XMLNode methodsNode) { final LabeledUnitPrinter up = new NormalUnitPrinter(body); final Map<Unit, String> stmtToName = up.labels(); final Chain<Unit> units = body.getUnits(); String currentLabel = "default"; long labelCount = 0; /* * // for invokes, add a list of potential targets if (!Scene.v().hasActiveInvokeGraph()) { * InvokeGraphBuilder.v().transform("jil.igb"); } * * // build an invoke graph based on class hiearchy analysis InvokeGraph igCHA = Scene.v().getActiveInvokeGraph(); * * // build an invoke graph based on variable type analysis InvokeGraph igVTA = Scene.v().getActiveInvokeGraph(); try { * VariableTypeAnalysis vta = null; int VTApasses = 1; //Options.getInt( PackManager.v().getPhaseOptions( "jil.igb" ), * "VTA-passes" ); for (int i = 0; i < VTApasses; i++) { vta = new VariableTypeAnalysis(igVTA); * vta.trimActiveInvokeGraph(); igVTA.refreshReachableMethods(); } } catch (RuntimeException re) { // this will fail if * the --analyze-context flag is not specified // logger.debug(""+ "JIL VTA FAILED: " + re ); igVTA = null; } */ final String cleanMethodName = cleanMethod(body.getMethod().getName()); // add method node XMLNode methodNode = methodsNode.addChild("method", new String[] { "name", "returntype", "class" }, new String[] { cleanMethodName, body.getMethod().getReturnType().toString(), body.getMethod().getDeclaringClass().getName() }); String declarationStr = body.getMethod().getDeclaration().trim(); methodNode.addChild("declaration", toCDATA(declarationStr), new String[] { "length" }, new String[] { String.valueOf(declarationStr.length()) }); // create references to parameters, locals, labels, stmts nodes XMLNode parametersNode = methodNode.addChild("parameters", new String[] { "method" }, new String[] { cleanMethodName }); XMLNode localsNode = methodNode.addChild("locals"); XMLNode labelsNode = methodNode.addChild("labels"); XMLNode stmtsNode = methodNode.addChild("statements"); // create default label XMLLabel xmlLabel = new XMLLabel(labelCount, cleanMethodName, currentLabel); labelsNode.addChild("label", new String[] { "id", "name", "method" }, new String[] { String.valueOf(labelCount++), currentLabel, cleanMethodName }); // include any analysis which will be used in the xml output final LiveLocals sll = new SimpleLiveLocals(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body)); // lists ArrayList<String> useList = new ArrayList<String>(); ArrayList<ArrayList<Long>> useDataList = new ArrayList<ArrayList<Long>>(); ArrayList<String> defList = new ArrayList<String>(); ArrayList<ArrayList<Long>> defDataList = new ArrayList<ArrayList<Long>>(); ArrayList<ArrayList<String>> paramData = new ArrayList<ArrayList<String>>(); ArrayList<XMLLabel> xmlLabelsList = new ArrayList<XMLLabel>(); long statementCount = 0; long maxStmtCount = 0; long labelID = 0; // for each statement... for (Unit currentStmt : units) { // new label if (stmtToName.containsKey(currentStmt)) { currentLabel = stmtToName.get(currentStmt); // fill in the stmt count for the previous label // index = xmlLabels.indexOf( "%s" ); // if( index != -1 ) // xmlLabels = xmlLabels.substring( 0, index ) + ( labelID ) + xmlLabels.substring( index + 2 ); // index = xmlLabels.indexOf( "%d" ); // if( index != -1 ) // xmlLabels = xmlLabels.substring( 0, index ) + new Float( ( new Float( labelID ).floatValue() / new Float( // units.size() ).intValue() ) * // 100.0 ).intValue() + xmlLabels.substring( index + 2 ); xmlLabel.stmtCount = labelID; xmlLabel.stmtPercentage = (long) (((float) labelID) / ((float) units.size()) * 100f); if (xmlLabel.stmtPercentage > maxStmtCount) { maxStmtCount = xmlLabel.stmtPercentage; } xmlLabelsList.add(xmlLabel); // xmlLabel.clear(); xmlLabel = new XMLLabel(labelCount, cleanMethodName, currentLabel); labelsNode.addChild("label", new String[] { "id", "name", "method" }, new String[] { String.valueOf(labelCount), currentLabel, cleanMethodName }); labelCount++; labelID = 0; } // examine each statement XMLNode stmtNode = stmtsNode.addChild("statement", new String[] { "id", "label", "method", "labelid" }, new String[] { String.valueOf(statementCount), currentLabel, cleanMethodName, String.valueOf(labelID) }); XMLNode sootstmtNode = stmtNode.addChild("soot_statement", new String[] { "branches", "fallsthrough" }, new String[] { boolToString(currentStmt.branches()), boolToString(currentStmt.fallsThrough()) }); // uses for each statement int j = 0; for (ValueBox box : currentStmt.getUseBoxes()) { if (box.getValue() instanceof Local) { String local = cleanLocal(box.getValue().toString()); sootstmtNode.addChild("uses", new String[] { "id", "local", "method" }, new String[] { String.valueOf(j), local, cleanMethodName }); j++; ArrayList<Long> tempArrayList = null; int useIndex = useList.indexOf(local); if (useIndex == -1) { useDataList.add(tempArrayList); useIndex = useList.size(); useList.add(local); } if (useDataList.size() > useIndex) { tempArrayList = useDataList.get(useIndex); if (tempArrayList == null) { tempArrayList = new ArrayList<Long>(); } tempArrayList.add(statementCount); useDataList.set(useIndex, tempArrayList); } } } // defines for each statement j = 0; for (ValueBox box : currentStmt.getDefBoxes()) { if (box.getValue() instanceof Local) { String local = cleanLocal(box.getValue().toString()); sootstmtNode.addChild("defines", new String[] { "id", "local", "method" }, new String[] { String.valueOf(j), local, cleanMethodName }); j++; ArrayList<Long> tempArrayList = null; int defIndex = defList.indexOf(local); if (defIndex == -1) { defDataList.add(tempArrayList); defIndex = defList.size(); defList.add(local); } if (defDataList.size() > defIndex) { tempArrayList = defDataList.get(defIndex); if (tempArrayList == null) { tempArrayList = new ArrayList<Long>(); } tempArrayList.add(statementCount); defDataList.set(defIndex, tempArrayList); } } } /* * // for invokes, add a list of potential targets if (stmtCurrentStmt.containsInvokeExpr()) { // default analysis is * CHA if (igCHA != null) { try { List targets = igCHA.getTargetsOf(stmtCurrentStmt); XMLNode CHAinvoketargetsNode = * sootstmtNode.addChild( "invoketargets", new String[] { "analysis", "count" }, new String[] { "CHA", targets.size() + * "" }); for (int i = 0; i < targets.size(); i++) { SootMethod meth = (SootMethod) targets.get(i); * CHAinvoketargetsNode.addChild( "target", new String[] { "id", "class", "method" }, new String[] { String.valueOf(i), * meth.getDeclaringClass().getFullName(), cleanMethod(meth.getName())}); } } catch (RuntimeException re) { * //logger.debug(""+ "XML: " + re + " (" + stmtCurrentStmt + ")" ); } } * * // now try VTA, which will only work if the -a or --analyze-context switch is specified if (igVTA != null) { * InvokeExpr ie = (InvokeExpr) stmtCurrentStmt.getInvokeExpr(); if (!(ie instanceof StaticInvokeExpr) && !(ie * instanceof SpecialInvokeExpr)) { try { List targets = igVTA.getTargetsOf(stmtCurrentStmt); XMLNode * VTAinvoketargetsNode = sootstmtNode.addChild( "invoketargets", new String[] { "analysis", "count" }, new String[] { * "VTA", String.valueOf(targets.size()) }); for (int i = 0; i < targets.size(); i++) { SootMethod meth = (SootMethod) * targets.get(i); VTAinvoketargetsNode.addChild( "target", new String[] { "id", "class", "method" }, new String[] { i * + "", meth.getDeclaringClass().getFullName(), cleanMethod(meth.getName())}); } } catch (RuntimeException re) { * //logger.debug(""+ "XML: " + re + " (" + stmtCurrentStmt + ")" ); } } } } */ // simple live locals { List<Local> liveLocalsIn = sll.getLiveLocalsBefore(currentStmt); List<Local> liveLocalsOut = sll.getLiveLocalsAfter(currentStmt); XMLNode livevarsNode = sootstmtNode.addChild("livevariables", new String[] { "incount", "outcount" }, new String[] { String.valueOf(liveLocalsIn.size()), String.valueOf(liveLocalsOut.size()) }); for (ListIterator<Local> it = liveLocalsIn.listIterator(); it.hasNext();) { int i = it.nextIndex();// index must be retrieved before 'next()' Local val = it.next(); livevarsNode.addChild("in", new String[] { "id", "local", "method" }, new String[] { String.valueOf(i), cleanLocal(val.toString()), cleanMethodName }); } for (ListIterator<Local> it = liveLocalsOut.listIterator(); it.hasNext();) { int i = it.nextIndex();// index must be retrieved before 'next()' Local val = it.next(); livevarsNode.addChild("out", new String[] { "id", "local", "method" }, new String[] { String.valueOf(i), cleanLocal(val.toString()), cleanMethodName }); } } // parameters for (int i = 0, e = body.getMethod().getParameterCount(); i < e; i++) { paramData.add(new ArrayList<String>()); } // parse any info from the statement code currentStmt.toString(up); String jimpleStr = up.toString().trim(); if (currentStmt instanceof soot.jimple.IdentityStmt && jimpleStr.contains("@parameter")) { // this line is a use of a parameter String tempStr = jimpleStr.substring(jimpleStr.indexOf("@parameter") + 10); int idx = tempStr.indexOf(':'); if (idx != -1) { tempStr = tempStr.substring(0, idx).trim(); } idx = tempStr.indexOf(' '); if (idx != -1) { tempStr = tempStr.substring(0, idx).trim(); } int paramIndex = Integer.valueOf(tempStr); ArrayList<String> tempVec = paramData.get(paramIndex); if (tempVec != null) { tempVec.add(Long.toString(statementCount)); } paramData.set(paramIndex, tempVec); } // add plain jimple representation of each statement sootstmtNode.addChild("jimple", toCDATA(jimpleStr), new String[] { "length" }, new String[] { String.valueOf(jimpleStr.length() + 1) }); // increment statement counters labelID++; statementCount++; } // add count to statments stmtsNode.addAttribute("count", String.valueOf(statementCount)); // method parameters { List<Type> parameterTypes = body.getMethod().getParameterTypes(); parametersNode.addAttribute("count", String.valueOf(parameterTypes.size())); for (ListIterator<Type> it = parameterTypes.listIterator(); it.hasNext();) { int i = it.nextIndex();// index must be retrieved before 'next()' Type val = it.next(); XMLNode paramNode = parametersNode.addChild("parameter", new String[] { "id", "type", "method", "name" }, new String[] { String.valueOf(i), String.valueOf(val), cleanMethodName, "_parameter" + i }); XMLNode sootparamNode = paramNode.addChild("soot_parameter"); ArrayList<String> tempVec = paramData.get(i); for (ListIterator<String> itk = tempVec.listIterator(); itk.hasNext();) { int k = itk.nextIndex();// index must be retrieved before 'next()' String valk = itk.next(); sootparamNode.addChild("use", new String[] { "id", "line", "method" }, new String[] { String.valueOf(k), valk, cleanMethodName }); } sootparamNode.addAttribute("uses", String.valueOf(tempVec.size())); } } /* * index = xmlLabels.indexOf( "%s" ); if( index != -1 ) xmlLabels = xmlLabels.substring( 0, index ) + ( labelID ) + * xmlLabels.substring( index + 2 ); index = xmlLabels.indexOf( "%d" ); if( index != -1 ) xmlLabels = * xmlLabels.substring( 0, index ) + new Float( ( new Float( labelID ).floatValue() / new Float( units.size() * ).floatValue() ) * 100.0 ).intValue() + xmlLabels.substring( index + 2 ); */ xmlLabel.stmtCount = labelID; xmlLabel.stmtPercentage = (long) (((float) labelID) / ((float) units.size()) * 100f); if (xmlLabel.stmtPercentage > maxStmtCount) { maxStmtCount = xmlLabel.stmtPercentage; } xmlLabelsList.add(xmlLabel); // print out locals { Collection<Local> locals = body.getLocals(); ArrayList<String> localTypes = new ArrayList<String>(); ArrayList<ArrayList<XMLNode>> typedLocals = new ArrayList<ArrayList<XMLNode>>(); ArrayList<Integer> typeCounts = new ArrayList<Integer>(); int j = 0; int currentType = 0; for (Local localData : locals) { int useCount = 0; int defineCount = 0; // collect the local types final String localType = localData.getType().toString(); if (!localTypes.contains(localType)) { localTypes.add(localType); typedLocals.add(new ArrayList<XMLNode>()); typeCounts.add(0); } final String local = cleanLocal(localData.toString()); // create a reference to the local node XMLNode localNode = new XMLNode("local", "", new String[] { "id", "method", "name", "type" }, new String[] { String.valueOf(j), cleanMethodName, local, localType }); XMLNode sootlocalNode = localNode.addChild("soot_local"); currentType = 0; for (ListIterator<String> it = localTypes.listIterator(); it.hasNext();) { String val = it.next(); if (localType.equalsIgnoreCase(val)) { int k = it.previousIndex(); currentType = k; typeCounts.set(k, typeCounts.get(k) + 1); break; } } // add all uses to this local for (String nextUse : useList) { if (local.equalsIgnoreCase(nextUse)) { ArrayList<Long> tempArrayList = useDataList.get(useList.indexOf(local)); useCount = tempArrayList.size(); for (ListIterator<Long> it = tempArrayList.listIterator(); it.hasNext();) { int i = it.nextIndex();// index must be retrieved before 'next()' Long val = it.next(); sootlocalNode.addChild("use", new String[] { "id", "line", "method" }, new String[] { String.valueOf(i), String.valueOf(val), cleanMethodName }); } break; } } // add all definitions to this local for (String nextDef : defList) { if (local.equalsIgnoreCase(nextDef)) { ArrayList<Long> tempArrayList = defDataList.get(defList.indexOf(local)); defineCount = tempArrayList.size(); for (ListIterator<Long> it = tempArrayList.listIterator(); it.hasNext();) { int i = it.nextIndex();// index must be retrieved before 'next()' Long val = it.next(); sootlocalNode.addChild("definition", new String[] { "id", "line", "method" }, new String[] { String.valueOf(i), String.valueOf(val), cleanMethodName }); } break; } } // add number of uses and defines to this local sootlocalNode.addAttribute("uses", String.valueOf(useCount)); sootlocalNode.addAttribute("defines", String.valueOf(defineCount)); // create a list of locals sorted by type ArrayList<XMLNode> list = typedLocals.get(currentType); list.add(localNode); typedLocals.set(currentType, list); // add local to locals node localsNode.addChild((XMLNode) localNode.clone()); j++; } // add count to the locals node localsNode.addAttribute("count", String.valueOf(locals.size())); // add types node to locals node, and each type with each local per type XMLNode typesNode = localsNode.addChild("types", new String[] { "count" }, new String[] { String.valueOf(localTypes.size()) }); for (ListIterator<String> it = localTypes.listIterator(); it.hasNext();) { int i = it.nextIndex();// index must be retrieved before 'next()' String val = it.next(); XMLNode typeNode = typesNode.addChild("type", new String[] { "id", "type", "count" }, new String[] { String.valueOf(i), val, String.valueOf(typeCounts.get(i)) }); for (XMLNode n : typedLocals.get(i)) { typeNode.addChild(n); } } } // add count attribute to labels node, and stmtcount, and stmtpercentage attributes to each label node labelsNode.addAttribute("count", String.valueOf(labelCount)); XMLNode current = labelsNode.child; for (XMLLabel tempLabel : xmlLabelsList) { tempLabel.stmtPercentage = (long) (((float) tempLabel.stmtPercentage) / ((float) maxStmtCount) * 100f); if (current != null) { current.addAttribute("stmtcount", String.valueOf(tempLabel.stmtCount)); current.addAttribute("stmtpercentage", String.valueOf(tempLabel.stmtPercentage)); current = current.next; } } // Print out exceptions { int j = 0; XMLNode exceptionsNode = methodNode.addChild("exceptions"); for (Trap trap : body.getTraps()) { // catch java.io.IOException from label0 to label1 with label2; XMLNode catchNode = exceptionsNode.addChild("exception", new String[] { "id", "method", "type" }, new String[] { String.valueOf(j++), cleanMethodName, Scene.v().quotedNameOf(trap.getException().getName()) }); catchNode.addChild("begin", new String[] { "label" }, new String[] { stmtToName.get(trap.getBeginUnit()) }); catchNode.addChild("end", new String[] { "label" }, new String[] { stmtToName.get(trap.getEndUnit()) }); catchNode.addChild("handler", new String[] { "label" }, new String[] { stmtToName.get(trap.getHandlerUnit()) }); } exceptionsNode.addAttribute("count", String.valueOf(exceptionsNode.getNumberOfChildren())); } // Scene.v().releaseActiveInvokeGraph(); } private static String cleanMethod(String str) { // method names can be filtered here, for example replacing < and > with _ to comply with XML name tokens return str.trim().replace('<', '_').replace('>', '_'); } private static String cleanLocal(String str) { // local names can be filtered here, for example replacing $ with _ to comply with XML name tokens return str.trim(); // .replace( '$', '_' ); } private static String toCDATA(String str) { // wrap a string in CDATA markup - str can contain anything and will pass XML validation return "<![CDATA[" + str.replaceAll("]]>", "]]&gt;") + "]]>"; } private static String boolToString(boolean bool) { return bool ? "true" : "false"; } private static class XMLLabel { public final long id; public final String methodName; public final String label; public long stmtCount; public long stmtPercentage; public XMLLabel(long in_id, String in_methodName, String in_label) { this.id = in_id; this.methodName = in_methodName; this.label = in_label; } } }
27,158
41.905213
125
java
soot
soot-master/src/main/java/soot/xml/XMLRoot.java
package soot.xml; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2002 David Eng * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** XML helper */ public class XMLRoot { public String name = ""; // <NAME attr1="val1" attr2="val2"...>val</NAME> public String value = ""; // <name attr1="val1" attr2="val2"...>VAL</name> public String[] attributes = { "" }; // <name ATTR1="val1" ATTR2="val2"...>val</name> public String[] values = { "" }; // <name attr1="VAL1" attr2="VAL2"...>val</name> protected XMLNode child = null; // -> to child node XMLRoot() { } @Override public String toString() { return XMLPrinter.xmlHeader + XMLPrinter.dtdHeader + this.child.toPostString(); } // add element to end of tree public XMLNode addElement(String name) { return addElement(name, "", "", ""); } public XMLNode addElement(String name, String value) { return addElement(name, value, "", ""); } public XMLNode addElement(String name, String value, String[] attributes) { return addElement(name, value, attributes, null); } public XMLNode addElement(String name, String[] attributes, String[] values) { return addElement(name, "", attributes, values); } public XMLNode addElement(String name, String value, String attribute, String attributeValue) { return addElement(name, value, new String[] { attribute }, new String[] { attributeValue }); } public XMLNode addElement(String name, String value, String[] attributes, String[] values) { XMLNode newnode = new XMLNode(name, value, attributes, values); newnode.root = this; if (this.child == null) { this.child = newnode; newnode.parent = null; // root's children have NO PARENTS :( } else { XMLNode current = this.child; while (current.next != null) { current = current.next; } current.next = newnode; newnode.prev = current; } return newnode; } }
2,619
31.345679
97
java
soot
soot-master/src/systemTest/java/soot/SootMethodRefImplTest.java
package soot; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2021 Timothy Hoffman * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.stream.Collectors; import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.jimple.Stmt; import soot.testing.framework.AbstractTestingFramework; /** * @author Timothy Hoffman */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class SootMethodRefImplTest extends AbstractTestingFramework { private static final String TEST_TARGET_CLASS = "soot.SootMethodRefImplTestInput"; @Override protected void setupSoot() { } @Test public void testCachingInvalidation() throws Exception { SootMethod m1 = prepareTarget(methodSigFromComponents(TEST_TARGET_CLASS, "void", "m1"), TEST_TARGET_CLASS); final SootClass clas = m1.getDeclaringClass(); // There are only 3 methods in the class originally. Assert.assertEquals(Arrays.asList("<init>", "m1", "m2"), clas.getMethods().stream().map(SootMethod::getName).sorted().collect(Collectors.toList())); // Ensure the previous value of SootMethodRefImpl#resolveCache // is not used if the referenced method itself is modified. final Body b = m1.retrieveActiveBody(); final SootMethodRef mRef = getMethodRef(b); Assert.assertEquals("m2", mRef.getName()); // Get the original referenced method appearing in the test source (i.e. "m2") final SootMethod origM = mRef.resolve(); Assert.assertTrue(!origM.isPhantom()); Assert.assertEquals("m2", origM.getName()); // Change the name of the method so the method reference no // longer refers to that method. origM.setName("newMethodName"); Assert.assertEquals("newMethodName", origM.getName()); // Changing the method itself does not change the reference Assert.assertEquals("m2", mRef.getName()); // There are still just 3 methods in the class (but "m2" was renamed). Assert.assertEquals(Arrays.asList("<init>", "m1", "newMethodName"), clas.getMethods().stream().map(SootMethod::getName).sorted().collect(Collectors.toList())); // When resolving the reference, the cached value is not used since the // original method was renamed. It now gives a different method (that was // created automatically since a method with the name "m2" no longer exists). final SootMethod newM = mRef.resolve(); Assert.assertNotSame(origM, newM); Assert.assertEquals("m2", newM.getName()); // There are now 4 methods since resolving "m2" created it again. Assert.assertEquals(Arrays.asList("<init>", "m1", "m2", "newMethodName"), clas.getMethods().stream().map(SootMethod::getName).sorted().collect(Collectors.toList())); } private static SootMethodRef getMethodRef(Body b) { SootMethodRef retVal = null; for (Unit u : b.getUnits()) { Assert.assertTrue(u instanceof Stmt); Stmt s = (Stmt) u; if (s.containsInvokeExpr()) { Assert.assertNull(retVal);// the body has exactly 1 InvokeExpr retVal = s.getInvokeExpr().getMethodRef(); } } Assert.assertNotNull(retVal);// the body has exactly 1 InvokeExpr return retVal; } }
3,981
36.92381
111
java
soot
soot-master/src/systemTest/java/soot/asm/AsmInnerClassTest.java
package soot.asm; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2020 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Modifier; import soot.Scene; import soot.SootMethod; import soot.tagkit.InnerClassTag; import soot.tagkit.Tag; import soot.testing.framework.AbstractTestingFramework; @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class AsmInnerClassTest extends AbstractTestingFramework { private static final String TEST_TARGET_CLASS = "soot.asm.ScopeFinderTarget"; @Override protected void setupSoot() { // no need for call graph } @Test public void nonInner() { // statements at the beginning of a for loop should have the line number as for the branching // statement and not the last line number after the branch that leads outside the loop SootMethod target = prepareTarget( methodSigFromComponents(TEST_TARGET_CLASS, "void", "method"), TEST_TARGET_CLASS); assertEquals(2, Scene.v().getApplicationClasses().size()); assertFalse(target.getDeclaringClass().hasOuterClass()); assertFalse(target.getDeclaringClass().isInnerClass()); InnerClassTag tag = (InnerClassTag) target.getDeclaringClass().getTag(InnerClassTag.NAME); // the class has inner classes assertNotNull(tag); } @Test public void InnerStatic() { SootMethod target2 = prepareTarget( methodSigFromComponents(TEST_TARGET_CLASS + "$Inner", "void", "<init>"), TEST_TARGET_CLASS + "$Inner"); assertEquals(2, Scene.v().getApplicationClasses().size()); assertTrue(target2.getDeclaringClass().hasOuterClass()); assertTrue(target2.getDeclaringClass().isInnerClass()); InnerClassTag tag2 = (InnerClassTag) target2.getDeclaringClass().getTag(InnerClassTag.NAME); assertNotNull(tag2); assertEquals("soot/asm/ScopeFinderTarget$Inner", tag2.getInnerClass()); assertEquals("soot/asm/ScopeFinderTarget", tag2.getOuterClass()); assertTrue(Modifier.isStatic(tag2.getAccessFlags())); } @Test public void InnerStaticInner() { SootMethod target3 = prepareTarget( methodSigFromComponents(TEST_TARGET_CLASS + "$Inner$InnerInner", "void", "method"), TEST_TARGET_CLASS + "$Inner$InnerInner"); // one dummy assertEquals(2, Scene.v().getApplicationClasses().size()); assertTrue(target3.getDeclaringClass().hasOuterClass()); assertTrue(target3.getDeclaringClass().isInnerClass()); InnerClassTag innerClassTag = null; for (Tag tag : target3.getDeclaringClass().getTags()) { // FIXME: we have multiple innerclasstags? for a parent it makes sense but for a child class? if (tag instanceof InnerClassTag) { boolean inner = ((InnerClassTag) tag) .getInnerClass() .equals("soot/asm/ScopeFinderTarget$Inner$InnerInner"); if (inner) { innerClassTag = (InnerClassTag) tag; break; } } } assertNotNull(innerClassTag); assertEquals("soot/asm/ScopeFinderTarget$Inner$InnerInner", innerClassTag.getInnerClass()); assertEquals("soot/asm/ScopeFinderTarget$Inner", innerClassTag.getOuterClass()); assertFalse(Modifier.isStatic(innerClassTag.getAccessFlags())); } }
4,264
37.423423
99
java
soot
soot-master/src/systemTest/java/soot/asm/AsmMethodSourceOrigNamesTest.java
package soot.asm; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2021 Timothy Hoffman * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Body; import soot.SootMethod; import soot.options.Options; import soot.testing.framework.AbstractTestingFramework; import soot.validation.CheckInitValidator; import soot.validation.ValidationException; /** * @author Timothy Hoffman */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class AsmMethodSourceOrigNamesTest extends AbstractTestingFramework { @Override protected void setupSoot() { final Options opts = Options.v(); opts.set_validate(false); opts.setPhaseOption("jb", "use-original-names:true"); opts.setPhaseOption("jb.sils", "enabled:false"); } /** * Below is the output of "javap -verbose" for the relevant method. The '|' character was added to mark the ranges where * the LocalVariableTable specifies a variable name for local slot 9. Notice there is an additional use of slot 9 at offset * 126 which does not appear in any of the specified ranges which means the local variable name for that use is unknown. * * <code><pre> * public void write(char[], int, int) throws java.io.IOException; * descriptor: ([CII)V * flags: ACC_PUBLIC * Code: * stack=5, locals=10, args_size=4 * 0: iconst_3 * 1: iload_3 * 2: imul * 3: istore 4 * 5: iload 4 * 7: sipush 16384 * 10: aload_0 * 11: getfield #5 // Field count:I * 14: isub * 15: if_icmplt 96 * 18: aload_0 * 19: invokevirtual #6 // Method flushBuffer:()V * 22: iload 4 * 24: sipush 16384 * 27: if_icmplt 96 * 30: iconst_1 * 31: iload_3 * 32: sipush 5461 * 35: idiv * 36: iadd * 37: istore 5 * 39: iconst_0 * 40: istore 6 * 42: goto 88 * 45: iload_2 * 46: iload_3 * 47: iload 6 * 49: imul * 50: iload 5 * 52: idiv * 53: iadd * 54: istore 7 * 56: iload_2 * 57: iload_3 * 58: iload 6 * 60: iconst_1 * 61: iadd * 62: imul * 63: iload 5 * 65: idiv * 66: iadd * 67: istore 8 * 69: iload 8 * 71: iload 7 * 73: isub * | 74: istore 9 * | 76: aload_0 * | 77: aload_1 * | 78: iload 7 * | 80: iload 9 * | 82: invokevirtual #7 // Method write:([CII)V * | 85: iinc 6, 1 * 88: iload 6 * 90: iload 5 * 92: if_icmplt 45 * 95: return * 96: iload_3 * 97: iload_2 * 98: iadd * 99: istore 5 * 101: aload_0 * 102: getfield #3 // Field m_outputBytes:[B * 105: astore 6 * 107: aload_0 * 108: getfield #5 // Field count:I * 111: istore 7 * 113: iload_2 * 114: istore 8 * 116: goto 133 * 119: aload 6 * 121: iload 7 * 123: iinc 7, 1 * ? 126: iload 9 * 128: i2b * 129: bastore * 130: iinc 8, 1 * 133: iload 8 * 135: iload 5 * 137: if_icmpge 153 * 140: aload_1 * 141: iload 8 * 143: caload * 144: dup * | 145: istore 9 * | 147: sipush 128 * | 150: if_icmplt 119 * | 153: goto 291 * 156: aload_1 * 157: iload 8 * 159: caload * | 160: istore 9 * | 162: iload 9 * | 164: sipush 128 * | 167: if_icmpge 184 * | 170: aload 6 * | 172: iload 7 * | 174: iinc 7, 1 * | 177: iload 9 * | 179: i2b * | 180: bastore * | 181: goto 288 * | 184: iload 9 * | 186: sipush 2048 * | 189: if_icmpge 231 * | 192: aload 6 * | 194: iload 7 * | 196: iinc 7, 1 * | 199: sipush 192 * | 202: iload 9 * | 204: bipush 6 * | 206: ishr * | 207: iadd * | 208: i2b * | 209: bastore * | 210: aload 6 * | 212: iload 7 * | 214: iinc 7, 1 * | 217: sipush 128 * | 220: iload 9 * | 222: bipush 63 * | 224: iand * | 225: iadd * | 226: i2b * | 227: bastore * | 228: goto 288 * | 231: aload 6 * | 233: iload 7 * | 235: iinc 7, 1 * | 238: sipush 224 * | 241: iload 9 * | 243: bipush 12 * | 245: ishr * | 246: iadd * | 247: i2b * | 248: bastore * | 249: aload 6 * | 251: iload 7 * | 253: iinc 7, 1 * | 256: sipush 128 * | 259: iload 9 * | 261: bipush 6 * | 263: ishr * | 264: bipush 63 * | 266: iand * | 267: iadd * | 268: i2b * | 269: bastore * | 270: aload 6 * | 272: iload 7 * | 274: iinc 7, 1 * | 277: sipush 128 * | 280: iload 9 * | 282: bipush 63 * | 284: iand * | 285: iadd * | 286: i2b * | 287: bastore * | 288: iinc 8, 1 * 291: iload 8 * 293: iload 5 * 295: if_icmplt 156 * 298: aload_0 * 299: iload 7 * 301: putfield #5 // Field count:I * 304: return * LocalVariableTable: * Start Length Slot Name Signature * 0 305 0 this Lorg/apache/xml/serializer/WriterToUTF8Buffered; * 0 305 1 chars [C * 0 305 2 start I * 0 305 3 length I * 5 299 4 lengthx3 I * 39 57 5 chunks I * 42 54 6 chunk I * 56 29 7 start_chunk I * 69 16 8 end_chunk I * 76 9 9 len_chunk I * 101 203 5 n I * 107 197 6 buf_loc [B * 113 191 7 count_loc I * 116 188 8 i I * 147 6 9 c C * 162 126 9 c C * Exceptions: * throws java.io.IOException * </pre></code> */ @Test public void testWriterToUTF8Buffered1() { final String clazz = "org.apache.xml.serializer.WriterToUTF8Buffered"; final String[] params = { "char[]", "int", "int" }; runXalanTest(prepareTarget(methodSigFromComponents(clazz, "void", "write", params), clazz)); } /** * Below is the output of "javap -verbose" for the relevant method. The '|' character was added to mark the ranges where * the LocalVariableTable specifies a variable name for local slot 9. Notice there is an additional use of slot 9 at offset * 161 which does not appear in any of the specified ranges which means the local variable name for that use is unknown. * * <code><pre> * public void write(java.lang.String) throws java.io.IOException; * descriptor: (Ljava/lang/String;)V * flags: ACC_PUBLIC * Code: * stack=5, locals=10, args_size=2 * 0: aload_1 * 1: invokevirtual #9 // Method java/lang/String.length:()I * 4: istore_2 * 5: iconst_3 * 6: iload_2 * 7: imul * 8: istore_3 * 9: iload_3 * 10: sipush 16384 * 13: aload_0 * 14: getfield #5 // Field count:I * 17: isub * 18: if_icmplt 116 * 21: aload_0 * 22: invokevirtual #6 // Method flushBuffer:()V * 25: iload_3 * 26: sipush 16384 * 29: if_icmplt 116 * 32: iconst_0 * 33: istore 4 * 35: iconst_1 * 36: iload_2 * 37: sipush 5461 * 40: idiv * 41: iadd * 42: istore 5 * 44: iconst_0 * 45: istore 6 * 47: goto 108 * 50: iconst_0 * 51: iload_2 * 52: iload 6 * 54: imul * 55: iload 5 * 57: idiv * 58: iadd * 59: istore 7 * 61: iconst_0 * 62: iload_2 * 63: iload 6 * 65: iconst_1 * 66: iadd * 67: imul * 68: iload 5 * 70: idiv * 71: iadd * 72: istore 8 * 74: iload 8 * 76: iload 7 * 78: isub * | 79: istore 9 * | 81: aload_1 * | 82: iload 7 * | 84: iload 8 * | 86: aload_0 * | 87: getfield #4 // Field m_inputChars:[C * | 90: iconst_0 * | 91: invokevirtual #10 // Method java/lang/String.getChars:(II[CI)V * | 94: aload_0 * | 95: aload_0 * | 96: getfield #4 // Field m_inputChars:[C * | 99: iconst_0 * | 100: iload 9 * | 102: invokevirtual #7 // Method write:([CII)V * | 105: iinc 6, 1 * 108: iload 6 * 110: iload 5 * 112: if_icmplt 50 * 115: return * 116: aload_1 * 117: iconst_0 * 118: iload_2 * 119: aload_0 * 120: getfield #4 // Field m_inputChars:[C * 123: iconst_0 * 124: invokevirtual #10 // Method java/lang/String.getChars:(II[CI)V * 127: aload_0 * 128: getfield #4 // Field m_inputChars:[C * 131: astore 4 * 133: iload_2 * 134: istore 5 * 136: aload_0 * 137: getfield #3 // Field m_outputBytes:[B * 140: astore 6 * 142: aload_0 * 143: getfield #5 // Field count:I * 146: istore 7 * 148: iconst_0 * 149: istore 8 * 151: goto 168 * 154: aload 6 * 156: iload 7 * 158: iinc 7, 1 * ? 161: iload 9 * 163: i2b * 164: bastore * 165: iinc 8, 1 * 168: iload 8 * 170: iload 5 * 172: if_icmpge 189 * 175: aload 4 * 177: iload 8 * 179: caload * 180: dup * | 181: istore 9 * | 183: sipush 128 * | 186: if_icmplt 154 * | 189: goto 328 * 192: aload 4 * 194: iload 8 * 196: caload * | 197: istore 9 * | 199: iload 9 * | 201: sipush 128 * | 204: if_icmpge 221 * | 207: aload 6 * | 209: iload 7 * | 211: iinc 7, 1 * | 214: iload 9 * | 216: i2b * | 217: bastore * | 218: goto 325 * | 221: iload 9 * | 223: sipush 2048 * | 226: if_icmpge 268 * | 229: aload 6 * | 231: iload 7 * | 233: iinc 7, 1 * | 236: sipush 192 * | 239: iload 9 * | 241: bipush 6 * | 243: ishr * | 244: iadd * | 245: i2b * | 246: bastore * | 247: aload 6 * | 249: iload 7 * | 251: iinc 7, 1 * | 254: sipush 128 * | 257: iload 9 * | 259: bipush 63 * | 261: iand * | 262: iadd * | 263: i2b * | 264: bastore * | 265: goto 325 * | 268: aload 6 * | 270: iload 7 * | 272: iinc 7, 1 * | 275: sipush 224 * | 278: iload 9 * | 280: bipush 12 * | 282: ishr * | 283: iadd * | 284: i2b * | 285: bastore * | 286: aload 6 * | 288: iload 7 * | 290: iinc 7, 1 * | 293: sipush 128 * | 296: iload 9 * | 298: bipush 6 * | 300: ishr * | 301: bipush 63 * | 303: iand * | 304: iadd * | 305: i2b * | 306: bastore * | 307: aload 6 * | 309: iload 7 * | 311: iinc 7, 1 * | 314: sipush 128 * | 317: iload 9 * | 319: bipush 63 * | 321: iand * | 322: iadd * | 323: i2b * | 324: bastore * | 325: iinc 8, 1 * 328: iload 8 * 330: iload 5 * 332: if_icmplt 192 * 335: aload_0 * 336: iload 7 * 338: putfield #5 // Field count:I * 341: return * LocalVariableTable: * Start Length Slot Name Signature * 0 342 0 this Lorg/apache/xml/serializer/WriterToUTF8Buffered; * 0 342 1 s Ljava/lang/String; * 5 336 2 length I * 9 332 3 lengthx3 I * 35 81 4 start I * 44 72 5 chunks I * 47 69 6 chunk I * 61 44 7 start_chunk I * 74 31 8 end_chunk I * 81 24 9 len_chunk I * 133 208 4 chars [C * 136 205 5 n I * 142 199 6 buf_loc [B * 148 193 7 count_loc I * 151 190 8 i I * 183 6 9 c C * 199 126 9 c C * Exceptions: * throws java.io.IOException * </pre></code> */ @Test public void testWriterToUTF8Buffered2() { final String clazz = "org.apache.xml.serializer.WriterToUTF8Buffered"; final String[] params = { "java.lang.String" }; runXalanTest(prepareTarget(methodSigFromComponents(clazz, "void", "write", params), clazz)); } /** * Below is the output of "javap -verbose" for the relevant method. The '|' character was added to mark the ranges where * the LocalVariableTable specifies a variable name for local slot 20. Notice there are several additional uses of slot 20 * at the locations marked with a '?' which do not appear in any of the specified ranges which means the local variable * names for those uses are unknown. * * <code><pre> * public void transformSelectedNodes(org.apache.xalan.transformer.TransformerImpl) throws javax.xml.transform.TransformerException; * descriptor: (Lorg/apache/xalan/transformer/TransformerImpl;)V * flags: ACC_PUBLIC * Code: * stack=8, locals=36, args_size=2 * 0: aload_1 * 1: invokevirtual #17 // Method org/apache/xalan/transformer/TransformerImpl.getXPathContext:()Lorg/apache/xpath/XPathContext; * 4: astore_2 * 5: aload_2 * 6: invokevirtual #18 // Method org/apache/xpath/XPathContext.getCurrentNode:()I * 9: istore_3 * 10: aload_0 * 11: getfield #19 // Field org/apache/xalan/templates/ElemForEach.m_selectExpression:Lorg/apache/xpath/Expression; * 14: aload_2 * 15: iload_3 * 16: invokevirtual #20 // Method org/apache/xpath/Expression.asIterator:(Lorg/apache/xpath/XPathContext;I)Lorg/apache/xml/dtm/DTMIterator; * 19: astore 4 * 21: aload_2 * 22: invokevirtual #21 // Method org/apache/xpath/XPathContext.getVarStack:()Lorg/apache/xpath/VariableStack; * 25: astore 5 * 27: aload_0 * 28: invokevirtual #22 // Method org/apache/xalan/templates/ElemCallTemplate.getParamElemCount:()I * 31: istore 6 * 33: aload 5 * 35: invokevirtual #23 // Method org/apache/xpath/VariableStack.getStackFrame:()I * 38: istore 7 * 40: aload_1 * 41: invokevirtual #24 // Method org/apache/xalan/transformer/TransformerImpl.getStackGuard:()Lorg/apache/xalan/transformer/StackGuard; * 44: astore 8 * 46: aload 8 * 48: invokevirtual #25 // Method org/apache/xalan/transformer/StackGuard.getRecursionLimit:()I * 51: iconst_m1 * 52: if_icmple 59 * 55: iconst_1 * 56: goto 60 * 59: iconst_0 * 60: istore 9 * 62: iconst_0 * 63: istore 10 * 65: aload_2 * 66: iconst_m1 * 67: invokevirtual #26 // Method org/apache/xpath/XPathContext.pushCurrentNode:(I)V * 70: aload_2 * 71: iconst_m1 * 72: invokevirtual #27 // Method org/apache/xpath/XPathContext.pushCurrentExpressionNode:(I)V * 75: aload_2 * 76: invokevirtual #28 // Method org/apache/xpath/XPathContext.pushSAXLocatorNull:()V * 79: aload_1 * 80: aconst_null * 81: invokevirtual #29 // Method org/apache/xalan/transformer/TransformerImpl.pushElemTemplateElement:(Lorg/apache/xalan/templates/ElemTemplateElement;)V * 84: aload_0 * 85: getfield #30 // Field org/apache/xalan/templates/ElemForEach.m_sortElems:Ljava/util/Vector; * 88: ifnonnull 95 * 91: aconst_null * 92: goto 101 * 95: aload_1 * 96: aload_0 * 97: iload_3 * 98: invokevirtual #31 // Method org/apache/xalan/transformer/TransformerImpl.processSortKeys:(Lorg/apache/xalan/templates/ElemForEach;I)Ljava/util/Vector; * 101: astore 11 * 103: aconst_null * 104: aload 11 * 106: if_acmpeq 120 * 109: aload_0 * 110: aload_2 * 111: aload 11 * 113: aload 4 * 115: invokevirtual #32 // Method org/apache/xalan/templates/ElemForEach.sortNodes:(Lorg/apache/xpath/XPathContext;Ljava/util/Vector;Lorg/apache/xml/dtm/DTMIterator;)Lorg/apache/xml/dtm/DTMIterator; * 118: astore 4 * 120: getstatic #10 // Field org/apache/xalan/transformer/TransformerImpl.S_DEBUG:Z * 123: ifeq 157 * 126: aload_1 * 127: invokevirtual #11 // Method org/apache/xalan/transformer/TransformerImpl.getTraceManager:()Lorg/apache/xalan/trace/TraceManager; * 130: iload_3 * 131: aload_0 * 132: ldc #33 // String select * 134: new #34 // class org/apache/xpath/XPath * 137: dup * 138: aload_0 * 139: getfield #19 // Field org/apache/xalan/templates/ElemForEach.m_selectExpression:Lorg/apache/xpath/Expression; * 142: invokespecial #35 // Method org/apache/xpath/XPath."<init>":(Lorg/apache/xpath/Expression;)V * 145: new #36 // class org/apache/xpath/objects/XNodeSet * 148: dup * 149: aload 4 * 151: invokespecial #37 // Method org/apache/xpath/objects/XNodeSet."<init>":(Lorg/apache/xml/dtm/DTMIterator;)V * 154: invokevirtual #38 // Method org/apache/xalan/trace/TraceManager.fireSelectedEvent:(ILorg/apache/xalan/templates/ElemTemplateElement;Ljava/lang/String;Lorg/apache/xpath/XPath;Lorg/apache/xpath/objects/XObject;)V * 157: aload_1 * 158: invokevirtual #39 // Method org/apache/xalan/transformer/TransformerImpl.getSerializationHandler:()Lorg/apache/xml/serializer/SerializationHandler; * 161: astore 12 * 163: aload_1 * 164: invokevirtual #40 // Method org/apache/xalan/transformer/TransformerImpl.getStylesheet:()Lorg/apache/xalan/templates/StylesheetRoot; * 167: astore 13 * 169: aload 13 * 171: invokevirtual #41 // Method org/apache/xalan/templates/StylesheetRoot.getTemplateListComposed:()Lorg/apache/xalan/templates/TemplateList; * 174: astore 14 * 176: aload_1 * 177: invokevirtual #42 // Method org/apache/xalan/transformer/TransformerImpl.getQuietConflictWarnings:()Z * 180: istore 15 * 182: aload_2 * 183: iload_3 * 184: invokevirtual #43 // Method org/apache/xpath/XPathContext.getDTM:(I)Lorg/apache/xml/dtm/DTM; * 187: astore 16 * 189: iconst_m1 * 190: istore 17 * 192: iload 6 * 194: ifle 295 * 197: aload 5 * 199: iload 6 * 201: invokevirtual #44 // Method org/apache/xpath/VariableStack.link:(I)I * 204: istore 17 * 206: aload 5 * 208: iload 7 * 210: invokevirtual #45 // Method org/apache/xpath/VariableStack.setStackFrame:(I)V * 213: iconst_0 * 214: istore 18 * 216: goto 281 * 219: aload_0 * 220: getfield #46 // Field org/apache/xalan/templates/ElemCallTemplate.m_paramElems:[Lorg/apache/xalan/templates/ElemWithParam; * 223: iload 18 * 225: aaload * 226: astore 19 * 228: getstatic #10 // Field org/apache/xalan/transformer/TransformerImpl.S_DEBUG:Z * 231: ifeq 243 * 234: aload_1 * 235: invokevirtual #11 // Method org/apache/xalan/transformer/TransformerImpl.getTraceManager:()Lorg/apache/xalan/trace/TraceManager; * 238: aload 19 * 240: invokevirtual #12 // Method org/apache/xalan/trace/TraceManager.fireTraceEvent:(Lorg/apache/xalan/templates/ElemTemplateElement;)V * 243: aload 19 * 245: aload_1 * 246: iload_3 * 247: invokevirtual #47 // Method org/apache/xalan/templates/ElemWithParam.getValue:(Lorg/apache/xalan/transformer/TransformerImpl;I)Lorg/apache/xpath/objects/XObject; * | 250: astore 20 * | 252: getstatic #10 // Field org/apache/xalan/transformer/TransformerImpl.S_DEBUG:Z * | 255: ifeq 267 * | 258: aload_1 * | 259: invokevirtual #11 // Method org/apache/xalan/transformer/TransformerImpl.getTraceManager:()Lorg/apache/xalan/trace/TraceManager; * | 262: aload 19 * | 264: invokevirtual #14 // Method org/apache/xalan/trace/TraceManager.fireTraceEndEvent:(Lorg/apache/xalan/templates/ElemTemplateElement;)V * | 267: aload 5 * | 269: iload 18 * | 271: aload 20 * | 273: iload 17 * | 275: invokevirtual #48 // Method org/apache/xpath/VariableStack.setLocalVariable:(ILorg/apache/xpath/objects/XObject;I)V * | 278: iinc 18, 1 * 281: iload 18 * 283: iload 6 * 285: if_icmplt 219 * 288: aload 5 * 290: iload 17 * 292: invokevirtual #45 // Method org/apache/xpath/VariableStack.setStackFrame:(I)V * 295: aload_2 * 296: aload 4 * 298: invokevirtual #49 // Method org/apache/xpath/XPathContext.pushContextNodeList:(Lorg/apache/xml/dtm/DTMIterator;)V * 301: iconst_1 * 302: istore 10 * 304: aload_2 * 305: invokevirtual #50 // Method org/apache/xpath/XPathContext.getCurrentNodeStack:()Lorg/apache/xml/utils/IntStack; * 308: astore 18 * 310: aload_2 * 311: invokevirtual #51 // Method org/apache/xpath/XPathContext.getCurrentExpressionNodeStack:()Lorg/apache/xml/utils/IntStack; * 314: astore 19 * 316: goto 831 * 319: aload 18 * ? 321: iload 20 * 323: invokevirtual #52 // Method org/apache/xml/utils/IntStack.setTop:(I)V * 326: aload 19 * ? 328: iload 20 * 330: invokevirtual #52 // Method org/apache/xml/utils/IntStack.setTop:(I)V * 333: aload_2 * ? 334: iload 20 * 336: invokevirtual #43 // Method org/apache/xpath/XPathContext.getDTM:(I)Lorg/apache/xml/dtm/DTM; * 339: aload 16 * 341: if_acmpeq 352 * 344: aload_2 * ? 345: iload 20 * 347: invokevirtual #43 // Method org/apache/xpath/XPathContext.getDTM:(I)Lorg/apache/xml/dtm/DTM; * 350: astore 16 * 352: aload 16 * ? 354: iload 20 * 356: invokeinterface #53, 2 // InterfaceMethod org/apache/xml/dtm/DTM.getExpandedTypeID:(I)I * 361: istore 21 * 363: aload 16 * ? 365: iload 20 * 367: invokeinterface #54, 2 // InterfaceMethod org/apache/xml/dtm/DTM.getNodeType:(I)S * 372: istore 22 * 374: aload_1 * 375: invokevirtual #7 // Method org/apache/xalan/transformer/TransformerImpl.getMode:()Lorg/apache/xml/utils/QName; * 378: astore 23 * 380: aload 14 * 382: aload_2 * ? 383: iload 20 * 385: iload 21 * 387: aload 23 * 389: iconst_m1 * 390: iload 15 * 392: aload 16 * 394: invokevirtual #55 // Method org/apache/xalan/templates/TemplateList.getTemplateFast:(Lorg/apache/xpath/XPathContext;IILorg/apache/xml/utils/QName;IZLorg/apache/xml/dtm/DTM;)Lorg/apache/xalan/templates/ElemTemplate; * 397: astore 24 * 399: aconst_null * 400: aload 24 * 402: if_acmpne 526 * 405: iload 22 * 407: tableswitch { // 1 to 11 * * 1: 464 * * 2: 474 * * 3: 474 * * 4: 474 * * 5: 523 * * 6: 523 * * 7: 523 * * 8: 523 * * 9: 513 * * 10: 523 * * 11: 464 * default: 523 * } * 464: aload 13 * 466: invokevirtual #56 // Method org/apache/xalan/templates/StylesheetRoot.getDefaultRule:()Lorg/apache/xalan/templates/ElemTemplate; * 469: astore 24 * 471: goto 532 * 474: aload_1 * 475: aload 13 * 477: invokevirtual #57 // Method org/apache/xalan/templates/StylesheetRoot.getDefaultTextRule:()Lorg/apache/xalan/templates/ElemTemplate; * ? 480: iload 20 * 482: invokevirtual #58 // Method org/apache/xalan/transformer/TransformerImpl.pushPairCurrentMatched:(Lorg/apache/xalan/templates/ElemTemplateElement;I)V * 485: aload_1 * 486: aload 13 * 488: invokevirtual #57 // Method org/apache/xalan/templates/StylesheetRoot.getDefaultTextRule:()Lorg/apache/xalan/templates/ElemTemplate; * 491: invokevirtual #59 // Method org/apache/xalan/transformer/TransformerImpl.setCurrentElement:(Lorg/apache/xalan/templates/ElemTemplateElement;)V * 494: aload 16 * ? 496: iload 20 * 498: aload 12 * 500: iconst_0 * 501: invokeinterface #60, 4 // InterfaceMethod org/apache/xml/dtm/DTM.dispatchCharactersEvents:(ILorg/xml/sax/ContentHandler;Z)V * 506: aload_1 * 507: invokevirtual #61 // Method org/apache/xalan/transformer/TransformerImpl.popCurrentMatched:()V * 510: goto 831 * 513: aload 13 * 515: invokevirtual #62 // Method org/apache/xalan/templates/StylesheetRoot.getDefaultRootRule:()Lorg/apache/xalan/templates/ElemTemplate; * 518: astore 24 * 520: goto 532 * 523: goto 831 * 526: aload_1 * 527: aload 24 * 529: invokevirtual #59 // Method org/apache/xalan/transformer/TransformerImpl.setCurrentElement:(Lorg/apache/xalan/templates/ElemTemplateElement;)V * 532: aload_1 * 533: aload 24 * ? 535: iload 20 * 537: invokevirtual #58 // Method org/apache/xalan/transformer/TransformerImpl.pushPairCurrentMatched:(Lorg/apache/xalan/templates/ElemTemplateElement;I)V * 540: iload 9 * 542: ifeq 550 * 545: aload 8 * 547: invokevirtual #63 // Method org/apache/xalan/transformer/StackGuard.checkForInfinateLoop:()V * 550: aload 24 * 552: getfield #64 // Field org/apache/xalan/templates/ElemTemplate.m_frameSize:I * 555: ifle 713 * 558: aload_2 * 559: invokevirtual #65 // Method org/apache/xpath/XPathContext.pushRTFContext:()V * 562: aload 5 * 564: invokevirtual #23 // Method org/apache/xpath/VariableStack.getStackFrame:()I * 567: istore 25 * 569: aload 5 * 571: aload 24 * 573: getfield #64 // Field org/apache/xalan/templates/ElemTemplate.m_frameSize:I * 576: invokevirtual #44 // Method org/apache/xpath/VariableStack.link:(I)I * 579: pop * 580: aload 24 * 582: getfield #66 // Field org/apache/xalan/templates/ElemTemplate.m_inArgsSize:I * 585: ifle 716 * 588: iconst_0 * 589: istore 26 * 591: aload 24 * 593: invokevirtual #67 // Method org/apache/xalan/templates/ElemTemplateElement.getFirstChildElem:()Lorg/apache/xalan/templates/ElemTemplateElement; * 596: astore 27 * 598: goto 704 * 601: bipush 41 * 603: aload 27 * 605: invokevirtual #68 // Method org/apache/xalan/templates/ElemTemplateElement.getXSLToken:()I * 608: if_icmpne 710 * 611: aload 27 * 613: checkcast #69 // class org/apache/xalan/templates/ElemParam * 616: astore 28 * 618: iconst_0 * 619: istore 29 * 621: goto 672 * 624: aload_0 * 625: getfield #46 // Field org/apache/xalan/templates/ElemCallTemplate.m_paramElems:[Lorg/apache/xalan/templates/ElemWithParam; * 628: iload 29 * 630: aaload * 631: astore 30 * 633: aload 30 * 635: getfield #70 // Field org/apache/xalan/templates/ElemWithParam.m_qnameID:I * 638: aload 28 * 640: getfield #71 // Field org/apache/xalan/templates/ElemParam.m_qnameID:I * 643: if_icmpne 669 * 646: aload 5 * 648: iload 29 * 650: iload 17 * 652: invokevirtual #72 // Method org/apache/xpath/VariableStack.getLocalVariable:(II)Lorg/apache/xpath/objects/XObject; * 655: astore 31 * 657: aload 5 * 659: iload 26 * 661: aload 31 * 663: invokevirtual #73 // Method org/apache/xpath/VariableStack.setLocalVariable:(ILorg/apache/xpath/objects/XObject;)V * 666: goto 679 * 669: iinc 29, 1 * 672: iload 29 * 674: iload 6 * 676: if_icmplt 624 * 679: iload 29 * 681: iload 6 * 683: if_icmpne 694 * 686: aload 5 * 688: iload 26 * 690: aconst_null * 691: invokevirtual #73 // Method org/apache/xpath/VariableStack.setLocalVariable:(ILorg/apache/xpath/objects/XObject;)V * 694: iinc 26, 1 * 697: aload 27 * 699: invokevirtual #74 // Method org/apache/xalan/templates/ElemTemplateElement.getNextSiblingElem:()Lorg/apache/xalan/templates/ElemTemplateElement; * 702: astore 27 * 704: aconst_null * 705: aload 27 * 707: if_acmpne 601 * 710: goto 716 * 713: iconst_0 * 714: istore 25 * 716: getstatic #10 // Field org/apache/xalan/transformer/TransformerImpl.S_DEBUG:Z * 719: ifeq 731 * 722: aload_1 * 723: invokevirtual #11 // Method org/apache/xalan/transformer/TransformerImpl.getTraceManager:()Lorg/apache/xalan/trace/TraceManager; * 726: aload 24 * 728: invokevirtual #12 // Method org/apache/xalan/trace/TraceManager.fireTraceEvent:(Lorg/apache/xalan/templates/ElemTemplateElement;)V * 731: aload 24 * 733: getfield #75 // Field org/apache/xalan/templates/ElemTemplateElement.m_firstChild:Lorg/apache/xalan/templates/ElemTemplateElement; * 736: astore 26 * 738: goto 788 * 741: aload_2 * 742: aload 26 * 744: invokevirtual #76 // Method org/apache/xpath/XPathContext.setSAXLocator:(Ljavax/xml/transform/SourceLocator;)V * 747: aload_1 * 748: aload 26 * 750: invokevirtual #29 // Method org/apache/xalan/transformer/TransformerImpl.pushElemTemplateElement:(Lorg/apache/xalan/templates/ElemTemplateElement;)V * 753: aload 26 * 755: aload_1 * 756: invokevirtual #77 // Method org/apache/xalan/templates/ElemTemplateElement.execute:(Lorg/apache/xalan/transformer/TransformerImpl;)V * 759: jsr 773 * 762: goto 781 * 765: astore 32 * 767: jsr 773 * 770: aload 32 * 772: athrow * 773: astore 33 * 775: aload_1 * 776: invokevirtual #78 // Method org/apache/xalan/transformer/TransformerImpl.popElemTemplateElement:()V * 779: ret 33 * 781: aload 26 * 783: getfield #79 // Field org/apache/xalan/templates/ElemTemplateElement.m_nextSibling:Lorg/apache/xalan/templates/ElemTemplateElement; * 786: astore 26 * 788: aload 26 * 790: ifnonnull 741 * 793: getstatic #10 // Field org/apache/xalan/transformer/TransformerImpl.S_DEBUG:Z * 796: ifeq 808 * 799: aload_1 * 800: invokevirtual #11 // Method org/apache/xalan/transformer/TransformerImpl.getTraceManager:()Lorg/apache/xalan/trace/TraceManager; * 803: aload 24 * 805: invokevirtual #14 // Method org/apache/xalan/trace/TraceManager.fireTraceEndEvent:(Lorg/apache/xalan/templates/ElemTemplateElement;)V * 808: aload 24 * 810: getfield #64 // Field org/apache/xalan/templates/ElemTemplate.m_frameSize:I * 813: ifle 827 * 816: aload 5 * 818: iload 25 * 820: invokevirtual #80 // Method org/apache/xpath/VariableStack.unlink:(I)V * 823: aload_2 * 824: invokevirtual #81 // Method org/apache/xpath/XPathContext.popRTFContext:()V * 827: aload_1 * 828: invokevirtual #61 // Method org/apache/xalan/transformer/TransformerImpl.popCurrentMatched:()V * 831: iconst_m1 * 832: aload 4 * 834: invokeinterface #82, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.nextNode:()I * 839: dup * | 840: istore 20 * | 842: if_icmpne 319 * | 845: jsr 885 * 848: goto 970 * 851: astore 11 * 853: aload_1 * 854: invokevirtual #84 // Method org/apache/xalan/transformer/TransformerImpl.getErrorListener:()Ljavax/xml/transform/ErrorListener; * 857: new #85 // class javax/xml/transform/TransformerException * 860: dup * 861: aload 11 * 863: invokespecial #86 // Method javax/xml/transform/TransformerException."<init>":(Ljava/lang/Throwable;)V * 866: invokeinterface #87, 2 // InterfaceMethod javax/xml/transform/ErrorListener.fatalError:(Ljavax/xml/transform/TransformerException;)V * 871: jsr 885 * 874: goto 970 * 877: astore 34 * 879: jsr 885 * 882: aload 34 * 884: athrow * 885: astore 35 * 887: getstatic #10 // Field org/apache/xalan/transformer/TransformerImpl.S_DEBUG:Z * 890: ifeq 924 * 893: aload_1 * 894: invokevirtual #11 // Method org/apache/xalan/transformer/TransformerImpl.getTraceManager:()Lorg/apache/xalan/trace/TraceManager; * 897: iload_3 * 898: aload_0 * 899: ldc #33 // String select * 901: new #34 // class org/apache/xpath/XPath * 904: dup * 905: aload_0 * 906: getfield #19 // Field org/apache/xalan/templates/ElemForEach.m_selectExpression:Lorg/apache/xpath/Expression; * 909: invokespecial #35 // Method org/apache/xpath/XPath."<init>":(Lorg/apache/xpath/Expression;)V * 912: new #36 // class org/apache/xpath/objects/XNodeSet * 915: dup * 916: aload 4 * 918: invokespecial #37 // Method org/apache/xpath/objects/XNodeSet."<init>":(Lorg/apache/xml/dtm/DTMIterator;)V * 921: invokevirtual #88 // Method org/apache/xalan/trace/TraceManager.fireSelectedEndEvent:(ILorg/apache/xalan/templates/ElemTemplateElement;Ljava/lang/String;Lorg/apache/xpath/XPath;Lorg/apache/xpath/objects/XObject;)V * 924: iload 6 * 926: ifle 936 * 929: aload 5 * 931: iload 7 * 933: invokevirtual #80 // Method org/apache/xpath/VariableStack.unlink:(I)V * 936: aload_2 * 937: invokevirtual #89 // Method org/apache/xpath/XPathContext.popSAXLocator:()V * 940: iload 10 * 942: ifeq 949 * 945: aload_2 * 946: invokevirtual #90 // Method org/apache/xpath/XPathContext.popContextNodeList:()V * 949: aload_1 * 950: invokevirtual #78 // Method org/apache/xalan/transformer/TransformerImpl.popElemTemplateElement:()V * 953: aload_2 * 954: invokevirtual #91 // Method org/apache/xpath/XPathContext.popCurrentExpressionNode:()V * 957: aload_2 * 958: invokevirtual #92 // Method org/apache/xpath/XPathContext.popCurrentNode:()V * 961: aload 4 * 963: invokeinterface #93, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.detach:()V * 968: ret 35 * 970: return * Exception table: * from to target type * 747 765 765 any * 65 845 851 Class org/xml/sax/SAXException * 65 877 877 any * LocalVariableTable: * Start Length Slot Name Signature * 0 971 0 this Lorg/apache/xalan/templates/ElemApplyTemplates; * 0 971 1 transformer Lorg/apache/xalan/transformer/TransformerImpl; * 5 965 2 xctxt Lorg/apache/xpath/XPathContext; * 10 960 3 sourceNode I * 21 949 4 sourceNodes Lorg/apache/xml/dtm/DTMIterator; * 27 943 5 vars Lorg/apache/xpath/VariableStack; * 33 937 6 nParams I * 40 930 7 thisframe I * 46 924 8 guard Lorg/apache/xalan/transformer/StackGuard; * 62 908 9 check Z * 65 905 10 pushContextNodeListFlag Z * 103 742 11 keys Ljava/util/Vector; * 163 682 12 rth Lorg/apache/xml/serializer/SerializationHandler; * 169 676 13 sroot Lorg/apache/xalan/templates/StylesheetRoot; * 176 669 14 tl Lorg/apache/xalan/templates/TemplateList; * 182 663 15 quiet Z * 189 656 16 dtm Lorg/apache/xml/dtm/DTM; * 192 653 17 argsFrame I * 216 79 18 i I * 228 50 19 ewp Lorg/apache/xalan/templates/ElemWithParam; * 252 26 20 obj Lorg/apache/xpath/objects/XObject; * 310 535 18 currentNodes Lorg/apache/xml/utils/IntStack; * 316 529 19 currentExpressionNodes Lorg/apache/xml/utils/IntStack; * 842 3 20 child I * 363 468 21 exNodeType I * 374 457 22 nodeType I * 380 451 23 mode Lorg/apache/xml/utils/QName; * 399 432 24 template Lorg/apache/xalan/templates/ElemTemplate; * 569 262 25 currentFrameBottom I * 591 119 26 paramIndex I * 598 112 27 elem Lorg/apache/xalan/templates/ElemTemplateElement; * 618 76 28 ep Lorg/apache/xalan/templates/ElemParam; * 621 73 29 i I * 633 36 30 ewp Lorg/apache/xalan/templates/ElemWithParam; * 657 12 31 obj Lorg/apache/xpath/objects/XObject; * 738 93 26 t Lorg/apache/xalan/templates/ElemTemplateElement; * 853 117 11 se Lorg/xml/sax/SAXException; * Exceptions: * throws javax.xml.transform.TransformerException * </pre></code> */ @Test public void testElemApplyTemplates() { final String clazz = "org.apache.xalan.templates.ElemApplyTemplates"; final String[] params = { "org.apache.xalan.transformer.TransformerImpl" }; runXalanTest(prepareTarget(methodSigFromComponents(clazz, "void", "transformSelectedNodes", params), clazz)); } /** * Below is the output of "javap -verbose" for the relevant method. The '|' character was added to mark the ranges where * the LocalVariableTable specifies a variable name for local slot 10. Notice there is an additional use of slot 10 at * offset 53 which does not appear in any of the specified ranges which means the local variable name for that use is * unknown. * * <code><pre> * public boolean compare(org.apache.xpath.objects.XObject, org.apache.xpath.objects.Comparator) throws javax.xml.transform.TransformerException; * descriptor: (Lorg/apache/xpath/objects/XObject;Lorg/apache/xpath/objects/Comparator;)Z * flags: ACC_PUBLIC * Code: * stack=5, locals=12, args_size=3 * 0: iconst_0 * 1: istore_3 * 2: aload_1 * 3: invokevirtual #48 // Method org/apache/xpath/objects/XObject.getType:()I * 6: istore 4 * 8: iconst_4 * 9: iload 4 * 11: if_icmpne 193 * 14: aload_0 * 15: invokevirtual #49 // Method iterRaw:()Lorg/apache/xml/dtm/DTMIterator; * 18: astore 5 * 20: aload_1 * 21: checkcast #2 // class org/apache/xpath/objects/XNodeSet * 24: invokevirtual #49 // Method iterRaw:()Lorg/apache/xml/dtm/DTMIterator; * 27: astore 6 * 29: aconst_null * 30: astore 8 * 32: goto 162 * 35: aload_0 * 36: iload 7 * 38: invokevirtual #26 // Method getStringFromNode:(I)Lorg/apache/xml/utils/XMLString; * 41: astore 9 * 43: aconst_null * 44: aload 8 * 46: if_acmpne 115 * 49: goto 98 * 52: aload_0 * ? 53: iload 10 * 55: invokevirtual #26 // Method getStringFromNode:(I)Lorg/apache/xml/utils/XMLString; * 58: astore 11 * 60: aload_2 * 61: aload 9 * 63: aload 11 * 65: invokevirtual #50 // Method org/apache/xpath/objects/Comparator.compareStrings:(Lorg/apache/xml/utils/XMLString;Lorg/apache/xml/utils/XMLString;)Z * 68: ifeq 76 * 71: iconst_1 * 72: istore_3 * 73: goto 112 * 76: aconst_null * 77: aload 8 * 79: if_acmpne 91 * 82: new #51 // class java/util/Vector * 85: dup * 86: invokespecial #52 // Method java/util/Vector."<init>":()V * 89: astore 8 * 91: aload 8 * 93: aload 11 * 95: invokevirtual #53 // Method java/util/Vector.addElement:(Ljava/lang/Object;)V * 98: iconst_m1 * 99: aload 6 * 101: invokeinterface #54, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.nextNode:()I * 106: dup * | 107: istore 10 * | 109: if_icmpne 52 * | 112: goto 162 * 115: aload 8 * 117: invokevirtual #55 // Method java/util/Vector.size:()I * | 120: istore 10 * | 122: iconst_0 * | 123: istore 11 * | 125: goto 155 * | 128: aload_2 * | 129: aload 9 * | 131: aload 8 * | 133: iload 11 * | 135: invokevirtual #56 // Method java/util/Vector.elementAt:(I)Ljava/lang/Object; * | 138: checkcast #57 // class org/apache/xml/utils/XMLString * | 141: invokevirtual #50 // Method org/apache/xpath/objects/Comparator.compareStrings:(Lorg/apache/xml/utils/XMLString;Lorg/apache/xml/utils/XMLString;)Z * | 144: ifeq 152 * | 147: iconst_1 * | 148: istore_3 * | 149: goto 162 * | 152: iinc 11, 1 * | 155: iload 11 * | 157: iload 10 * | 159: if_icmplt 128 * | 162: iconst_m1 * 163: aload 5 * 165: invokeinterface #54, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.nextNode:()I * 170: dup * 171: istore 7 * 173: if_icmpne 35 * 176: aload 5 * 178: invokeinterface #58, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.reset:()V * 183: aload 6 * 185: invokeinterface #58, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.reset:()V * 190: goto 451 * 193: iconst_1 * 194: iload 4 * 196: if_icmpne 231 * 199: aload_0 * 200: invokevirtual #59 // Method bool:()Z * 203: ifeq 210 * 206: dconst_1 * 207: goto 211 * 210: dconst_0 * 211: dstore 5 * 213: aload_1 * 214: invokevirtual #60 // Method org/apache/xpath/objects/XObject.num:()D * 217: dstore 7 * 219: aload_2 * 220: dload 5 * 222: dload 7 * 224: invokevirtual #61 // Method org/apache/xpath/objects/Comparator.compareNumbers:(DD)Z * 227: istore_3 * 228: goto 451 * 231: iconst_2 * 232: iload 4 * 234: if_icmpne 300 * 237: aload_0 * 238: invokevirtual #49 // Method iterRaw:()Lorg/apache/xml/dtm/DTMIterator; * 241: astore 5 * 243: aload_1 * 244: invokevirtual #60 // Method org/apache/xpath/objects/XObject.num:()D * 247: dstore 6 * 249: goto 276 * 252: aload_0 * 253: iload 8 * 255: invokevirtual #20 // Method getNumberFromNode:(I)D * 258: dstore 9 * 260: aload_2 * 261: dload 9 * 263: dload 6 * 265: invokevirtual #61 // Method org/apache/xpath/objects/Comparator.compareNumbers:(DD)Z * 268: ifeq 276 * 271: iconst_1 * 272: istore_3 * 273: goto 290 * 276: iconst_m1 * 277: aload 5 * 279: invokeinterface #54, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.nextNode:()I * 284: dup * 285: istore 8 * 287: if_icmpne 252 * 290: aload 5 * 292: invokeinterface #58, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.reset:()V * 297: goto 451 * 300: iconst_5 * 301: iload 4 * 303: if_icmpne 369 * 306: aload_1 * 307: invokevirtual #62 // Method org/apache/xpath/objects/XObject.xstr:()Lorg/apache/xml/utils/XMLString; * 310: astore 5 * 312: aload_0 * 313: invokevirtual #49 // Method iterRaw:()Lorg/apache/xml/dtm/DTMIterator; * 316: astore 6 * 318: goto 345 * 321: aload_0 * 322: iload 7 * 324: invokevirtual #26 // Method getStringFromNode:(I)Lorg/apache/xml/utils/XMLString; * 327: astore 8 * 329: aload_2 * 330: aload 8 * 332: aload 5 * 334: invokevirtual #50 // Method org/apache/xpath/objects/Comparator.compareStrings:(Lorg/apache/xml/utils/XMLString;Lorg/apache/xml/utils/XMLString;)Z * 337: ifeq 345 * 340: iconst_1 * 341: istore_3 * 342: goto 359 * 345: iconst_m1 * 346: aload 6 * 348: invokeinterface #54, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.nextNode:()I * 353: dup * 354: istore 7 * 356: if_icmpne 321 * 359: aload 6 * 361: invokeinterface #58, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.reset:()V * 366: goto 451 * 369: iconst_3 * 370: iload 4 * 372: if_icmpne 438 * 375: aload_1 * 376: invokevirtual #62 // Method org/apache/xpath/objects/XObject.xstr:()Lorg/apache/xml/utils/XMLString; * 379: astore 5 * 381: aload_0 * 382: invokevirtual #49 // Method iterRaw:()Lorg/apache/xml/dtm/DTMIterator; * 385: astore 6 * 387: goto 414 * 390: aload_0 * 391: iload 7 * 393: invokevirtual #26 // Method getStringFromNode:(I)Lorg/apache/xml/utils/XMLString; * 396: astore 8 * 398: aload_2 * 399: aload 8 * 401: aload 5 * 403: invokevirtual #50 // Method org/apache/xpath/objects/Comparator.compareStrings:(Lorg/apache/xml/utils/XMLString;Lorg/apache/xml/utils/XMLString;)Z * 406: ifeq 414 * 409: iconst_1 * 410: istore_3 * 411: goto 428 * 414: iconst_m1 * 415: aload 6 * 417: invokeinterface #54, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.nextNode:()I * 422: dup * 423: istore 7 * 425: if_icmpne 390 * 428: aload 6 * 430: invokeinterface #58, 1 // InterfaceMethod org/apache/xml/dtm/DTMIterator.reset:()V * 435: goto 451 * 438: aload_2 * 439: aload_0 * 440: invokevirtual #63 // Method num:()D * 443: aload_1 * 444: invokevirtual #60 // Method org/apache/xpath/objects/XObject.num:()D * 447: invokevirtual #61 // Method org/apache/xpath/objects/Comparator.compareNumbers:(DD)Z * 450: istore_3 * 451: iload_3 * 452: ireturn * LocalVariableTable: * Start Length Slot Name Signature * 0 453 0 this Lorg/apache/xpath/objects/XNodeSet; * 0 453 1 obj2 Lorg/apache/xpath/objects/XObject; * 0 453 2 comparator Lorg/apache/xpath/objects/Comparator; * 2 451 3 result Z * 8 445 4 type I * 20 170 5 list1 Lorg/apache/xml/dtm/DTMIterator; * 29 161 6 list2 Lorg/apache/xml/dtm/DTMIterator; * 173 17 7 node1 I * 32 158 8 node2Strings Ljava/util/Vector; * 43 119 9 s1 Lorg/apache/xml/utils/XMLString; * 109 3 10 node2 I * 60 38 11 s2 Lorg/apache/xml/utils/XMLString; * 122 40 10 n I * 125 37 11 i I * 213 15 5 num1 D * 219 9 7 num2 D * 243 54 5 list1 Lorg/apache/xml/dtm/DTMIterator; * 249 48 6 num2 D * 287 10 8 node I * 260 16 9 num1 D * 312 54 5 s2 Lorg/apache/xml/utils/XMLString; * 318 48 6 list1 Lorg/apache/xml/dtm/DTMIterator; * 356 10 7 node I * 329 16 8 s1 Lorg/apache/xml/utils/XMLString; * 381 54 5 s2 Lorg/apache/xml/utils/XMLString; * 387 48 6 list1 Lorg/apache/xml/dtm/DTMIterator; * 425 10 7 node I * 398 16 8 s1 Lorg/apache/xml/utils/XMLString; * Exceptions: * throws javax.xml.transform.TransformerException * </pre></code> */ @Test public void testXNodeSet() { final String clazz = "org.apache.xpath.objects.XNodeSet"; final String[] params = { "org.apache.xpath.objects.XObject", "org.apache.xpath.objects.Comparator" }; runXalanTest(prepareTarget(methodSigFromComponents(clazz, "boolean", "compare", params), clazz)); } private void runXalanTest(SootMethod m) { Body body = m.retrieveActiveBody(); // Run CheckInitValidator to ensure the special case for "use-original-names" // in AsmMethodSource did not cause any problems when replacing locals. ArrayList<ValidationException> exceptions = new ArrayList<>(); CheckInitValidator.INSTANCE.validate(body, exceptions); Assert.assertTrue(exceptions.isEmpty()); } }
58,746
45.477057
246
java
soot
soot-master/src/systemTest/java/soot/asm/AsmMethodSourceTest.java
package soot.asm; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2020 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Body; import soot.Local; import soot.SootMethod; import soot.Unit; import soot.UnitPatchingChain; import soot.jimple.Jimple; import soot.jimple.NopStmt; import soot.options.Options; import soot.testing.framework.AbstractTestingFramework; import soot.util.HashChain; /** @author Manuel Benz at 13.02.20 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class AsmMethodSourceTest extends AbstractTestingFramework { private static final String TEST_TARGET_CLASS = "soot.asm.LineNumberExtraction"; @Override protected void setupSoot() { final Options opts = Options.v(); opts.setPhaseOption("jb", "use-original-names:true"); opts.setPhaseOption("jb.sils", "enabled:false"); opts.setPhaseOption("jb.tr", "ignore-nullpointer-dereferences:true"); opts.setPhaseOption("cg", "enabled:false"); opts.set_keep_line_number(true); } @Test public void iterator() { // statements at the beginning of a for loop should have the line number as for the branching // statement and not the last line number after the branch that leads outside the loop SootMethod target = prepareTarget(methodSigFromComponents(TEST_TARGET_CLASS, "void", "iterator"), TEST_TARGET_CLASS); Body body = target.retrieveActiveBody(); Optional<Unit> unit = body.getUnits().stream() .filter(u -> u.toString().contains("<java.util.Iterator: java.lang.Object next()>()")).findFirst(); Assert.assertTrue(unit.isPresent()); Assert.assertEquals(31, unit.get().getJavaSourceStartLineNumber()); } @Test public void localNaming() { // This test ensures that local names are preserved in the Jimple code. final String className = "soot.asm.LocalNaming"; final String[] params = { "java.lang.String", "java.lang.Integer", "byte[]", "java.lang.StringBuilder" }; SootMethod target = prepareTarget(methodSigFromComponents(className, "void", "localNaming", params), className); Body body = target.retrieveActiveBody(); Set<String> localNames = body.getLocals().stream().map(Local::getName).collect(Collectors.toSet()); // All expected Local names are present Assert.assertTrue(localNames.contains("alpha")); Assert.assertTrue(localNames.contains("beta")); Assert.assertTrue(localNames.contains("gamma")); Assert.assertTrue(localNames.contains("delta")); Assert.assertTrue(localNames.contains("epsilon")); Assert.assertTrue(localNames.contains("zeta")); Assert.assertTrue(localNames.contains("eta")); Assert.assertTrue(localNames.contains("theta")); Assert.assertTrue(localNames.contains("iota")); Assert.assertTrue(localNames.contains("omega")); // No Local name contains "$stack" Assert.assertTrue(localNames.stream().allMatch(n -> !n.contains("$stack"))); } /** * This is the case phase jb.sils is disabled. see the case phase jb.sils is enabled in {@link SilsTest#testSilsEnabled()} */ @Test public void testSilsDisabled() { final String className = "soot.asm.LocalNaming"; final String[] params = {}; SootMethod target = prepareTarget(methodSigFromComponents(className, "void", "test", params), className); Body body = target.retrieveActiveBody(); Set<String> localNames = body.getLocals().stream().map(Local::getName).collect(Collectors.toSet()); // test if all expected Local names are present Assert.assertTrue(localNames.contains("d")); Assert.assertTrue(localNames.contains("f")); Assert.assertTrue(localNames.contains("arr")); } @Test public void testInner() { NopStmt[] nops = new NopStmt[6]; for (int i = 0; i < nops.length; i++) { nops[i] = Jimple.v().newNopStmt(); } UnitPatchingChain chainNew = new UnitPatchingChain(new HashChain<Unit>()); UnitContainer container = new UnitContainer(nops[0], new UnitContainer(nops[1], new UnitContainer(nops[2]), nops[3]), nops[4], new UnitContainer(nops[5])); AsmMethodSource.emitUnits(container, chainNew); UnitPatchingChain chainOld = new UnitPatchingChain(new HashChain<Unit>()); oldEmitImplementation(container, chainOld); Assert.assertEquals(chainOld.size(), chainNew.size()); Iterator<Unit> itO = chainOld.iterator(); Iterator<Unit> itN = chainNew.iterator(); while (itO.hasNext()) { Unit oo = itO.next(); Unit nn = itN.next(); if (oo != nn) { Assert.fail(); } } } private void oldEmitImplementation(Unit u, UnitPatchingChain c) { if (u instanceof UnitContainer) { for (Unit uu : ((UnitContainer) u).units) { oldEmitImplementation(uu, c); } } else { c.add(u); } } }
5,738
36.509804
124
java
soot
soot-master/src/systemTest/java/soot/asm/ResolveFieldInitializersTest.java
package soot.asm; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2020 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertEquals; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Scene; import soot.SootClass; import soot.testing.framework.AbstractTestingFramework; /** @author Manuel Benz at 20.02.20 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class ResolveFieldInitializersTest extends AbstractTestingFramework { private static final String TEST_TARGET_CLASS = "soot.asm.ResolveFieldInitializers"; @Test public void initializedInMethodRef() { prepareTarget(methodSigFromComponents(TEST_TARGET_CLASS, "void", "<init>"), TEST_TARGET_CLASS); SootClass sootClass = Scene.v().getSootClass("java.util.ArrayDeque"); assertEquals(SootClass.SIGNATURES, sootClass.resolvingLevel()); } @Test public void initializedInConstructor() { prepareTarget(methodSigFromComponents(TEST_TARGET_CLASS, "void", "<init>"), TEST_TARGET_CLASS); SootClass sootClass = Scene.v().getSootClass("java.util.LinkedList"); assertEquals(SootClass.SIGNATURES, sootClass.resolvingLevel()); } }
1,942
34.981481
99
java
soot
soot-master/src/systemTest/java/soot/asm/SilsTest.java
package soot.asm; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Set; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Body; import soot.Local; import soot.SootMethod; import soot.options.Options; import soot.testing.framework.AbstractTestingFramework; /** * Test for the phase "jb.sils" * * @author Linghui Luo */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class SilsTest extends AbstractTestingFramework { @Override protected void setupSoot() { final Options opts = Options.v(); opts.setPhaseOption("jb", "use-original-names:true"); opts.setPhaseOption("jb.sils", "enabled:true"); opts.setPhaseOption("jb.tr", "ignore-nullpointer-dereferences:true"); opts.setPhaseOption("cg", "enabled:false"); } /** * This is the case phase jb.sils is enabled (default). see the case phase jb.sils is disabled in * {@link AsmMethodSourceTest#testSilsDisabled()} */ @Test @Ignore public void testSilsEnabled() { final String className = "soot.asm.LocalNaming"; final String[] params = {}; SootMethod target = prepareTarget(methodSigFromComponents(className, "void", "test", params), className); Body body = target.retrieveActiveBody(); Set<String> localNames = body.getLocals().stream().map(Local::getName).collect(Collectors.toSet()); // test if all expected Local names are present // currently d, f are not preserved. Assert.assertTrue(localNames.contains("d")); Assert.assertTrue(localNames.contains("f")); Assert.assertTrue(localNames.contains("arr")); } }
2,526
32.693333
109
java
soot
soot-master/src/systemTest/java/soot/defaultInterfaceMethods/DefaultInterfaceTest.java
package soot.defaultInterfaceMethods; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2019 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 static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Body; import soot.FastHierarchy; import soot.MethodOrMethodContext; import soot.PhaseOptions; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.UnitPatchingChain; import soot.jimple.Stmt; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.jimple.toolkits.callgraph.VirtualCalls; import soot.testing.framework.AbstractTestingFramework; /** */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class DefaultInterfaceTest extends AbstractTestingFramework { private static String voidType = "void"; private static String mainClass = "main"; @Override protected void setupSoot() { super.setupSoot(); PhaseOptions.v().setPhaseOption("cg.cha", "on"); } @Test public void SubClassTest() throws FileNotFoundException, UnsupportedEncodingException { String testClass = "soot.defaultInterfaceMethods.JavaNCSSCheck"; String abstractClass = "soot.defaultInterfaceDifferentPackage.AbstractCheck"; String classToAnalyze = "soot.defaultInterfaceDifferentPackage.AbstractCheck"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, voidType, mainClass), testClass, classToAnalyze); ArrayList<Edge> edges = GetCallGraph(); assertEquals(edges.get(0).getTgt(), Scene.v().getMethod("<soot.defaultInterfaceDifferentPackage.AbstractCheck: void log(java.lang.String,java.lang.String)>")); } @Test public void simpleDefaultInterfaceTest() { String testClass = "soot.defaultInterfaceMethods.SimpleDefaultInterface"; String defaultClass = "soot.defaultInterfaceMethods.Default"; String classToAnalyze = "soot.defaultInterfaceMethods.Default"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, voidType, mainClass), testClass, classToAnalyze); SootMethod defaultMethod = Scene.v().getMethod("<soot.defaultInterfaceMethods.Default: void target()>"); Body body = target.retrieveActiveBody(); SootMethod targetMethod = resolveMethodRefInBody(body.getUnits(), "void target()"); SootMethod resolvedMethod = VirtualCalls.v() .resolveNonSpecial(Scene.v().getRefType(testClass), defaultMethod.makeRef(), false); SootMethod concreteImpl = Scene.v() .getFastHierarchy() .resolveConcreteDispatch(Scene.v().getSootClass(testClass), defaultMethod); SootMethod concreteImplViaResolveMethod = Scene.v() .getFastHierarchy() .resolveMethod(Scene.v().getSootClass(testClass), defaultMethod, false); Set<SootMethod> abstractImpl = Scene.v() .getFastHierarchy() .resolveAbstractDispatch(Scene.v().getSootClass(defaultClass), defaultMethod); boolean edgePresent = checkInEdges(defaultMethod, target); final ReachableMethods reachableMethods = Scene.v().getReachableMethods(); /* Arguments for assert function */ assertEquals(defaultMethod, resolvedMethod); assertEquals(defaultMethod, targetMethod); assertEquals(defaultMethod.getName(), "target"); assertNotNull(defaultMethod); assertTrue(reachableMethods.contains(defaultMethod)); assertTrue(edgePresent); assertEquals(defaultMethod, concreteImpl); assertEquals(concreteImpl, concreteImplViaResolveMethod); assertTrue( abstractImpl.contains( Scene.v().getMethod("<soot.defaultInterfaceMethods.Default: void target()>"))); } @Test public void interfaceSameSignatureTest() { String testClassSig = "soot.defaultInterfaceMethods.InterfaceSameSignature"; String interfaceReadSig = "soot.defaultInterfaceMethods.Read"; String interfaceWriteSig = "soot.defaultInterfaceMethods.Write"; final SootMethod target = prepareTarget( methodSigFromComponents(testClassSig, voidType, mainClass), testClassSig, interfaceReadSig, interfaceWriteSig); SootClass testClass = Scene.v().getSootClass(testClassSig); SootClass interfaceRead = Scene.v().getSootClass(interfaceReadSig); SootClass interfaceWrite = Scene.v().getSootClass(interfaceWriteSig); SootMethod mainPrintMethod = Scene.v().getMethod("<soot.defaultInterfaceMethods.InterfaceSameSignature: void print()>"); SootMethod readInterfacePrint = Scene.v().getMethod("<soot.defaultInterfaceMethods.Read: void print()>"); SootMethod writeInterfacePrint = Scene.v().getMethod("<soot.defaultInterfaceMethods.Write: void print()>"); SootMethod readInterfaceRead = Scene.v().getMethod("<soot.defaultInterfaceMethods.Read: void read()>"); SootMethod writeInterfaceWrite = Scene.v().getMethod("<soot.defaultInterfaceMethods.Write: void write()>"); Body mainBody = target.retrieveActiveBody(); Body mainPrintBody = mainPrintMethod.retrieveActiveBody(); SootMethod refMainMethod = resolveMethodRefInBody(mainBody.getUnits(), "void print()"); SootMethod refWritePrintMethod = resolveMethodRefInBody( mainPrintBody.getUnits(), "soot.defaultInterfaceMethods.Write: void print()"); SootMethod refReadPrintMethod = resolveMethodRefInBody( mainPrintBody.getUnits(), "soot.defaultInterfaceMethods.Read: void print()"); SootMethod refDefaultRead = resolveMethodRefInBody(mainBody.getUnits(), "void read()"); SootMethod refDefaultWrite = resolveMethodRefInBody(mainBody.getUnits(), "void write()"); SootMethod resolvedMainMethod = VirtualCalls.v() .resolveNonSpecial( Scene.v().getRefType(testClassSig), mainPrintMethod.makeRef(), false); SootMethod resolvedWritePrintMethod = VirtualCalls.v() .resolveNonSpecial( Scene.v().getRefType(testClassSig), writeInterfacePrint.makeRef(), false); SootMethod resolvedReadPrintMethod = VirtualCalls.v() .resolveNonSpecial( Scene.v().getRefType(testClassSig), readInterfacePrint.makeRef(), false); SootMethod resolvedDefaultReadMethod = VirtualCalls.v() .resolveNonSpecial( Scene.v().getRefType(testClassSig), readInterfaceRead.makeRef(), false); SootMethod resolvedDefaultWriteMethod = VirtualCalls.v() .resolveNonSpecial( Scene.v().getRefType(testClassSig), writeInterfaceWrite.makeRef(), false); FastHierarchy fh = Scene.v().getFastHierarchy(); SootMethod concreteImplMainPrint = fh.resolveConcreteDispatch(testClass, mainPrintMethod); SootMethod concreteImplWritePrint = fh.resolveConcreteDispatch(testClass, refWritePrintMethod); SootMethod concreteImplReadPrint = fh.resolveConcreteDispatch(testClass, refReadPrintMethod); SootMethod concreteImplDefaultRead = fh.resolveConcreteDispatch(testClass, refDefaultRead); SootMethod concreteImplDefaultWrite = fh.resolveConcreteDispatch(testClass, refDefaultWrite); assertEquals( Sets.newHashSet(readInterfaceRead), fh.resolveAbstractDispatch(interfaceRead, refDefaultRead)); assertEquals( Sets.newHashSet(writeInterfaceWrite), fh.resolveAbstractDispatch(interfaceWrite, refDefaultWrite)); assertEquals( Sets.newHashSet(mainPrintMethod), fh.resolveAbstractDispatch(interfaceRead, refReadPrintMethod)); assertEquals( Sets.newHashSet(mainPrintMethod), fh.resolveAbstractDispatch(interfaceWrite, refWritePrintMethod)); /* Edges should be present */ boolean edgeMainPrintToReadPrint = checkInEdges(readInterfacePrint, mainPrintMethod); boolean edgeMainPrintToWritePrint = checkInEdges(writeInterfacePrint, mainPrintMethod); boolean edgeMainMethodToPrint = checkInEdges(mainPrintMethod, target); boolean edgeMainMethodToReadMethod = checkInEdges(readInterfaceRead, target); boolean edgeMainMethodToWriteMethod = checkInEdges(writeInterfaceWrite, target); /* Edges should not be present */ boolean edgeMainMethodToReadPrint = checkInEdges(readInterfacePrint, target); boolean edgeMainMethodToWritePrint = checkInEdges(writeInterfacePrint, target); final ReachableMethods reachableMethods = Scene.v().getReachableMethods(); /* Arguments for assert function */ Map<SootMethod, String> targetMethods = new HashMap<SootMethod, String>() { { put(mainPrintMethod, "print"); put(readInterfacePrint, "print"); put(writeInterfacePrint, "print"); put(readInterfaceRead, "read"); put(writeInterfaceWrite, "write"); } }; Map<SootMethod, SootMethod> resolvedMethods = new HashMap<SootMethod, SootMethod>() { { put(mainPrintMethod, resolvedMainMethod); put(mainPrintMethod, resolvedWritePrintMethod); put(mainPrintMethod, resolvedReadPrintMethod); put(readInterfaceRead, resolvedDefaultReadMethod); put(writeInterfaceWrite, resolvedDefaultWriteMethod); } }; Map<SootMethod, SootMethod> methodRef = new HashMap<SootMethod, SootMethod>() { { put(mainPrintMethod, refMainMethod); put(writeInterfacePrint, refWritePrintMethod); put(readInterfacePrint, refReadPrintMethod); put(readInterfaceRead, refDefaultRead); put(writeInterfaceWrite, refDefaultWrite); } }; Map<SootMethod, SootMethod> concreteImpl = new HashMap<SootMethod, SootMethod>() { { put(mainPrintMethod, concreteImplMainPrint); put(mainPrintMethod, concreteImplWritePrint); put(mainPrintMethod, concreteImplReadPrint); put(readInterfaceRead, concreteImplDefaultRead); put(writeInterfaceWrite, concreteImplDefaultWrite); } }; ArrayList<Boolean> edgePresent = new ArrayList<Boolean>() { { add(edgeMainPrintToReadPrint); add(edgeMainPrintToWritePrint); add(edgeMainMethodToPrint); add(edgeMainMethodToReadMethod); add(edgeMainMethodToWriteMethod); } }; ArrayList<Boolean> edgeNotPresent = new ArrayList<Boolean>() { { add(edgeMainMethodToReadPrint); add(edgeMainMethodToWritePrint); } }; for (Map.Entry<SootMethod, String> targetMethod : targetMethods.entrySet()) { assertNotNull(targetMethod.getKey()); } for (Map.Entry<SootMethod, SootMethod> virtualResolvedMethod : resolvedMethods.entrySet()) { assertEquals(virtualResolvedMethod.getKey(), virtualResolvedMethod.getValue()); } for (Map.Entry<SootMethod, SootMethod> methodRef1 : methodRef.entrySet()) { assertEquals(methodRef1.getKey(), methodRef1.getValue()); } for (Map.Entry<SootMethod, String> targetMethod : targetMethods.entrySet()) { assertEquals(targetMethod.getKey().getName(), targetMethod.getValue()); } for (Map.Entry<SootMethod, String> targetMethod : targetMethods.entrySet()) { assertTrue(reachableMethods.contains(targetMethod.getKey())); } for (boolean isPresent : edgePresent) { assertTrue(isPresent); } for (boolean notPresent : edgeNotPresent) { assertFalse(notPresent); } for (Map.Entry<SootMethod, SootMethod> concreteImpl1 : concreteImpl.entrySet()) { assertEquals(concreteImpl1.getKey(), concreteImpl1.getValue()); } } @Test public void classInterfaceWithSameSignatureTest() { String testClass = "soot.defaultInterfaceMethods.ClassInterfaceSameSignature"; String defaultClass = "soot.defaultInterfaceMethods.HelloWorld"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, voidType, mainClass), testClass, defaultClass); SootMethod mainPrintMethod = Scene.v() .getMethod("<soot.defaultInterfaceMethods.ClassInterfaceSameSignature: void print()>"); SootMethod defaultPrintMethod = Scene.v().getMethod("<soot.defaultInterfaceMethods.HelloWorld: void print()>"); Body mainBody = target.retrieveActiveBody(); SootMethod refMainMethod = resolveMethodRefInBody(mainBody.getUnits(), "void print()"); SootMethod resolvedMethod = VirtualCalls.v() .resolveNonSpecial( Scene.v().getRefType(testClass), defaultPrintMethod.makeRef(), false); SootMethod concreteImpl = Scene.v() .getFastHierarchy() .resolveConcreteDispatch(Scene.v().getSootClass(testClass), defaultPrintMethod); Set<SootMethod> abstractImpl = Scene.v() .getFastHierarchy() .resolveAbstractDispatch(Scene.v().getSootClass(defaultClass), defaultPrintMethod); boolean edgeMainMethodToMainPrint = checkInEdges(mainPrintMethod, target); boolean edgeMainPrintToDefaultPrint = checkInEdges(defaultPrintMethod, target); final ReachableMethods reachableMethods = Scene.v().getReachableMethods(); Map<SootMethod, String> targetMethods = new HashMap<SootMethod, String>() { { put(mainPrintMethod, "print"); put(defaultPrintMethod, "print"); } }; ArrayList<Boolean> edgePresent = new ArrayList<Boolean>() { { add(edgeMainMethodToMainPrint); } }; for (Map.Entry<SootMethod, String> targetMethod : targetMethods.entrySet()) { assertNotNull(targetMethod.getKey()); } assertEquals(mainPrintMethod, resolvedMethod); assertEquals(mainPrintMethod, refMainMethod); for (Map.Entry<SootMethod, String> targetMethod : targetMethods.entrySet()) { assertEquals(targetMethod.getKey().getName(), targetMethod.getValue()); } assertTrue(reachableMethods.contains(mainPrintMethod)); for (boolean isPresent : edgePresent) { assertTrue(isPresent); } assertEquals(mainPrintMethod, concreteImpl); assertTrue( abstractImpl.contains( Scene.v() .getMethod( "<soot.defaultInterfaceMethods.ClassInterfaceSameSignature: void print()>"))); } @Test public void superClassInterfaceWithSameSignatureTest() { String testClass = "soot.defaultInterfaceMethods.SuperClassInterfaceSameSignature"; String defaultClass = "soot.defaultInterfaceMethods.PrintInterface"; String defaultSuperClass = "soot.defaultInterfaceMethods.DefaultPrint"; String superClassImplementsInterface = "soot.defaultInterfaceMethods.SuperClassImplementsInterface"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, voidType, mainClass), testClass, defaultClass, superClassImplementsInterface); SootMethod defaultSuperMainMethod = Scene.v() .getMethod("<soot.defaultInterfaceMethods.SuperClassImplementsInterface: void main()>"); SootMethod mainMethod = Scene.v() .getMethod( "<soot.defaultInterfaceMethods.SuperClassImplementsInterface: void print()>"); SootMethod defaultMethod = Scene.v().getMethod("<soot.defaultInterfaceMethods.PrintInterface: void print()>"); SootMethod defaultSuperClassMethod = Scene.v().getMethod("<soot.defaultInterfaceMethods.DefaultPrint: void print()>"); Body mainBody = target.retrieveActiveBody(); SootMethod refMainMethod = resolveMethodRefInBody(mainBody.getUnits(), "void print()"); SootMethod resolvedMethod = VirtualCalls.v() .resolveNonSpecial(Scene.v().getRefType(testClass), defaultMethod.makeRef(), false); SootMethod resolvedSuperClassDefaultMethod = VirtualCalls.v() .resolveNonSpecial( Scene.v().getRefType(testClass), defaultSuperClassMethod.makeRef(), false); SootMethod concreteImpl = Scene.v() .getFastHierarchy() .resolveConcreteDispatch(Scene.v().getSootClass(testClass), defaultMethod); Set<SootMethod> abstractImpl = Scene.v() .getFastHierarchy() .resolveAbstractDispatch(Scene.v().getSootClass(defaultClass), defaultMethod); Set<SootMethod> abstractImplSuperClass = Scene.v() .getFastHierarchy() .resolveAbstractDispatch( Scene.v().getSootClass(defaultSuperClass), defaultSuperClassMethod); boolean edgeMainToSuperClassPrint = checkInEdges(mainMethod, target); boolean edgeMainToDefaultPrint = checkInEdges(defaultMethod, target); boolean edgeMainToSuperDefaultPrint = checkInEdges(defaultSuperClassMethod, target); boolean edgeSuperMainToSuperPrint = checkInEdges(defaultSuperClassMethod, defaultSuperMainMethod); final ReachableMethods reachableMethods = Scene.v().getReachableMethods(); List<SootMethod> targetMethods = new ArrayList<SootMethod>() { { add(mainMethod); add(defaultMethod); add(defaultSuperClassMethod); } }; ArrayList<Boolean> edgeNotPresent = new ArrayList<Boolean>() { { add(edgeMainToDefaultPrint); add(edgeMainToSuperDefaultPrint); add(edgeSuperMainToSuperPrint); } }; Map<SootMethod, SootMethod> resolvedMethods = new HashMap<SootMethod, SootMethod>() { { put(mainMethod, resolvedMethod); put(resolvedSuperClassDefaultMethod, resolvedMethod); } }; for (SootMethod targetMethod : targetMethods) { assertNotNull(targetMethod); } assertEquals(targetMethods.get(0), refMainMethod); assertEquals(targetMethods.get(0).getName(), "print"); assertTrue(edgeMainToSuperClassPrint); for (boolean notPresent : edgeNotPresent) { assertFalse(notPresent); } assertEquals(targetMethods.get(0), concreteImpl); assertNotEquals(targetMethods.get(1), concreteImpl); assertTrue( abstractImpl.contains( Scene.v() .getMethod( "<soot.defaultInterfaceMethods.SuperClassImplementsInterface: void print()>"))); assertTrue( abstractImplSuperClass.contains( Scene.v() .getMethod( "<soot.defaultInterfaceMethods.SuperClassImplementsInterface: void print()>"))); } @Test public void derivedInterfacesTest() { String testClassSig = "soot.defaultInterfaceMethods.DerivedInterfaces"; String defaultInterfaceOneSig = "soot.defaultInterfaceMethods.InterfaceTestOne"; String defaultInterfaceTwoSig = "soot.defaultInterfaceMethods.InterfaceTestTwo"; final SootMethod target = prepareTarget( methodSigFromComponents(testClassSig, voidType, mainClass), testClassSig, defaultInterfaceOneSig, defaultInterfaceTwoSig); FastHierarchy fh = Scene.v().getFastHierarchy(); SootClass testClass = Scene.v().getSootClass(testClassSig); SootClass defaultInterfaceOne = Scene.v().getSootClass(defaultInterfaceOneSig); SootClass defaultInterfaceTwo = Scene.v().getSootClass(defaultInterfaceTwoSig); SootMethod interfaceOnePrint = Scene.v().getMethod(methodSigFromComponents(defaultInterfaceOneSig, "void print()")); SootMethod interfaceTwoPrint = Scene.v().getMethod(methodSigFromComponents(defaultInterfaceTwoSig, "void print()")); SootMethod refMainMethod = resolveMethodRefInBody(target.retrieveActiveBody().getUnits(), "void print()"); SootMethod interfaceOneResolvedMethod = VirtualCalls.v().resolveNonSpecial(testClass.getType(), interfaceOnePrint.makeRef(), false); SootMethod interfaceTwoResolvedMethod = VirtualCalls.v().resolveNonSpecial(testClass.getType(), interfaceTwoPrint.makeRef(), false); SootMethod concreteImplInterfaceOne = fh.resolveConcreteDispatch(testClass, interfaceOnePrint); SootMethod concreteImplInterfaceTwo = fh.resolveConcreteDispatch(testClass, interfaceTwoPrint); Set<SootMethod> abstractImplInterfaceOne = fh.resolveAbstractDispatch(defaultInterfaceOne, interfaceOnePrint); boolean edgeMainToInterfaceTwoPrint = checkInEdges(interfaceTwoPrint, target); boolean edgeMainToInterfaceOnePrint = checkInEdges(interfaceOnePrint, target); final ReachableMethods reachableMethods = Scene.v().getReachableMethods(); List<SootMethod> targetMethods = new ArrayList<SootMethod>() { { add(interfaceOnePrint); add(interfaceTwoPrint); } }; Map<SootMethod, SootMethod> resolvedMethods = new HashMap<SootMethod, SootMethod>() { { put(interfaceTwoPrint, interfaceOneResolvedMethod); put(interfaceTwoPrint, interfaceTwoResolvedMethod); } }; Map<SootMethod, SootMethod> concreteImplTrue = new HashMap<SootMethod, SootMethod>() { { put(interfaceTwoPrint, concreteImplInterfaceOne); put(interfaceTwoPrint, concreteImplInterfaceTwo); } }; Map<SootMethod, SootMethod> concreteImplNotTrue = new HashMap<SootMethod, SootMethod>() { { put(interfaceOnePrint, concreteImplInterfaceOne); put(interfaceOnePrint, concreteImplInterfaceTwo); } }; for (SootMethod targetMethod : targetMethods) { Assert.assertNotNull(targetMethod); } assertEquals(targetMethods.get(1), refMainMethod); assertEquals(targetMethods.get(1).getName(), "print"); assertFalse(edgeMainToInterfaceOnePrint); assertTrue(edgeMainToInterfaceTwoPrint); assertTrue(reachableMethods.contains(targetMethods.get(1))); assertFalse(reachableMethods.contains(targetMethods.get(0))); for (Map.Entry<SootMethod, SootMethod> virtualResolvedMethod : resolvedMethods.entrySet()) { assertEquals(virtualResolvedMethod.getKey(), virtualResolvedMethod.getValue()); } for (Map.Entry<SootMethod, SootMethod> concreteImpl : concreteImplTrue.entrySet()) { assertEquals(concreteImpl.getKey(), concreteImpl.getValue()); } for (Map.Entry<SootMethod, SootMethod> concreteImpl : concreteImplNotTrue.entrySet()) { assertNotEquals(concreteImpl.getKey(), concreteImpl.getValue()); } assertEquals(Sets.newHashSet(targetMethods.get(1)), abstractImplInterfaceOne); assertEquals( Sets.newHashSet(targetMethods.get(1)), fh.resolveAbstractDispatch(defaultInterfaceTwo, interfaceTwoPrint)); } @Test public void interfaceInheritanceTest() { String testClass = "soot.defaultInterfaceMethods.InterfaceInheritance"; String defaultClass = "soot.defaultInterfaceMethods.InterfaceTestA"; String defaultInterface = "soot.defaultInterfaceMethods.InterfaceTestB"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, voidType, mainClass), testClass, defaultClass, defaultInterface); SootMethod interfaceTestAPrint = Scene.v().getMethod("<soot.defaultInterfaceMethods.InterfaceTestA: void print()>"); SootMethod mainPrintMessageMethod = Scene.v() .getMethod("<soot.defaultInterfaceMethods.InterfaceInheritance: void printMessage()>"); Body mainBody = target.retrieveActiveBody(); SootMethod refMainMethod = resolveMethodRefInBody(mainBody.getUnits(), "void print()"); SootMethod resolvedMethod = VirtualCalls.v() .resolveNonSpecial( Scene.v().getRefType(testClass), interfaceTestAPrint.makeRef(), false); SootMethod concreteImpl = Scene.v() .getFastHierarchy() .resolveConcreteDispatch(Scene.v().getSootClass(testClass), interfaceTestAPrint); Set<SootMethod> abstractImpl = Scene.v() .getFastHierarchy() .resolveAbstractDispatch(Scene.v().getSootClass(defaultClass), interfaceTestAPrint); boolean edgeMainToInterfaceTestAPrint = checkInEdges(interfaceTestAPrint, target); boolean edgeMainToMainPrintMessage = checkInEdges(mainPrintMessageMethod, target); final ReachableMethods reachableMethods = Scene.v().getReachableMethods(); List<SootMethod> targetMethods = new ArrayList<SootMethod>() { { add(interfaceTestAPrint); add(mainPrintMessageMethod); } }; for (SootMethod targetMethod : targetMethods) { Assert.assertNotNull(targetMethod); } assertEquals(targetMethods.get(0), refMainMethod); assertEquals(targetMethods.get(0).getName(), "print"); assertTrue(edgeMainToInterfaceTestAPrint); assertFalse(edgeMainToMainPrintMessage); assertTrue(reachableMethods.contains(targetMethods.get(0))); assertFalse(reachableMethods.contains(targetMethods.get(1))); assertEquals(targetMethods.get(0), resolvedMethod); assertEquals(targetMethods.get(0), concreteImpl); assertTrue(abstractImpl.contains(targetMethods.get(0))); } @Test public void interfaceReAbstractionTest() { String testClass = "soot.defaultInterfaceMethods.InterfaceReAbstracting"; String defaultClass = "soot.defaultInterfaceMethods.InterfaceA"; String defaultInterface = "soot.defaultInterfaceMethods.InterfaceB"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, "void", "main"), testClass, defaultClass, defaultInterface); SootMethod interfaceAPrint = Scene.v().getMethod("<soot.defaultInterfaceMethods.InterfaceA: void print()>"); SootMethod mainMethodPrint = Scene.v().getMethod("<soot.defaultInterfaceMethods.InterfaceReAbstracting: void print()>"); Body mainBody = target.retrieveActiveBody(); SootMethod refMainMethod = resolveMethodRefInBody(mainBody.getUnits(), "void print()"); SootMethod resolvedMethod = VirtualCalls.v() .resolveNonSpecial(Scene.v().getRefType(testClass), interfaceAPrint.makeRef(), false); SootMethod concreteImpl = Scene.v() .getFastHierarchy() .resolveConcreteDispatch(Scene.v().getSootClass(testClass), interfaceAPrint); Set<SootMethod> abstractImpl = Scene.v() .getFastHierarchy() .resolveAbstractDispatch(Scene.v().getSootClass(defaultClass), interfaceAPrint); boolean edgeMainMethodToMainPrint = checkInEdges(mainMethodPrint, target); boolean edgeMainMethodToInterfaceAPrint = checkInEdges(interfaceAPrint, target); final ReachableMethods reachableMethods = Scene.v().getReachableMethods(); List<SootMethod> targetMethods = new ArrayList<SootMethod>() { { add(mainMethodPrint); add(interfaceAPrint); } }; for (SootMethod targetMethod : targetMethods) { Assert.assertNotNull(targetMethod); } assertEquals(targetMethods.get(0), refMainMethod); assertEquals(targetMethods.get(0).getName(), "print"); assertTrue(edgeMainMethodToMainPrint); assertFalse(edgeMainMethodToInterfaceAPrint); assertTrue(reachableMethods.contains(targetMethods.get(0))); assertFalse(reachableMethods.contains(targetMethods.get(1))); assertEquals(targetMethods.get(0), resolvedMethod); assertEquals(targetMethods.get(0), concreteImpl); assertNotEquals(targetMethods.get(1), concreteImpl); assertEquals( Sets.newHashSet( Scene.v() .getMethod("<soot.defaultInterfaceMethods.InterfaceReAbstracting: void print()>")), abstractImpl); } @Test public void superClassPreferenceOverDefaultMethodTest() { String testClass = "soot.defaultInterfaceMethods.SuperClassPreferenceOverDefaultMethod"; String defaultInterfaceOne = "soot.defaultInterfaceMethods.InterfaceOne"; String defaultInterfaceTwo = "soot.defaultInterfaceMethods.InterfaceTwo"; String defaultSuperClass = "soot.defaultInterfaceMethods.SuperClass"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, voidType, mainClass), testClass, defaultInterfaceOne, defaultInterfaceTwo, defaultSuperClass); SootMethod interfaceOnePrint = Scene.v().getMethod("<soot.defaultInterfaceMethods.InterfaceOne: void print()>"); SootMethod interfaceTwoPrint = Scene.v().getMethod("<soot.defaultInterfaceMethods.InterfaceTwo: void print()>"); SootMethod superClassPrint = Scene.v().getMethod("<soot.defaultInterfaceMethods.SuperClass: void print()>"); Body mainBody = target.retrieveActiveBody(); SootMethod refMainMethod = resolveMethodRefInBody(mainBody.getUnits(), "void print()"); SootMethod resolvedInterfaceOneDefaultMethod = VirtualCalls.v() .resolveNonSpecial(Scene.v().getRefType(testClass), interfaceOnePrint.makeRef(), false); SootMethod resolvedInterfaceTwoDefaultMethod = VirtualCalls.v() .resolveNonSpecial(Scene.v().getRefType(testClass), interfaceTwoPrint.makeRef(), false); SootMethod concreteImplInterfaceOne = Scene.v() .getFastHierarchy() .resolveConcreteDispatch(Scene.v().getSootClass(testClass), interfaceOnePrint); SootMethod concreteImplInterfaceTwo = Scene.v() .getFastHierarchy() .resolveConcreteDispatch(Scene.v().getSootClass(testClass), interfaceTwoPrint); Set<SootMethod> abstractImplInterfaceOne = Scene.v() .getFastHierarchy() .resolveAbstractDispatch( Scene.v().getSootClass(defaultInterfaceOne), interfaceOnePrint); Set<SootMethod> abstractImplInterfaceTwo = Scene.v() .getFastHierarchy() .resolveAbstractDispatch( Scene.v().getSootClass(defaultInterfaceTwo), interfaceTwoPrint); boolean edgeMainToInterfaceOnePrint = checkInEdges(interfaceOnePrint, target); boolean edgeMainToInterfaceTwoPrint = checkInEdges(interfaceTwoPrint, target); boolean edgeMainToSuperClassPrint = checkInEdges(superClassPrint, target); final ReachableMethods reachableMethods = Scene.v().getReachableMethods(); List<SootMethod> targetMethods = new ArrayList<SootMethod>() { { add(superClassPrint); add(interfaceOnePrint); add(interfaceTwoPrint); } }; ArrayList<Boolean> edgeNotPresent = new ArrayList<Boolean>() { { add(edgeMainToInterfaceOnePrint); add(edgeMainToInterfaceTwoPrint); } }; Map<SootMethod, SootMethod> resolvedMethods = new HashMap<SootMethod, SootMethod>() { { put(superClassPrint, resolvedInterfaceOneDefaultMethod); put(superClassPrint, resolvedInterfaceTwoDefaultMethod); } }; Map<SootMethod, SootMethod> concreteImplTrue = new HashMap<SootMethod, SootMethod>() { { put(superClassPrint, concreteImplInterfaceOne); put(superClassPrint, concreteImplInterfaceTwo); } }; Map<SootMethod, SootMethod> concreteImplNotTrue = new HashMap<SootMethod, SootMethod>() { { put(interfaceOnePrint, concreteImplInterfaceOne); put(interfaceOnePrint, concreteImplInterfaceTwo); } }; for (SootMethod targetMethod : targetMethods) { assertNotNull(targetMethod); } assertEquals(targetMethods.get(0), refMainMethod); assertEquals(targetMethods.get(0).getName(), "print"); assertTrue(edgeMainToSuperClassPrint); for (boolean notPresent : edgeNotPresent) { assertFalse(notPresent); } assertTrue(reachableMethods.contains(targetMethods.get(0))); assertFalse(reachableMethods.contains(targetMethods.get(1))); assertFalse(reachableMethods.contains(targetMethods.get(2))); for (Map.Entry<SootMethod, SootMethod> virtualResolvedMethod : resolvedMethods.entrySet()) { assertEquals(virtualResolvedMethod.getKey(), virtualResolvedMethod.getValue()); } for (Map.Entry<SootMethod, SootMethod> concreteImpl : concreteImplTrue.entrySet()) { assertEquals(concreteImpl.getKey(), concreteImpl.getValue()); } for (Map.Entry<SootMethod, SootMethod> concreteImpl : concreteImplNotTrue.entrySet()) { assertNotEquals(concreteImpl.getKey(), concreteImpl.getValue()); } assertTrue( abstractImplInterfaceOne.contains( Scene.v().getMethod("<soot.defaultInterfaceMethods.SuperClass: void print()>"))); assertTrue( abstractImplInterfaceTwo.contains( Scene.v().getMethod("<soot.defaultInterfaceMethods.SuperClass: void print()>"))); } private boolean checkInEdges(SootMethod defaultMethod, SootMethod targetMethod) { boolean isPresent = false; Iterator<Edge> inEdges = Scene.v().getCallGraph().edgesInto(defaultMethod); while (inEdges.hasNext()) { MethodOrMethodContext sourceMethod = inEdges.next().getSrc(); if (sourceMethod.equals(targetMethod)) { isPresent = true; } } return isPresent; } /** * Searches the given unit chain for the first call to a method with the given subsignature and * resolves it's MethodRef * * @param units * @param methodSubSig * @return */ private SootMethod resolveMethodRefInBody(UnitPatchingChain units, String methodSubSig) { SootMethod method = null; for (Unit unit : units) { Stmt s = (Stmt) unit; if (s.containsInvokeExpr() && s.getInvokeExpr().getMethodRef().getSignature().contains(methodSubSig)) { return s.getInvokeExpr().getMethodRef().tryResolve(); } } return null; } @Test public void maximallySpecificSuperInterface() { String targetClassName = "soot.defaultInterfaceMethods.MaximallySpecificSuperInterface"; String superClass = "soot.defaultInterfaceMethods.B"; String subInterface = "soot.defaultInterfaceMethods.C"; String superInterface = "soot.defaultInterfaceMethods.D"; final SootMethod mainMethod = prepareTarget( methodSigFromComponents(targetClassName, voidType, mainClass), targetClassName, superClass, subInterface, superInterface); SootClass testClass = mainMethod.getDeclaringClass(); SootMethod subInterfacePrint = Scene.v().getMethod(methodSigFromComponents(subInterface, "void print()")); SootMethod superInterfacePrint = Scene.v().getMethod(methodSigFromComponents(superInterface, "void print()")); SootMethod methodRefResolved = resolveMethodRefInBody(mainMethod.retrieveActiveBody().getUnits(), "void print()"); assertEquals(subInterfacePrint, methodRefResolved); SootMethod virtualCallsResolved = VirtualCalls.v() .resolveNonSpecial(testClass.getType(), superInterfacePrint.makeRef(), false); assertEquals(subInterfacePrint, virtualCallsResolved); SootMethod concreteImplI1 = Scene.v().getFastHierarchy().resolveConcreteDispatch(testClass, superInterfacePrint); assertEquals(subInterfacePrint, concreteImplI1); Set<SootMethod> abstractImpl = Scene.v() .getFastHierarchy() .resolveAbstractDispatch(superInterfacePrint.getDeclaringClass(), superInterfacePrint); assertEquals(Sets.newHashSet(subInterfacePrint), abstractImpl); assertTrue(checkInEdges(subInterfacePrint, mainMethod)); assertTrue(Scene.v().getReachableMethods().contains(subInterfacePrint)); } private static ArrayList<Edge> GetCallGraph() { CallGraph cg = Scene.v().getCallGraph(); Iterator<Edge> mainMethodEdges = cg.edgesOutOf(Scene.v().getMethod("<soot.defaultInterfaceMethods.JavaNCSSCheck: void finishTree()>")); ArrayList<Edge> edgeList = Lists.newArrayList(mainMethodEdges); return edgeList; } }
37,962
39.172487
163
java
soot
soot-master/src/systemTest/java/soot/dexpler/instructions/DexByteCodeInstrutionsTest.java
package soot.dexpler.instructions; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Test; import soot.ModulePathSourceLocator; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.SootMethodRef; import soot.UnitPatchingChain; import soot.jimple.DynamicInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import soot.jimple.VirtualInvokeExpr; import soot.options.Options; import soot.testing.framework.AbstractTestingFramework; /** * @author Manuel Benz created on 22.10.18 */ public class DexByteCodeInstrutionsTest extends AbstractTestingFramework { private static final String METHOD_HANDLE_CLASS = "java.lang.invoke.MethodHandle"; private static final String TARGET_CLASS = "soot.dexpler.instructions.DexBytecodeTarget"; private static final String METHOD_HANDLE_INVOKE_SUBSIG = "java.lang.Object invoke(java.lang.Object[])"; private static final String SUPPLIER_GET_SUBSIG = "java.util.function.Supplier get()"; @Override protected void setupSoot() { super.setupSoot(); Options.v().set_src_prec(Options.src_prec_apk); // to get the basic classes; java.lang.Object, java.lang.Throwable, ... we add the rt.jar to the classpath String rtJar = ""; if (Scene.isJavaGEQ9(System.getProperty("java.version"))) { rtJar = ModulePathSourceLocator.DUMMY_CLASSPATH_JDK9_FS; } else { rtJar = System.getProperty("java.home") + File.separator + "lib" + File.separator + "rt.jar"; } Options.v().set_process_dir(Arrays.asList(targetDexPath(), rtJar)); Options.v().set_force_android_jar(androidJarPath()); Options.v().set_android_api_version(26); } @Override protected void runSoot() { // we do not want to have a call graph for this test } private String androidJarPath() { // this is not the nicest thing. Make sure to keep the version in sync with the pom // also .m2 repository could fail return System.getProperty("user.home") + "/.m2/repository/" + "com/google/android/android/4.1.1.4/android-4.1.1.4.jar"; } private String targetDexPath() { final URL targetDex = getClass().getResource("dexBytecodeTarget.dex"); try { return targetDex.toURI().getPath(); } catch (URISyntaxException e) { throw new RuntimeException("Exception loading test resources", e); } } @Test public void InvokePolymorphic1() { final SootMethod testTarget = prepareTarget( methodSigFromComponents(TARGET_CLASS, "void invokePolymorphicTarget(java.lang.invoke.MethodHandle)"), TARGET_CLASS); // We model invokePolymorphic as invokeVirtual final List<InvokeExpr> invokes = invokesFromMethod(testTarget); Assert.assertEquals(1, invokes.size()); final InvokeExpr invokePoly = invokes.get(0); Assert.assertTrue(invokePoly instanceof VirtualInvokeExpr); final SootMethodRef targetMethodRef = invokePoly.getMethodRef(); Assert.assertEquals(methodSigFromComponents(METHOD_HANDLE_CLASS, METHOD_HANDLE_INVOKE_SUBSIG), targetMethodRef.getSignature()); } @Test public void InvokeCustom1() { final SootMethod testTarget = prepareTarget(methodSigFromComponents(TARGET_CLASS, "void invokeCustomTarget()"), TARGET_CLASS); // We model invokeCustom as invokeDynamic final List<InvokeExpr> invokes = invokesFromMethod(testTarget); Assert.assertEquals(1, invokes.size()); final InvokeExpr invokeCustom = invokes.get(0); Assert.assertTrue(invokeCustom instanceof DynamicInvokeExpr); final SootMethodRef targetMethodRef = invokeCustom.getMethodRef(); Assert.assertEquals(methodSigFromComponents(SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME, SUPPLIER_GET_SUBSIG), targetMethodRef.getSignature()); final String callToLambdaMethaFactory = "dynamicinvoke \"get\" <java.util.function.Supplier ()>() <java.lang.invoke.LambdaMetafactory: java.lang.invoke.CallSite metafactory(java.lang.invoke.MethodHandles$Lookup,java.lang.String,java.lang.invoke.MethodType,java.lang.invoke.MethodType,java.lang.invoke.MethodHandle,java.lang.invoke.MethodType)>(methodtype: java.lang.Object __METHODTYPE__(), methodhandle: \"REF_INVOKE_STATIC\" <soot.dexpler.instructions.DexBytecodeTarget: java.lang.String lambda$invokeCustomTarget$0()>, methodtype: java.lang.String __METHODTYPE__())"; Assert.assertEquals(callToLambdaMethaFactory, invokeCustom.toString()); } private List<InvokeExpr> invokesFromMethod(SootMethod testTarget) { final UnitPatchingChain units = testTarget.retrieveActiveBody().getUnits(); return units.stream().filter(u -> ((Stmt) u).containsInvokeExpr()).map(u -> ((Stmt) u).getInvokeExpr()) .collect(Collectors.toList()); } }
5,638
40.160584
540
java
soot
soot-master/src/systemTest/java/soot/jimple/PolymorphicDispatchTest.java
package soot.jimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Assert; import org.junit.Test; import soot.Body; import soot.PackManager; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.options.Options; import soot.testing.framework.AbstractTestingFramework; /** * @author Andreas Dann created on 06.02.19 * @author Manuel Benz 27.2.19 */ public class PolymorphicDispatchTest extends AbstractTestingFramework { private static final String TEST_TARGET_CLASS = "soot.jimple.PolymorphicDispatch"; @Override protected void setupSoot() { Options.v().set_allow_phantom_refs(true); Options.v().set_no_bodies_for_excluded(false); Options.v().set_prepend_classpath(true); // if we use validate globally, every test will fail due to validation of target methods of other tests. Even if the test // would actually pass... Options.v().set_validate(false); } @Override protected void runSoot() { PackManager.v().runBodyPacks(); } @Test public void findsTarget() { String methodSignature = methodSigFromComponents(TEST_TARGET_CLASS, "void", "unambiguousMethod", ""); final SootMethod sootMethod = prepareTarget(methodSignature, TEST_TARGET_CLASS); Assert.assertTrue(sootMethod.isConcrete()); Body body = sootMethod.retrieveActiveBody(); Assert.assertNotNull(body); // validate individual method body.validate(); for (Unit u : body.getUnits()) { if (u instanceof AssignStmt) { Value right = ((AssignStmt) u).getRightOp(); if (right instanceof InvokeExpr) { SootMethod m = ((InvokeExpr) right).getMethodRef().resolve(); Assert.assertFalse(m.isPhantom()); Assert.assertTrue(m.isDeclared()); if (m.getName().equals("invoke")) { Assert.assertTrue(m.isNative()); } } } } } @Test public void handlesAmbiguousMethod() { String methodSignature = methodSigFromComponents(TEST_TARGET_CLASS, "void", "ambiguousMethod", ""); final SootMethod sootMethod = prepareTarget(methodSignature, TEST_TARGET_CLASS); Assert.assertTrue(sootMethod.isConcrete()); Body body = sootMethod.retrieveActiveBody(); Assert.assertNotNull(body); // validate individual method body.validate(); for (Unit u : body.getUnits()) { if (u instanceof AssignStmt) { Value right = ((AssignStmt) u).getRightOp(); if (right instanceof InvokeExpr) { SootMethod m = ((InvokeExpr) right).getMethodRef().resolve(); Assert.assertFalse(m.isPhantom()); Assert.assertTrue(m.isDeclared()); if (m.getName().equals("invoke")) { Assert.assertTrue(m.isNative()); } } } } } }
3,532
30.265487
125
java
soot
soot-master/src/systemTest/java/soot/jimple/PropagateLineNumberTagTest.java
package soot.jimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2020 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Optional; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Body; import soot.SootMethod; import soot.Unit; import soot.ValueBox; import soot.jimple.internal.ImmediateBox; import soot.options.Options; import soot.tagkit.LineNumberTag; import soot.testing.framework.AbstractTestingFramework; /** @author Manuel Benz at 20.01.20 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class PropagateLineNumberTagTest extends AbstractTestingFramework { private static final String TEST_TARGET_CLASS = "soot.jimple.PropagateLineNumberTag"; @Override protected void setupSoot() { Options.v().setPhaseOption("jb", "use-original-names:true"); Options.v().setPhaseOption("jb.tr", "ignore-nullpointer-dereferences:true"); Options.v().set_keep_line_number(true); Options.v().setPhaseOption("cg.cha", "on"); } @Test public void nullAssignment() { SootMethod target = prepareTarget( methodSigFromComponents(TEST_TARGET_CLASS, "void", "nullAssignment"), TEST_TARGET_CLASS); Body body = target.retrieveActiveBody(); Optional<Unit> unit = body.getUnits().stream() .filter( u -> u.toString() .equals( "staticinvoke <soot.jimple.PropagateLineNumberTag: soot.jimple.PropagateLineNumberTag$A foo(soot.jimple.PropagateLineNumberTag$A)>(null)")) .findFirst(); assertTrue(unit.isPresent()); List<ValueBox> useBoxes = unit.get().getUseBoxes(); assertEquals(2, useBoxes.size()); ValueBox valueBox = useBoxes.get(0); assertTrue(valueBox instanceof ImmediateBox); assertEquals(1, valueBox.getTags().size()); assertTrue(valueBox.getTags().get(0) instanceof LineNumberTag); assertEquals(33, valueBox.getJavaSourceStartLineNumber()); } @Test public void transitiveNullAssignment() { SootMethod target = prepareTarget( methodSigFromComponents(TEST_TARGET_CLASS, "void", "transitiveNullAssignment"), TEST_TARGET_CLASS); Body body = target.retrieveActiveBody(); // first call to foo Optional<Unit> unit = body.getUnits().stream() .filter( u -> u.toString() .equals( "staticinvoke <soot.jimple.PropagateLineNumberTag: soot.jimple.PropagateLineNumberTag$A foo(soot.jimple.PropagateLineNumberTag$A)>(null)")) .findFirst(); assertTrue(unit.isPresent()); List<ValueBox> useBoxes = unit.get().getUseBoxes(); assertEquals(2, useBoxes.size()); ValueBox valueBox = useBoxes.get(0); assertTrue(valueBox instanceof ImmediateBox); assertEquals(1, valueBox.getTags().size()); assertTrue(valueBox.getTags().get(0) instanceof LineNumberTag); assertEquals(39, valueBox.getJavaSourceStartLineNumber()); // second call to foo unit = body.getUnits().stream() .filter( u -> u.toString() .equals( "staticinvoke <soot.jimple.PropagateLineNumberTag: soot.jimple.PropagateLineNumberTag$A foo(soot.jimple.PropagateLineNumberTag$A)>(null)")) .skip(1) .findFirst(); assertTrue(unit.isPresent()); useBoxes = unit.get().getUseBoxes(); assertEquals(2, useBoxes.size()); valueBox = useBoxes.get(0); assertTrue(valueBox instanceof ImmediateBox); assertEquals(1, valueBox.getTags().size()); assertTrue(valueBox.getTags().get(0) instanceof LineNumberTag); assertEquals(39, valueBox.getJavaSourceStartLineNumber()); } }
4,721
33.217391
167
java
soot
soot-master/src/systemTest/java/soot/jimple/toolkit/callgraph/AndroidCallGraphVirtualEdgesTest.java
package soot.jimple.toolkit.callgraph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2021 Qidan He * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Scene; import soot.jimple.toolkits.callgraph.Edge; import soot.testing.framework.AbstractTestingFramework; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class AndroidCallGraphVirtualEdgesTest extends AbstractTestingFramework { private static final String TARGET_CLASS = "soot.jimple.toolkit.callgraph.AsyncTaskTestMainSample"; private static final String TARGET_METHOD = "void target1()"; private static final int DO_IN_BG = 0x1; private static final int ON_PRE_EXE = DO_IN_BG << 1; private static final int ON_PRO_UPD = DO_IN_BG << 2; private static final int ON_POS_EXE = DO_IN_BG << 4; private static final Map<String, Integer> asyncFuncMaps = new HashMap<>(); @Test public void TestAsyncTaskBasicCG() { prepareTarget(methodSigFromComponents(TARGET_CLASS, TARGET_METHOD), TARGET_CLASS); asyncFuncMaps.clear(); asyncFuncMaps.put("doInBackground", DO_IN_BG); asyncFuncMaps.put("onPreExecute", ON_PRE_EXE); asyncFuncMaps.put("onPostExecute", ON_POS_EXE); asyncFuncMaps.put("onProgressUpdate", ON_PRO_UPD); int full = 0, ret = 0; for(String key: asyncFuncMaps.keySet()) { full |= asyncFuncMaps.get(key); } for (Edge edge : Scene.v().getCallGraph()) { String sig = edge.getTgt().method().toString(); for (String key : asyncFuncMaps.keySet()) { if (sig.contains(key)) ret |= asyncFuncMaps.get(key); } } //The four functions shall all appear in call graph Assert.assertEquals(ret, full); } }
2,721
34.350649
103
java
soot
soot-master/src/systemTest/java/soot/jimple/toolkit/callgraph/MultiCallGraphVirtualEdgesTest.java
package soot.jimple.toolkit.callgraph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2021 Qidan He * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Scene; import soot.jimple.toolkits.callgraph.Edge; import soot.testing.framework.AbstractTestingFramework; @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class MultiCallGraphVirtualEdgesTest extends AbstractTestingFramework { private static final String TARGET_CLASS = "soot.jimple.toolkit.callgraph.ContainerMultiTypeSample"; private static final String TARGET_METHOD = "void target()"; @Test public void TestAsyncTaskBasicCG() { prepareTarget(methodSigFromComponents(TARGET_CLASS, TARGET_METHOD), TARGET_CLASS); boolean found = false; for (Edge edge : Scene.v().getCallGraph()) { //String sig = edge.getTgt().method().toString(); System.out.println(edge); String sig = edge.getTgt().method().toString(); if (edge.toString().contains("AHelper") && edge.toString().contains("handle")) found = true; } //Assert.assertTrue(found); } }
1,974
34.909091
104
java
soot
soot-master/src/systemTest/java/soot/jimple/toolkit/callgraph/TypeBasedReflectionModelAnySubTypeTest.java
package soot.jimple.toolkit.callgraph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 John Toman * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of 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 org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsNot.not; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Kind; import soot.RefType; import soot.Scene; import soot.SootMethod; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import soot.jimple.spark.internal.CompleteAccessibility; import soot.options.Options; import soot.testing.framework.AbstractTestingFramework; @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class TypeBasedReflectionModelAnySubTypeTest extends AbstractTestingFramework { private static final String[] INTERFACE_INVOKEES = new String[] { "<soot.jimple.toolkit.callgraph.SubImplementation: void invokeTarget(java.lang.String)>", "<soot.jimple.toolkit.callgraph.SubClass: void invokeTarget2(java.lang.String)>" }; private static final String[] INTERFACE_EXCLUDED_TARGETS = new String[] { "<soot.jimple.toolkit.callgraph.SubImplementation: void doNotCall(soot.jimple.toolkit.callgraph.Interface)>", "<soot.jimple.toolkit.callgraph.SubClass: void doNotCall2(soot.jimple.toolkit.callgraph.Interface)>" }; private static final String[] CLASS_INVOKEES = new String[] { "<soot.jimple.toolkit.callgraph.B: void invokeTarget(java.lang.String)>", "<soot.jimple.toolkit.callgraph.C: void invokeTarget2(java.lang.String)>" }; private static final String TEST_PACKAGE = "soot.jimple.toolkit.callgraph.*"; private static final String TEST_PTA_ENTRY_POINT = "<soot.jimple.toolkit.callgraph.EntryPoint: void ptaResolution()>"; private static final String TEST_TYPESTATE_ENTRY_POINT = "<soot.jimple.toolkit.callgraph.EntryPoint: void typestateResolution()>"; @Test public void anySubTypePointsToResolution() { SootMethod entryPoint = prepareTarget(TEST_PTA_ENTRY_POINT, TEST_PACKAGE); commonInvokeTest(entryPoint); } @Test public void anySubTypeTypestateResolution() { SootMethod entryPoint = prepareTarget(TEST_TYPESTATE_ENTRY_POINT, TEST_PACKAGE); commonInvokeTest(entryPoint); } private void commonInvokeTest(SootMethod entryPoint) { Set<String> interfaceInvokeCallees = new HashSet<>(); Set<String> classInvokeCallees = new HashSet<>(); Scene.v().getCallGraph().edgesOutOf(entryPoint).forEachRemaining(edge -> { if(edge.kind() != Kind.REFL_INVOKE) { return; } Stmt src = edge.srcStmt(); Assert.assertTrue(src.containsInvokeExpr()); InvokeExpr ie = src.getInvokeExpr(); Assert.assertEquals("Wrong signature", "<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>", ie.getMethodRef().getSignature()); Assert.assertTrue(ie.getArgCount() > 0); Assert.assertThat(ie.getArg(0).getType(), instanceOf(RefType.class)); RefType t = (RefType) ie.getArg(0).getType(); if(t.getClassName().equals("soot.jimple.toolkit.callgraph.Interface")) { interfaceInvokeCallees.add(edge.getTgt().method().getSignature()); } else if(t.getClassName().equals("soot.jimple.toolkit.callgraph.A")) { classInvokeCallees.add(edge.getTgt().method().getSignature()); } else { Assert.fail("Unrecognized base type " + t); } }); Assert.assertFalse(interfaceInvokeCallees.isEmpty()); Assert.assertFalse(classInvokeCallees.isEmpty()); Assert.assertThat(interfaceInvokeCallees, hasItems(INTERFACE_INVOKEES)); Assert.assertThat(interfaceInvokeCallees, not(hasItems(INTERFACE_EXCLUDED_TARGETS))); Assert.assertThat(classInvokeCallees, hasItems(CLASS_INVOKEES)); Assert.assertEquals(2, classInvokeCallees.size()); } @Override protected void setupSoot() { super.setupSoot(); Options.v().setPhaseOption("cg", "types-for-invoke:true"); Options.v().setPhaseOption("cg", "library:any-subtype"); Scene.v().addBasicClass("soot.jimple.toolkit.callgraph.EntryPoint"); Scene.v().addBasicClass("soot.jimple.toolkit.callgraph.C"); Scene.v().setClientAccessibilityOracle(CompleteAccessibility.v()); } }
5,123
41
137
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/AbstractLambdaMetaFactoryCGTest.java
package soot.lambdaMetaFactory; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static com.google.common.collect.Lists.newArrayList; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Ignore; import org.junit.Test; import soot.Kind; import soot.Scene; import soot.SootMethod; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.testing.framework.AbstractTestingFramework; /** * @author Manuel Benz created on 2018-12-17 */ @Ignore public abstract class AbstractLambdaMetaFactoryCGTest extends AbstractTestingFramework { private static final String TEST_METHOD_NAME = "main"; private static final String TEST_METHOD_RET = "void"; @Override protected void setupSoot() { } @Test public void lambdaNoCaptures() { String testClass = "soot.lambdaMetaFactory.LambdaNoCaptures"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass, "java.util.function.Function"); final CallGraph cg = Scene.v().getCallGraph(); final String metaFactoryClass = getMetaFactoryNameLambda(testClass, TEST_METHOD_NAME); final SootMethod bootstrap = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.Function", "bootstrap$")); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>")); final SootMethod apply = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.lang.Object", "apply", "java.lang.Object")); final SootMethod lambdaBody = Scene.v().getMethod(methodSigFromComponents(testClass, "java.lang.String", "lambda$main$0", "java.lang.Integer")); final SootMethod staticCallee = Scene.v().getMethod(methodSigFromComponents(testClass, "void", "staticCallee", "java.lang.Integer")); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue( "There should be an instance invocation on the synthetic LambdaMetaFactory's implementation of the functional interface in the main method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(apply) && e.kind() == Kind.INTERFACE)); assertTrue( "There should be a static call to the lambda body implementation in the generated functional interface implementation of the synthetic LambdaMetaFactory", newArrayList(cg.edgesOutOf(apply)).stream().anyMatch(e -> e.getTgt().equals(lambdaBody) && e.isStatic())); assertTrue("There should be a static call to the staticCallee method in actual lambda body implementation", newArrayList(cg.edgesOutOf(lambdaBody)).stream().anyMatch(e -> e.getTgt().equals(staticCallee) && e.isStatic())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } @Test public void lambdaWithCaptures() { String testClass = "soot.lambdaMetaFactory.LambdaWithCaptures"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass); final CallGraph cg = Scene.v().getCallGraph(); final String metaFactoryClass = getMetaFactoryNameLambda(testClass, TEST_METHOD_NAME); final SootMethod bootstrap = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.Supplier", "bootstrap$", testClass, "java.lang.String")); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>", testClass, "java.lang.String")); final SootMethod get = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.lang.Object", "get")); final SootMethod lambdaBody = Scene.v().getMethod(methodSigFromComponents(testClass, "java.lang.String", "lambda$main$0", "java.lang.String")); final SootMethod getString = Scene.v().getMethod(methodSigFromComponents(testClass, "java.lang.String", "getString")); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue( "There should be an interface invocation on the synthetic LambdaMetaFactory's implementation of the functional interface in the main method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(get) && e.kind() == Kind.INTERFACE)); assertTrue( "There should be a virtual call to the lambda body implementation in the generated functional interface implementation of the synthetic LambdaMetaFactory", newArrayList(cg.edgesOutOf(get)).stream().anyMatch(e -> e.getTgt().equals(lambdaBody) && e.isVirtual())); assertTrue("There should be a special call to the getString method in actual lambda body implementation", newArrayList(cg.edgesOutOf(lambdaBody)).stream().anyMatch(e -> e.getTgt().equals(getString) && e.isSpecial())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } @Test public void markerInterfaces() { String testClass = "soot.lambdaMetaFactory.MarkerInterfaces"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass); final CallGraph cg = Scene.v().getCallGraph(); final String metaFactoryClass = getMetaFactoryNameLambda(testClass, TEST_METHOD_NAME); final SootMethod bootstrap = Scene.v() .getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.Supplier", "bootstrap$", testClass)); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>", testClass)); final SootMethod get = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.lang.Object", "get")); final SootMethod lambdaBody = Scene.v().getMethod(methodSigFromComponents(testClass, "java.lang.Object", "lambda$main$0")); final SootMethod getString = Scene.v().getMethod(methodSigFromComponents(testClass, "java.lang.String", "getString")); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue( "There should be an interface invocation on the synthetic LambdaMetaFactory's implementation of the functional interface in the main method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(get) && e.kind() == Kind.INTERFACE)); assertTrue( "There should be a virtual call to the lambda body implementation in the generated functional interface implementation of the synthetic LambdaMetaFactory", newArrayList(cg.edgesOutOf(get)).stream().anyMatch(e -> e.getTgt().equals(lambdaBody) && e.isVirtual())); assertTrue("There should be a virtual call to the getString method in actual lambda body implementation", newArrayList(cg.edgesOutOf(lambdaBody)).stream().anyMatch(e -> e.getTgt().equals(getString) && e.isVirtual())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } @Test public void staticMethodRef() { String testClass = "soot.lambdaMetaFactory.StaticMethodRef"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass); final CallGraph cg = Scene.v().getCallGraph(); final String referencedMethodName = "staticMethod"; final String metaFactoryClass = getMetaFactoryNameMethodRef(testClass, referencedMethodName); final SootMethod bootstrap = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.Supplier", "bootstrap$")); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>")); final SootMethod get = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.lang.Object", "get")); final SootMethod referencedMethod = Scene.v().getMethod(methodSigFromComponents(testClass, "int", referencedMethodName)); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue( "There should be an interface invocation on the synthetic LambdaMetaFactory's implementation of the functional interface in the main method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(get) && e.kind() == Kind.INTERFACE)); assertTrue("There should be a static call to the referenced method", newArrayList(cg.edgesOutOf(get)).stream().anyMatch(e -> e.getTgt().equals(referencedMethod) && e.isStatic())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } @Test public void privateMethodRef() { String testClass = "soot.lambdaMetaFactory.PrivateMethodRef"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass); final CallGraph cg = Scene.v().getCallGraph(); final String referencedMethodName = "privateMethod"; final String metaFactoryClass = getMetaFactoryNameMethodRef(testClass, referencedMethodName); final SootMethod bootstrap = Scene.v() .getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.Supplier", "bootstrap$", testClass)); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>", testClass)); final SootMethod get = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.lang.Object", "get")); final SootMethod referencedMethod = Scene.v().getMethod(methodSigFromComponents(testClass, "int", referencedMethodName)); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue( "There should be an interface invocation on the synthetic LambdaMetaFactory's implementation of the functional interface in the main method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(get) && e.kind() == Kind.INTERFACE)); assertTrue("There should be a virtual call to the referenced method", newArrayList(cg.edgesOutOf(get)).stream().anyMatch(e -> e.getTgt().equals(referencedMethod) && e.isVirtual())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } @Test public void publicMethodRef() { String testClass = "soot.lambdaMetaFactory.PublicMethodRef"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass); final CallGraph cg = Scene.v().getCallGraph(); final String referencedMethodName = "publicMethod"; final String metaFactoryClass = getMetaFactoryNameMethodRef(testClass, referencedMethodName); final SootMethod bootstrap = Scene.v() .getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.Supplier", "bootstrap$", testClass)); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>", testClass)); final SootMethod get = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.lang.Object", "get")); final SootMethod referencedMethod = Scene.v().getMethod(methodSigFromComponents(testClass, "int", referencedMethodName)); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue( "There should be an interface invocation on the synthetic LambdaMetaFactory's implementation of the functional interface in the main method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(get) && e.kind() == Kind.INTERFACE)); assertTrue("There should be a virtual call to the referenced method", newArrayList(cg.edgesOutOf(get)).stream().anyMatch(e -> e.getTgt().equals(referencedMethod) && e.isVirtual())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } @Test public void constructorMethodRef() { String testClass = "soot.lambdaMetaFactory.ConstructorMethodRef"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass); final CallGraph cg = Scene.v().getCallGraph(); final String referencedMethodName = "<init>"; final String metaFactoryClass = getMetaFactoryNameMethodRef(testClass, referencedMethodName); final SootMethod bootstrap = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.Supplier", "bootstrap$")); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>")); final SootMethod get = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.lang.Object", "get")); final SootMethod referencedMethod = Scene.v().getMethod(methodSigFromComponents(testClass, "void", referencedMethodName)); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue( "There should be an interface invocation on the synthetic LambdaMetaFactory's implementation of the functional interface in the main method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(get) && e.kind() == Kind.INTERFACE)); assertTrue("There should be a special call to the referenced method", newArrayList(cg.edgesOutOf(get)).stream().anyMatch(e -> e.getTgt().equals(referencedMethod) && e.isSpecial())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } @Test public void inheritedMethodRef() { String testClass = "soot.lambdaMetaFactory.InheritedMethodRef"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass); final CallGraph cg = Scene.v().getCallGraph(); final String referencedMethodName = "superMethod"; final String metaFactoryClass = getMetaFactoryNameLambda(testClass, TEST_METHOD_NAME); final SootMethod bootstrap = Scene.v() .getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.Supplier", "bootstrap$", testClass)); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>", testClass)); final SootMethod get = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.lang.Object", "get")); final SootMethod referencedMethod = Scene.v().getMethod(methodSigFromComponents("soot.lambdaMetaFactory.Super", "int", referencedMethodName)); final SootMethod lambdaBody = Scene.v().getMethod(methodSigFromComponents(testClass, "java.lang.Integer", "lambda$main$0")); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue( "There should be an interface invocation on the synthetic LambdaMetaFactory's implementation of the functional interface in the main method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(get) && e.kind() == Kind.INTERFACE)); //Call is from <soot.lambdaMetaFactory.InheritedMethodRef$lambda_main_0__1 //to <soot.lambdaMetaFactory.InheritedMethodRef: java.lang.Integer lambda$main$0()> //As such, it needs to be a virtual call. assertTrue( "There should be a virtual call to the lambda body implementation in the generated functional interface implementation of the synthetic LambdaMetaFactory", newArrayList(cg.edgesOutOf(get)).stream().anyMatch(e -> e.getTgt().equals(lambdaBody) && e.isVirtual())); assertTrue("There should be a special call to the referenced method", newArrayList(cg.edgesOutOf(lambdaBody)).stream() .anyMatch(e -> e.getTgt().equals(referencedMethod) && e.isSpecial())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } @Test public void methodRefWithParameters() { String testClass = "soot.lambdaMetaFactory.MethodRefWithParameters"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, TEST_METHOD_RET, TEST_METHOD_NAME), testClass); final CallGraph cg = Scene.v().getCallGraph(); final String referencedMethodName = "staticWithCaptures"; final String metaFactoryClass = getMetaFactoryNameMethodRef(testClass, referencedMethodName); final SootMethod bootstrap = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "java.util.function.BiFunction", "bootstrap$")); final SootMethod metaFactoryConstructor = Scene.v().getMethod(methodSigFromComponents(metaFactoryClass, "void", "<init>")); final SootMethod apply = Scene.v().getMethod( methodSigFromComponents(metaFactoryClass, "java.lang.Object", "apply", "java.lang.Object", "java.lang.Object")); final SootMethod referencedMethod = Scene.v().getMethod(methodSigFromComponents(testClass, "int", referencedMethodName, "int", "java.lang.Integer")); final List<Edge> edgesFromTarget = newArrayList(cg.edgesOutOf(target)); assertTrue("There should be an edge from main to the bootstrap method of the synthetic LambdaMetaFactory", edgesFromTarget.stream().anyMatch(e -> e.tgt().equals(bootstrap) && e.isStatic())); assertTrue("There should be an edge to the constructor of the LambdaMetaFactory in the bootstrap method", newArrayList(cg.edgesOutOf(bootstrap)).stream() .anyMatch(e -> e.tgt().equals(metaFactoryConstructor) && e.isSpecial())); assertTrue("There should be an interface invocation on the referenced method", edgesFromTarget.stream().anyMatch(e -> e.getTgt().equals(apply) && e.kind() == Kind.INTERFACE)); assertTrue("There should be a static call to the referenced method", newArrayList(cg.edgesOutOf(apply)).stream().anyMatch(e -> e.getTgt().equals(referencedMethod) && e.isStatic())); validateAllBodies(target.getDeclaringClass(), bootstrap.getDeclaringClass()); } private String getMetaFactoryNameMethodRef(String testClass, String referencedMethod) { return testClass + "$" + referencedMethod.replace("<", "").replace(">", "") + "__1"; } private String getMetaFactoryNameLambda(String testClass, String testMethodName) { return testClass + "$lambda_" + testMethodName + "_0__1"; } }
22,694
53.951574
163
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/Issue1146Test.java
package soot.lambdaMetaFactory; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2019 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.SootMethod; import soot.testing.framework.AbstractTestingFramework; /** * Reproduces issue 1146: https://github.com/soot-oss/soot/issues/1146 * * @author Manuel Benz at 2019-05-14 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class Issue1146Test extends AbstractTestingFramework { @Test public void getVertragTest() { String testClass = "soot.lambdaMetaFactory.Issue1146"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, "soot.lambdaMetaFactory.Issue1146$Vertrag", "getVertrag", "java.lang.String"), testClass, "java.util.function.Function"); // if no exception is thrown, everything is working as intended } @Test public void getVertrag2Test() { String testClass = "soot.lambdaMetaFactory.Issue1146"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, "soot.lambdaMetaFactory.Issue1146$Vertrag", "getVertrag2", "java.lang.String"), testClass, "java.util.function.Function"); // if no exception is thrown, everything is working as intended } }
2,061
33.949153
122
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/Issue1292Test.java
package soot.lambdaMetaFactory; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2019 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.testing.framework.AbstractTestingFramework; /** * Reproduces issue 1292: https://github.com/soot-oss/soot/issues/1292 * * @author raintung.li */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class Issue1292Test extends AbstractTestingFramework { @Test public void testNewTest() { String testClass = "soot.lambdaMetaFactory.Issue1292"; prepareTarget( methodSigFromComponents(testClass, "void", "testNew", "java.util.List"), testClass, "java.util.function.Function"); // if no exception is thrown, everything is working as intended } }
1,565
32.319149
92
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/Issue1367Test.java
package soot.lambdaMetaFactory; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2019 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.SootMethod; import soot.testing.framework.AbstractTestingFramework; /** * Reproduces issue 1367: https://github.com/Sable/soot/issues/1367 * * @author David Seekatz */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class Issue1367Test extends AbstractTestingFramework { @Test public void constructorReference() { String testClass = "soot.lambdaMetaFactory.Issue1367"; final SootMethod target = prepareTarget( methodSigFromComponents(testClass, "java.util.function.Supplier", "constructorReference"), testClass, "java.util.function.Function"); validateAllBodies(target.getDeclaringClass()); } }
1,669
31.745098
106
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/LambdaMetaFactoryAdaptTest.java
package soot.lambdaMetaFactory; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2019 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.SootMethod; import soot.testing.framework.AbstractTestingFramework; /** * @author Manuel Benz created on 2018-12-18 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class LambdaMetaFactoryAdaptTest extends AbstractTestingFramework { @Test public void parameterBoxing() { String testClass = "soot.lambdaMetaFactory.Adapt"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, "void", "parameterBoxingTarget"), testClass); // TODO more fine-grained testing validateAllBodies(target.getDeclaringClass()); } @Test public void parameterWidening() { String testClass = "soot.lambdaMetaFactory.Adapt"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, "void", "parameterWidening"), testClass); // TODO more fine-grained testing validateAllBodies(target.getDeclaringClass()); } @Test public void returnBoxing() { String testClass = "soot.lambdaMetaFactory.Adapt"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, "void", "returnBoxing"), testClass); // TODO more fine-grained testing validateAllBodies(target.getDeclaringClass()); } @Test public void returnWidening() { String testClass = "soot.lambdaMetaFactory.Adapt"; final SootMethod target = prepareTarget(methodSigFromComponents(testClass, "void", "returnWidening"), testClass); // TODO more fine-grained testing validateAllBodies(target.getDeclaringClass()); } }
2,476
29.580247
124
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/LambdaMetaFactoryCHATest.java
package soot.lambdaMetaFactory; import org.powermock.core.classloader.annotations.PowerMockIgnore; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.PhaseOptions; /** * @author Manuel Benz created on 31.10.18 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class LambdaMetaFactoryCHATest extends AbstractLambdaMetaFactoryCGTest { @Override protected void setupSoot() { super.setupSoot(); PhaseOptions.v().setPhaseOption("cg.cha", "on"); } }
1,271
30.8
92
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/LambdaMetaFactoryRTATest.java
package soot.lambdaMetaFactory; import org.powermock.core.classloader.annotations.PowerMockIgnore; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.options.Options; /** * @author Manuel Benz created on 31.10.18 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class LambdaMetaFactoryRTATest extends AbstractLambdaMetaFactoryCGTest { @Override protected void setupSoot() { super.setupSoot(); Options.v().setPhaseOption("cg.spark", "on"); Options.v().setPhaseOption("cg.spark", "rta:true"); Options.v().setPhaseOption("cg.spark", "on-fly-cg:false"); } }
1,390
32.119048
92
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/LambdaMetaFactorySPARKTest.java
package soot.lambdaMetaFactory; import org.powermock.core.classloader.annotations.PowerMockIgnore; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.PhaseOptions; /** * @author Manuel Benz created on 31.10.18 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class LambdaMetaFactorySPARKTest extends AbstractLambdaMetaFactoryCGTest { @Override protected void setupSoot() { super.setupSoot(); PhaseOptions.v().setPhaseOption("cg.spark", "on"); } }
1,275
30.9
92
java
soot
soot-master/src/systemTest/java/soot/lambdaMetaFactory/LambdaMetaFactoryVTATest.java
package soot.lambdaMetaFactory; import org.powermock.core.classloader.annotations.PowerMockIgnore; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.options.Options; /** * @author Manuel Benz created on 31.10.18 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class LambdaMetaFactoryVTATest extends AbstractLambdaMetaFactoryCGTest { @Override protected void setupSoot() { super.setupSoot(); Options.v().setPhaseOption("cg.spark", "on"); Options.v().setPhaseOption("cg.spark", "vta:true"); } }
1,327
31.390244
92
java
soot
soot-master/src/systemTest/java/soot/testing/framework/AbstractTestingFramework.java
package soot.testing.framework; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.junit.Assert; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; import soot.ArrayType; import soot.Body; import soot.G; import soot.Local; import soot.Modifier; import soot.PackManager; import soot.PhaseOptions; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.UnitPatchingChain; import soot.Value; import soot.VoidType; import soot.baf.Baf; import soot.baf.BafASMBackend; import soot.baf.BafBody; import soot.jimple.Jimple; import soot.jimple.JimpleBody; import soot.jimple.NullConstant; import soot.options.Options; import soot.shimple.ShimpleBody; import soot.util.Chain; /** * @author Manuel Benz created on 22.06.18 * @author Andreas Dann * @author Timothy Hoffman */ @RunWith(PowerMockRunner.class) @PowerMockIgnore({ "javax.management.", "com.sun.org.apache.xerces.", "javax.xml.", "org.xml.", "org.w3c.dom.", "com.sun.org.apache.xalan.", "javax.activation.*" }) public abstract class AbstractTestingFramework { protected static final String SYSTEMTEST_TARGET_CLASSES_DIR = "target/systemTest-target-classes"; public static String methodSigFromComponents(String clazz, String subsig) { return String.format("<%s: %s>", clazz, subsig); } public static String methodSigFromComponents(String clazz, String returnType, String methodName, String... params) { return methodSigFromComponents(clazz, String.format("%s %s(%s)", returnType, methodName, String.join(",", params))); } public static void validateAllBodies(SootClass... classes) { for (SootClass aClass : classes) { for (SootMethod method : aClass.getMethods()) { method.retrieveActiveBody().validate(); } } } /** * Sets up the Scene by analyzing all included classes and generating a call graph for the given target. This is done by * generating an entry point that calls the method with the given signature. * <p> * <p> * Important: Every test case has to call this method with an appropriate target before testing something. * * @param targetMethodSignature * Signature of the method to be analyzed * @param classesOrPackagesToAnalyze * Defines the list of classes/packages that are included when building the Scene. State package with wildcards, * e.g., "soot.*" to include all classes in the soot package. Note that it is good practice to include all classes * that are tested (or the complete package) explicitly, to ensure they are not excluded when building the Scene. * @return */ protected SootMethod prepareTarget(String targetMethodSignature, String... classesOrPackagesToAnalyze) { return prepareTarget(targetMethodSignature, Arrays.asList(classesOrPackagesToAnalyze)); } /** * Sets up the Scene by analyzing all included classes and generating a call graph for the given target. This is done by * generating an entry point that calls the method with the given signature. * <p> * <p> * Important: Every test case has to call this method with an appropriate target before testing something. * * @param targetMethodSignature * Signature of the method to be analyzed * @param classesOrPackagesToAnalyze * Defines the list of classes/packages that are included when building the Scene. State package with wildcards, * e.g., "soot.*" to include all classes in the soot package. Note that it is good practice to include all classes * that are tested (or the complete package) explicitly, to ensure they are not excluded when building the Scene. * @return */ protected SootMethod prepareTarget(String targetMethodSignature, Collection<String> classesOrPackagesToAnalyze) { setupSoot(classesOrPackagesToAnalyze); Scene.v().loadNecessaryClasses(); mockStatics(); SootMethod sootTestMethod = createTestTarget(targetMethodSignature); runSoot(); Assert.assertNotNull( "Could not find target method. System test setup seems to be incorrect. Please try to re-run `mvn test-compile` to make sure that the target code is present for analysis.", sootTestMethod); return sootTestMethod; } /** * Can be used to mock static members with PowerMock if needed. Is run right after Soot was initialized and before the * testing target is acquired */ protected void mockStatics() { } protected void runSoot() { PackManager.v().runPacks(); } /** * Sets common options for all test cases * * @param classesOrPackagesToAnalyze */ private void setupSoot(Collection<String> classesOrPackagesToAnalyze) { G.reset(); Options.v().set_whole_program(true); Options.v().set_output_format(Options.output_format_none); Options.v().set_allow_phantom_refs(true); Options.v().set_no_bodies_for_excluded(true); Options.v().set_exclude(getExcludes()); Options.v().set_include(new ArrayList<>(classesOrPackagesToAnalyze)); Options.v().set_process_dir(Collections.singletonList(SYSTEMTEST_TARGET_CLASSES_DIR)); Options.v().set_validate(true); setupSoot(); } /** * Can be used to set Soot options as needed */ protected void setupSoot() { PhaseOptions.v().setPhaseOption("cg.spark", "on"); } /** * Defines the list of classes/packages that are excluded when building the Scene. State package with wildcards, e.g., * "soot.*" to exclude all classes in the soot package. * <p> * Note that it is good practice to exclude everything and include only the needed classes for the specific test case when * calling {@link AbstractTestingFramework#prepareTarget(String, String...)} * * @return A list of excluded packages and classes */ protected List<String> getExcludes() { List<String> excludeList = new ArrayList<>(); //excludeList.add("java.*"); excludeList.add("sun.*"); excludeList.add("android.*"); excludeList.add("org.apache.*"); excludeList.add("org.eclipse.*"); excludeList.add("soot.*"); excludeList.add("javax.*"); return excludeList; } private SootMethod createTestTarget(String targetMethod) { SootMethod sootTestMethod = getMethodForSig(targetMethod); if (sootTestMethod == null) { throw new RuntimeException("The method with name " + targetMethod + " was not found in the Soot Scene."); } SootClass targetClass = makeDummyClass(sootTestMethod); Scene.v().addClass(targetClass); targetClass.setApplicationClass(); Scene.v().setEntryPoints(Collections.singletonList(targetClass.getMethodByName("main"))); return sootTestMethod; } private SootClass makeDummyClass(SootMethod sootTestMethod) { SootClass sootClass = new SootClass("dummyClass"); ArrayType argsParamterType = ArrayType.v(RefType.v("java.lang.String"), 1); SootMethod mainMethod = new SootMethod("main", Arrays.asList(new Type[] { argsParamterType }), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); sootClass.addMethod(mainMethod); final Jimple jimp = Jimple.v(); final JimpleBody body = jimp.newBody(mainMethod); mainMethod.setActiveBody(body); final Chain<Local> locals = body.getLocals(); final UnitPatchingChain units = body.getUnits(); Local argsParameter = jimp.newLocal("args", argsParamterType); locals.add(argsParameter); units.add(jimp.newIdentityStmt(argsParameter, jimp.newParameterRef(argsParamterType, 0))); RefType testCaseType = RefType.v(sootTestMethod.getDeclaringClass()); Local allocatedTestObj = jimp.newLocal("dummyObj", testCaseType); locals.add(allocatedTestObj); units.add(jimp.newAssignStmt(allocatedTestObj, jimp.newNewExpr(testCaseType))); SootMethod method; try { method = testCaseType.getSootClass().getMethod("void <init>()"); } catch (RuntimeException ex) { method = testCaseType.getSootClass().getMethodByName("<init>"); } List<Value> constructorArgs = Collections.nCopies(method.getParameterCount(), NullConstant.v()); units.add(jimp.newInvokeStmt(jimp.newSpecialInvokeExpr(allocatedTestObj, method.makeRef(), constructorArgs))); List<Value> args = Collections.nCopies(sootTestMethod.getParameterCount(), NullConstant.v()); units.add(jimp.newInvokeStmt(jimp.newVirtualInvokeExpr(allocatedTestObj, sootTestMethod.makeRef(), args))); units.add(jimp.newReturnVoidStmt()); return sootClass; } private String classFromSignature(String targetMethod) { return targetMethod.substring(1, targetMethod.indexOf(':')); } private SootMethod getMethodForSig(String sig) { Scene.v().forceResolve(classFromSignature(sig), SootClass.BODIES); return Scene.v().getMethod(sig); } /** * Create and load a {@link Class} in the current JVM by converting the given {@link SootClass} to bytecode. * * @param sc * @return */ public static Class<?> generateClass(SootClass sc) { final byte[] classBytes = generateBytecode(sc); // Using a new ClassLoader instance for each call to this method ensures every // class loaded is a distinct Class instance, even when they have the same name. return new ClassLoader() { @Override public Class findClass(String name) { return defineClass(name, classBytes, 0, classBytes.length); } }.findClass(sc.getName()); } /** * Convert the given {@link SootClass} to JVM bytecode. * * @param sc * @return */ public static byte[] generateBytecode(SootClass sc) { // First, convert all method Body instances to BafBody for (SootMethod m : sc.getMethods()) { if (m.isConcrete()) { convertBodyToBaf(m); } } // Then use ASM to generate a byte[] for the classfile ByteArrayOutputStream os = new ByteArrayOutputStream(); new BafASMBackend(sc, Options.v().java_version()).generateClassFile(os); return os.toByteArray(); } /** * Converts the {@link Body} of the given {@link SootMethod} to a {@link BafBody}. * * @param m */ public static void convertBodyToBaf(SootMethod m) { Body b = m.retrieveActiveBody(); Assert.assertNotNull(b); if (!(b instanceof BafBody)) { // If ShimpleBody, first convert to JimpleBody if (b instanceof ShimpleBody) { b = ((ShimpleBody) b).toJimpleBody(); } Assert.assertTrue("Does not currently handle " + b.getClass(), b instanceof JimpleBody); // Convert JimpleBody to BafBody (based on PackManager#convertJimpleBodyToBaf) BafBody bafBody = Baf.v().newBody((JimpleBody) b); PackManager.v().getPack("bop").apply(bafBody); PackManager.v().getPack("tag").apply(bafBody); m.setActiveBody(bafBody); } } /** * @param sc * @param className * @param resolvingLevel * one of the constants defined in {@link SootClass} * * @return the {@link SootClass} with the given name * * @see SootClass#DANGLING * @see SootClass#HIERARCHY * @see SootClass#SIGNATURES * @see SootClass#BODIES */ public static SootClass getOrResolveSootClass(Scene sc, String className, int resolvingLevel) { Assert.assertNotNull(className); if (sc.containsClass(className)) { SootClass retVal = sc.getSootClass(className); if (retVal.resolvingLevel() >= resolvingLevel && !retVal.isPhantom()) { assertResolvePostConditions(retVal, resolvingLevel); return retVal; } else { // The forceResolve(..) will not make any change if the class is // phantom or the resolving level is already high enough, so ensure // those two conditions will be false before trying the resolution. retVal.setResolvingLevel(SootClass.DANGLING); retVal.setLibraryClass(); } } SootClass retVal = sc.forceResolve(className, resolvingLevel); retVal.setApplicationClass(); assertResolvePostConditions(retVal, resolvingLevel); return retVal; } private static void assertResolvePostConditions(SootClass c, int expectLvl) { Assert.assertNotNull(c); Assert.assertFalse("phantom class: " + c, c.isPhantom()); Assert.assertTrue("insufficiently resolved: (" + c.resolvingLevel() + ") " + c, c.resolvingLevel() >= expectLvl); for (SootMethod m : c.getMethods()) { Assert.assertFalse("phantom method: " + m, m.isPhantom()); Assert.assertTrue("concrete method without method body/source: " + m, !m.isConcrete() || m.hasActiveBody() || m.getSource() != null); } } }
13,626
36.643646
180
java
soot
soot-master/src/systemTest/java/soot/testing/framework/HelloTestingFrameworkTest.java
package soot.testing.framework; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2018 Manuel Benz * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.SootMethod; /** * @author Manuel Benz created on 22.06.18 */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class HelloTestingFrameworkTest extends AbstractTestingFramework { private static final String TEST_TARGET_CLASS = "soot.testing.framework.HelloTestingFrameworkTarget"; @Test public void findsTarget() { final SootMethod sootMethod = prepareTarget("<" + TEST_TARGET_CLASS + ": void helloWorld()>", TEST_TARGET_CLASS); Assert.assertNotNull("Could not find target method. System test setup seems to be incorrect.", sootMethod); Assert.assertTrue(sootMethod.isConcrete()); Assert.assertNotNull(sootMethod.retrieveActiveBody()); } }
1,676
33.9375
117
java
soot
soot-master/src/systemTest/java/soot/toolkits/scalar/LocalPackerTest.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2020 Timothy Hoffman * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Assert; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import soot.Body; import soot.Local; import soot.SootMethod; import soot.jimple.JimpleBody; import soot.options.Options; import soot.testing.framework.AbstractTestingFramework; /** * @author Timothy Hoffman */ @PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" }) public class LocalPackerTest extends AbstractTestingFramework { private static final String TEST_TARGET_CLASS = "soot.toolkits.scalar.LocalPackerTestInput"; @Override protected void setupSoot() { Options.v().setPhaseOption("jb", "use-original-names:true"); Options.v().setPhaseOption("jb.sils", "enabled:false"); } @Test public void nullAssignment() { SootMethod target = prepareTarget(methodSigFromComponents(TEST_TARGET_CLASS, "void", "prefixVariableNames"), TEST_TARGET_CLASS); Body body = target.retrieveActiveBody(); Assert.assertTrue(body instanceof JimpleBody); // Assert all local names are distinct Assert.assertTrue(body.getLocals().stream().map(Local::getName).distinct().count() == body.getLocalCount()); LocalPacker.v().transform(body); // Assert all local names are distinct Assert.assertTrue(body.getLocals().stream().map(Local::getName).distinct().count() == body.getLocalCount()); } }
2,222
32.179104
116
java