repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/WrappedPointsToSet.java
|
package soot.jimple.spark.ondemand;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Set;
import soot.PointsToSet;
import soot.Type;
import soot.jimple.ClassConstant;
import soot.jimple.spark.sets.EqualsSupportingPointsToSet;
import soot.jimple.spark.sets.PointsToSetInternal;
public class WrappedPointsToSet implements EqualsSupportingPointsToSet {
final PointsToSetInternal wrapped;
public PointsToSetInternal getWrapped() {
return wrapped;
}
public WrappedPointsToSet(final PointsToSetInternal wrapped) {
super();
this.wrapped = wrapped;
}
public boolean hasNonEmptyIntersection(PointsToSet other) {
if (other instanceof AllocAndContextSet) {
return other.hasNonEmptyIntersection(this);
} else if (other instanceof WrappedPointsToSet) {
return hasNonEmptyIntersection(((WrappedPointsToSet) other).getWrapped());
} else {
return wrapped.hasNonEmptyIntersection(other);
}
}
public boolean isEmpty() {
return wrapped.isEmpty();
}
public Set<ClassConstant> possibleClassConstants() {
return wrapped.possibleClassConstants();
}
public Set<String> possibleStringConstants() {
return wrapped.possibleStringConstants();
}
public Set<Type> possibleTypes() {
return wrapped.possibleTypes();
}
public String toString() {
return wrapped.toString();
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
// have to get around the tyranny of reference losing equality
if (obj instanceof WrappedPointsToSet) {
WrappedPointsToSet wrapper = (WrappedPointsToSet) obj;
return wrapped.equals(wrapper.wrapped);
}
return obj.equals(wrapped);
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return wrapped.hashCode();
}
/**
* {@inheritDoc}
*/
public boolean pointsToSetEquals(Object other) {
if (!(other instanceof EqualsSupportingPointsToSet)) {
return false;
}
EqualsSupportingPointsToSet otherPts = (EqualsSupportingPointsToSet) unwrapIfNecessary(other);
return wrapped.pointsToSetEquals(otherPts);
}
/**
* {@inheritDoc}
*/
public int pointsToSetHashCode() {
return wrapped.pointsToSetHashCode();
}
protected Object unwrapIfNecessary(Object obj) {
if (obj instanceof WrappedPointsToSet) {
WrappedPointsToSet wrapper = (WrappedPointsToSet) obj;
obj = wrapper.wrapped;
}
return obj;
}
}
| 3,295
| 24.160305
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/AbstractMultiMap.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
abstract class AbstractMultiMap<K, V> implements MultiMap<K, V> {
protected final Map<K, Set<V>> map = new HashMap<K, Set<V>>();
protected final boolean create;
protected AbstractMultiMap(boolean create) {
this.create = create;
}
protected abstract Set<V> createSet();
protected Set<V> emptySet() {
return Collections.<V>emptySet();
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#get(K)
*/
@Override
public Set<V> get(K key) {
Set<V> ret = map.get(key);
if (ret == null) {
if (create) {
ret = createSet();
map.put(key, ret);
} else {
ret = emptySet();
}
}
return ret;
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#put(K, V)
*/
@Override
public boolean put(K key, V val) {
Set<V> vals = map.get(key);
if (vals == null) {
vals = createSet();
map.put(key, vals);
}
return vals.add(val);
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#remove(K, V)
*/
@Override
public boolean remove(K key, V val) {
Set<V> elems = map.get(key);
if (elems == null) {
return false;
}
boolean ret = elems.remove(val);
if (elems.isEmpty()) {
map.remove(key);
}
return ret;
}
@Override
public Set<V> removeAll(K key) {
return map.remove(key);
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#keys()
*/
@Override
public Set<K> keySet() {
return map.keySet();
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#containsKey(java.lang.Object)
*/
@Override
public boolean containsKey(K key) {
return map.containsKey(key);
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#size()
*/
@Override
public int size() {
int ret = 0;
for (K key : keySet()) {
ret += get(key).size();
}
return ret;
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#toString()
*/
@Override
public String toString() {
return map.toString();
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#putAll(K, java.util.Set)
*/
@Override
public boolean putAll(K key, Collection<? extends V> vals) {
Set<V> edges = map.get(key);
if (edges == null) {
edges = createSet();
map.put(key, edges);
}
return edges.addAll(vals);
}
@Override
public void clear() {
map.clear();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
}
| 3,459
| 19
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/ArraySet.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ArraySet<T> extends AbstractSet<T> {
private static final ArraySet EMPTY = new ArraySet<Object>(0, true) {
public boolean add(Object obj_) {
throw new RuntimeException();
}
};
@SuppressWarnings("all")
public static final <T> ArraySet<T> empty() {
return (ArraySet<T>) EMPTY;
}
private T[] _elems;
private int _curIndex = 0;
private final boolean checkDupes;
@SuppressWarnings("all")
public ArraySet(int numElems_, boolean checkDupes) {
_elems = (T[]) new Object[numElems_];
this.checkDupes = checkDupes;
}
public ArraySet() {
this(1, true);
}
@SuppressWarnings("all")
public ArraySet(ArraySet<T> other) {
int size = other._curIndex;
this._elems = (T[]) new Object[size];
this.checkDupes = other.checkDupes;
this._curIndex = size;
System.arraycopy(other._elems, 0, _elems, 0, size);
}
public ArraySet(Collection<T> other) {
this(other.size(), true);
addAll(other);
}
/*
* (non-Javadoc)
*
* @see AAA.util.AAASet#add(java.lang.Object)
*/
@SuppressWarnings("all")
public boolean add(T obj_) {
assert obj_ != null;
if (checkDupes && this.contains(obj_)) {
return false;
}
if (_curIndex == _elems.length) {
// lengthen array
Object[] tmp = _elems;
_elems = (T[]) new Object[tmp.length * 2];
System.arraycopy(tmp, 0, _elems, 0, tmp.length);
}
_elems[_curIndex] = obj_;
_curIndex++;
return true;
}
public boolean addAll(ArraySet<T> other) {
boolean ret = false;
for (int i = 0; i < other.size(); i++) {
boolean added = add(other.get(i));
ret = ret || added;
}
return ret;
}
/*
* (non-Javadoc)
*
* @see AAA.util.AAASet#contains(java.lang.Object)
*/
public boolean contains(Object obj_) {
for (int i = 0; i < _curIndex; i++) {
if (_elems[i].equals(obj_)) {
return true;
}
}
return false;
}
public boolean intersects(ArraySet<T> other) {
for (int i = 0; i < other.size(); i++) {
if (contains(other.get(i))) {
return true;
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see AAA.util.AAASet#forall(AAA.util.ObjectVisitor)
*/
public void forall(ObjectVisitor<T> visitor_) {
for (int i = 0; i < _curIndex; i++) {
visitor_.visit(_elems[i]);
}
}
public int size() {
return _curIndex;
}
public T get(int i) {
return _elems[i];
}
public boolean remove(Object obj_) {
int ind;
for (ind = 0; ind < _curIndex && !_elems[ind].equals(obj_); ind++) {
}
// check if object was never there
if (ind == _curIndex) {
return false;
}
return remove(ind);
}
/**
* @param ind
* @return
*/
public boolean remove(int ind) {
// hope i got this right...
System.arraycopy(_elems, ind + 1, _elems, ind, _curIndex - (ind + 1));
_curIndex--;
return true;
}
public void clear() {
_curIndex = 0;
}
public boolean isEmpty() {
return size() == 0;
}
public String toString() {
StringBuffer ret = new StringBuffer();
ret.append('[');
for (int i = 0; i < size(); i++) {
ret.append(get(i).toString());
if (i + 1 < size()) {
ret.append(", ");
}
}
ret.append(']');
return ret.toString();
}
/*
* (non-Javadoc)
*
* @see java.util.Set#toArray()
*/
public Object[] toArray() {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see java.util.Set#addAll(java.util.Collection)
*/
public boolean addAll(Collection<? extends T> c) {
boolean ret = false;
for (T element : c) {
boolean added = add(element);
ret = ret || added;
}
return ret;
}
/*
* (non-Javadoc)
*
* @see java.util.Set#iterator()
*/
public Iterator<T> iterator() {
return new ArraySetIterator();
}
/*
* (non-Javadoc)
*
* @see java.util.Set#toArray(java.lang.Object[])
*/
@SuppressWarnings("unchecked")
public <U> U[] toArray(U[] a) {
for (int i = 0; i < _curIndex; i++) {
T t = _elems[i];
a[i] = (U) t;
}
return a;
}
/**
* @author manu
*/
public class ArraySetIterator implements Iterator<T> {
int ind = 0;
final int setSize = size();
/**
*
*/
public ArraySetIterator() {
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return ind < setSize;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#next()
*/
public T next() {
if (ind >= setSize) {
throw new NoSuchElementException();
}
return get(ind++);
}
}
}
| 5,917
| 19.911661
| 74
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/ArraySetDupesMultiMap.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Set;
public class ArraySetDupesMultiMap<K, V> extends AbstractMultiMap<K, V> {
public ArraySetDupesMultiMap(boolean create) {
super(create);
}
public ArraySetDupesMultiMap() {
this(false);
}
@Override
protected Set<V> createSet() {
return new ArraySet<V>(1, false);
}
}
| 1,166
| 26.139535
| 73
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/ArraySetMultiMap.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.Set;
public class ArraySetMultiMap<K, V> extends AbstractMultiMap<K, V> {
public static final ArraySetMultiMap EMPTY = new ArraySetMultiMap<Object, Object>() {
public boolean put(Object key, Object val) {
throw new RuntimeException();
}
public boolean putAll(Object key, Collection<? extends Object> vals) {
throw new RuntimeException();
}
};
public ArraySetMultiMap() {
super(false);
}
public ArraySetMultiMap(boolean create) {
super(create);
}
@Override
protected Set<V> createSet() {
return new ArraySet<V>();
}
protected Set<V> emptySet() {
return ArraySet.<V>empty();
}
public ArraySet<V> get(K key) {
return (ArraySet<V>) super.get(key);
}
}
| 1,625
| 25.225806
| 87
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/Averager.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class Averager {
private double curAverage;
private long numSamples;
public void addSample(double sample) {
curAverage = ((curAverage * numSamples) + sample) / (numSamples + 1);
numSamples++;
}
/**
* @return
*/
public double getCurAverage() {
return curAverage;
}
/**
* @return
*/
public long getNumSamples() {
return numSamples;
}
}
| 1,243
| 23.392157
| 73
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/DisjointSets.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Arrays;
public final class DisjointSets {
private int[] array;
/**
* Construct a disjoint sets object.
*
* @param numElements
* the initial number of elements--also the initial number of disjoint sets, since every element is initially in
* its own set.
*/
public DisjointSets(int numElements) {
array = new int[numElements];
Arrays.fill(array, -1);
}
/**
* union() unites two disjoint sets into a single set. A union-by-size heuristic is used to choose the new root. This
* method will corrupt the data structure if root1 and root2 are not roots of their respective sets, or if they're
* identical.
*
* @param root1
* the root of the first set.
* @param root2
* the root of the other set.
*/
public void union(int root1, int root2) {
assert array[root1] < 0;
assert array[root2] < 0;
assert root1 != root2;
if (array[root2] < array[root1]) { // root2 has larger tree
array[root2] += array[root1]; // update # of items in root2's tree
array[root1] = root2; // make root2 new root
} else { // root1 has equal or larger tree
array[root1] += array[root2]; // update # of items in root1's tree
array[root2] = root1; // make root1 new root
}
}
/**
* find() finds the (int) name of the set containing a given element. Performs path compression along the way.
*
* @param x
* the element sought.
* @return the set containing x.
*/
public int find(int x) {
if (array[x] < 0) {
return x; // x is the root of the tree; return it
} else {
// Find out who the root is; compress path by making the root x's
// parent.
array[x] = find(array[x]);
return array[x]; // Return the root
}
}
}
| 2,668
| 30.77381
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/FIFOQueue.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* A FIFO queue of objects, implemented as a circular buffer. NOTE: elements stored in the buffer should be non-null; this is
* not checked for performance reasons.
*
* @author Manu Sridharan
*/
public final class FIFOQueue {
/**
* the buffer.
*/
private Object[] _buf;
/**
* pointer to current top of buffer
*/
private int _top;
/**
* point to current bottom of buffer, where things will be added invariant: after call to add / remove, should always point
* to an empty slot in the buffer
*/
private int _bottom;
/**
* @param initialSize_
* the initial size of the queue
*/
public FIFOQueue(int initialSize_) {
_buf = new Object[initialSize_];
}
public FIFOQueue() {
this(10);
}
public boolean push(Object obj_) {
return add(obj_);
}
/**
* add an element to the bottom of the queue
*/
public boolean add(Object obj_) {
// Assert.chk(obj_ != null);
// add the element
_buf[_bottom] = obj_;
// increment bottom, wrapping around if necessary
_bottom = (_bottom == _buf.length - 1) ? 0 : _bottom + 1;
// see if we need to increase the queue size
if (_bottom == _top) {
// allocate a new array and copy
int oldLen = _buf.length;
int newLen = oldLen * 2;
// System.out.println("growing buffer to size " + newLen);
Object[] newBuf = new Object[newLen];
int topToEnd = oldLen - _top;
int newTop = newLen - topToEnd;
// copy from 0 to _top to beginning of new buffer,
// _top to _buf.length to the end of the new buffer
System.arraycopy(_buf, 0, newBuf, 0, _top);
System.arraycopy(_buf, _top, newBuf, newTop, topToEnd);
_buf = newBuf;
_top = newTop;
return true;
}
return false;
}
public Object pop() {
return remove();
}
/**
* remove the top element from the buffer
*/
public Object remove() {
// check if buffer is empty
if (_bottom == _top) {
return null;
}
Object ret = _buf[_top];
// increment top, wrapping if necessary
_top = (_top == _buf.length - 1) ? 0 : _top + 1;
return ret;
}
public boolean isEmpty() {
return _bottom == _top;
}
public String toString() {
return _bottom + " " + _top;
}
public void clear() {
_bottom = 0;
_top = 0;
}
}
| 3,200
| 24.608
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/HashSetMultiMap.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.Set;
public class HashSetMultiMap<K, V> extends AbstractMultiMap<K, V> {
public HashSetMultiMap() {
super(false);
}
public HashSetMultiMap(boolean create) {
super(create);
}
@Override
protected Set<V> createSet() {
return new HashSet<V>();
}
}
| 1,166
| 25.522727
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/ImmutableStack.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Arrays;
public class ImmutableStack<T> {
private static final ImmutableStack<Object> EMPTY = new ImmutableStack<Object>(new Object[0]);
private static final int MAX_SIZE = Integer.MAX_VALUE;
public static int getMaxSize() {
return MAX_SIZE;
}
@SuppressWarnings("unchecked")
public static final <T> ImmutableStack<T> emptyStack() {
return (ImmutableStack<T>) EMPTY;
}
final private T[] entries;
private ImmutableStack(T[] entries) {
this.entries = entries;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o != null && o instanceof ImmutableStack) {
ImmutableStack other = (ImmutableStack) o;
return Arrays.equals(entries, other.entries);
}
return false;
}
public int hashCode() {
return Util.hashArray(this.entries);
}
@SuppressWarnings("unchecked")
public ImmutableStack<T> push(T entry) {
assert entry != null;
if (MAX_SIZE == 0) {
return emptyStack();
}
int size = entries.length + 1;
T[] tmpEntries = null;
if (size <= MAX_SIZE) {
tmpEntries = (T[]) new Object[size];
System.arraycopy(entries, 0, tmpEntries, 0, entries.length);
tmpEntries[size - 1] = entry;
} else {
tmpEntries = (T[]) new Object[MAX_SIZE];
System.arraycopy(entries, 1, tmpEntries, 0, entries.length - 1);
tmpEntries[MAX_SIZE - 1] = entry;
}
return new ImmutableStack<T>(tmpEntries);
}
public T peek() {
assert entries.length != 0;
return entries[entries.length - 1];
}
@SuppressWarnings("unchecked")
public ImmutableStack<T> pop() {
assert entries.length != 0;
int size = entries.length - 1;
T[] tmpEntries = (T[]) new Object[size];
System.arraycopy(entries, 0, tmpEntries, 0, size);
return new ImmutableStack<T>(tmpEntries);
}
public boolean isEmpty() {
return entries.length == 0;
}
public int size() {
return entries.length;
}
public T get(int i) {
return entries[i];
}
public String toString() {
String objArrayToString = Util.objArrayToString(entries);
assert entries.length <= MAX_SIZE : objArrayToString;
return objArrayToString;
}
public boolean contains(T entry) {
return Util.arrayContains(entries, entry, entries.length);
}
public boolean topMatches(ImmutableStack<T> other) {
if (other.size() > size()) {
return false;
}
for (int i = other.size() - 1, j = this.size() - 1; i >= 0; i--, j--) {
if (!other.get(i).equals(get(j))) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
public ImmutableStack<T> reverse() {
T[] tmpEntries = (T[]) new Object[entries.length];
for (int i = entries.length - 1, j = 0; i >= 0; i--, j++) {
tmpEntries[j] = entries[i];
}
return new ImmutableStack<T>(tmpEntries);
}
@SuppressWarnings("unchecked")
public ImmutableStack<T> popAll(ImmutableStack<T> other) {
// TODO Auto-generated method stub
assert topMatches(other);
int size = entries.length - other.entries.length;
T[] tmpEntries = (T[]) new Object[size];
System.arraycopy(entries, 0, tmpEntries, 0, size);
return new ImmutableStack<T>(tmpEntries);
}
@SuppressWarnings("unchecked")
public ImmutableStack<T> pushAll(ImmutableStack<T> other) {
// TODO Auto-generated method stub
int size = entries.length + other.entries.length;
T[] tmpEntries = null;
if (size <= MAX_SIZE) {
tmpEntries = (T[]) new Object[size];
System.arraycopy(entries, 0, tmpEntries, 0, entries.length);
System.arraycopy(other.entries, 0, tmpEntries, entries.length, other.entries.length);
} else {
tmpEntries = (T[]) new Object[MAX_SIZE];
// other has size at most MAX_SIZE
// must keep all in other
// top MAX_SIZE - other.size from this
int numFromThis = MAX_SIZE - other.entries.length;
System.arraycopy(entries, entries.length - numFromThis, tmpEntries, 0, numFromThis);
System.arraycopy(other.entries, 0, tmpEntries, numFromThis, other.entries.length);
}
return new ImmutableStack<T>(tmpEntries);
}
}
| 5,025
| 28.22093
| 96
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/IteratorMapper.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
public class IteratorMapper<T, U> implements Iterator<U> {
private final Mapper<T, U> mapper;
private final Iterator<T> delegate;
public IteratorMapper(final Mapper<T, U> mapper, final Iterator<T> delegate) {
this.mapper = mapper;
this.delegate = delegate;
}
public boolean hasNext() {
return delegate.hasNext();
}
public U next() {
// TODO Auto-generated method stub
return mapper.map(delegate.next());
}
public void remove() {
delegate.remove();
}
}
| 1,379
| 25.538462
| 80
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/Mapper.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* A simple interface for defining a function that maps objects.
*/
public interface Mapper<T, U> {
public U map(T obj_);
}
| 979
| 30.612903
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/MultiMap.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.Set;
public interface MultiMap<K, V> {
public Set<V> get(K key);
public boolean put(K key, V val);
public boolean remove(K key, V val);
public Set<K> keySet();
public boolean containsKey(K key);
public int size();
public String toString();
public boolean putAll(K key, Collection<? extends V> vals);
public Set<V> removeAll(K key);
public void clear();
public boolean isEmpty();
}
| 1,308
| 24.666667
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/MutablePair.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* A mutable pair of objects.
*
* @author manu
*
*/
public class MutablePair<T, U> {
public MutablePair(T o1, U o2) {
this.o1 = o1;
this.o2 = o2;
}
public int hashCode() {
return o1.hashCode() + o2.hashCode();
}
public boolean equals(Object other) {
if (other instanceof MutablePair) {
MutablePair p = (MutablePair) other;
return o1.equals(p.o1) && o2.equals(p.o2);
} else {
return false;
}
}
public String toString() {
return "Pair " + o1 + "," + o2;
}
public T getO1() {
return o1;
}
public U getO2() {
return o2;
}
private T o1;
private U o2;
public void setO1(T o1) {
this.o1 = o1;
}
public void setO2(U o2) {
this.o2 = o2;
}
}
| 1,599
| 20.052632
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/ObjWrapper.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* @author manu
*/
public class ObjWrapper {
public final Object wrapped;
/**
* @param wrapped
*/
public ObjWrapper(final Object wrapped) {
this.wrapped = wrapped;
}
public String toString() {
return "wrapped " + wrapped;
}
}
| 1,108
| 24.790698
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/ObjectVisitor.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public interface ObjectVisitor<T> {
public void visit(T obj_);
}
| 917
| 29.6
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/Predicate.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Interface for defining an arbitrary predicate on {@link Object}s.
*/
public abstract class Predicate<T> {
public static final Predicate FALSE = new Predicate() {
@Override
public boolean test(Object obj_) {
return false;
}
};
public static final Predicate TRUE = FALSE.not();
@SuppressWarnings("unchecked")
public static <T> Predicate<T> truePred() {
return (Predicate<T>) TRUE;
}
@SuppressWarnings("unchecked")
public static <T> Predicate<T> falsePred() {
return (Predicate<T>) FALSE;
}
/** Test whether an {@link Object} satisfies this {@link Predicate} */
public abstract boolean test(T obj_);
/** Return a predicate that is a negation of this predicate */
public Predicate<T> not() {
final Predicate<T> originalPredicate = this;
return new Predicate<T>() {
public boolean test(T obj_) {
return !originalPredicate.test(obj_);
}
};
}
/**
* Return a predicate that is a conjunction of this predicate and another predicate
*/
public Predicate<T> and(final Predicate<T> conjunct_) {
final Predicate<T> originalPredicate = this;
return new Predicate<T>() {
public boolean test(T obj_) {
return originalPredicate.test(obj_) && conjunct_.test(obj_);
}
};
}
/**
* Return a predicate that is a conjunction of this predicate and another predicate
*/
public Predicate<T> or(final Predicate<T> disjunct_) {
final Predicate<T> originalPredicate = this;
return new Predicate<T>() {
public boolean test(T obj_) {
return originalPredicate.test(obj_) || disjunct_.test(obj_);
}
};
}
} // class Predicate
| 2,528
| 28.406977
| 85
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/Propagator.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Set;
public class Propagator<T> {
private final Set<T> marked;
private final Stack<T> worklist;
public Propagator(Set<T> marked, Stack<T> worklist) {
super();
this.marked = marked;
this.worklist = worklist;
}
public void prop(T val) {
if (marked.add(val)) {
worklist.push(val);
}
}
}
| 1,192
| 25.511111
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/Stack.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
/**
* @author manu_s
*
*/
public final class Stack<T> implements Cloneable {
private T[] elems;
private int size = 0;
@SuppressWarnings("unchecked")
public Stack(int numElems_) {
elems = (T[]) new Object[numElems_];
}
public Stack() {
this(4);
}
@SuppressWarnings("unchecked")
public void push(T obj_) {
assert obj_ != null;
if (size == elems.length) {
// lengthen array
Object[] tmp = elems;
elems = (T[]) new Object[tmp.length * 2];
System.arraycopy(tmp, 0, elems, 0, tmp.length);
}
elems[size] = obj_;
size++;
}
public void pushAll(Collection<T> c) {
for (T t : c) {
push(t);
}
}
public T pop() {
if (size == 0) {
return null;
}
size--;
T ret = elems[size];
elems[size] = null;
return ret;
}
public T peek() {
if (size == 0) {
return null;
}
return elems[size - 1];
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void clear() {
size = 0;
}
@SuppressWarnings("unchecked")
public Stack<T> clone() {
Stack<T> ret = null;
try {
ret = (Stack<T>) super.clone();
ret.elems = (T[]) new Object[elems.length];
System.arraycopy(elems, 0, ret.elems, 0, size);
return ret;
} catch (CloneNotSupportedException e) {
// should not happen
throw new InternalError();
}
}
public Object get(int i) {
return elems[i];
}
public boolean contains(Object o) {
return Util.arrayContains(elems, o, size);
}
/**
* returns first index
*
* @param o
* @return
*/
public int indexOf(T o) {
for (int i = 0; i < size && elems[i] != null; i++) {
if (elems[i].equals(o)) {
return i;
}
}
return -1;
}
public String toString() {
StringBuffer s = new StringBuffer();
s.append("[");
for (int i = 0; i < size && elems[i] != null; i++) {
if (i > 0) {
s.append(", ");
}
s.append(elems[i].toString());
}
s.append("]");
return s.toString();
}
}
| 2,996
| 19.8125
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/UnorderedPair.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class UnorderedPair<U, V> {
public U o1;
public V o2;
public UnorderedPair(U o1, V o2) {
this.o1 = o1;
this.o2 = o2;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (obj != null && obj.getClass() == UnorderedPair.class) {
UnorderedPair u = (UnorderedPair) obj;
return (u.o1.equals(o1) && u.o2.equals(o2)) || (u.o1.equals(o2) && u.o2.equals(o1));
}
return false;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return o1.hashCode() + o2.hashCode();
}
public String toString() {
return "{" + o1.toString() + ", " + o2.toString() + "}";
}
}
| 1,591
| 25.098361
| 90
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/genericutil/Util.java
|
package soot.jimple.spark.ondemand.genericutil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.security.Permission;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Miscellaneous utility functions.
*/
public class Util {
private static final Logger logger = LoggerFactory.getLogger(Util.class);
/** The empty {@link BitSet}. */
public static final BitSet EMPTY_BITSET = new BitSet();
/** Factorial */
public static long fact(long n_) {
long result = 1;
for (long i = 1; i <= n_; i++) {
result *= i;
}
return result;
}
/** Factorial */
public static BigInteger fact(BigInteger n_) {
BigInteger result = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(n_) <= 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(i);
}
return result;
}
/**
* Factorial on doubles; avoids overflow problems present when using integers.
*
* @param n_
* arg on which to compute factorial
* @return (<code>double</code> approximation to) factorial of largest positive integer <= (n_ + epsilon)
*/
public static double fact(double n_) {
n_ += 1e-6;
double result = 1.0;
for (double i = 1; i <= n_; i += 1.0) {
result *= i;
}
return result;
}
/** Factorial */
public static int fact(int n_) {
int result = 1;
for (int i = 1; i <= n_; i++) {
result *= i;
}
return result;
}
/** Binary log: finds the smallest power k such that 2^k>=n */
public static int binaryLogUp(int n_) {
int k = 0;
while ((1 << k) < n_) {
k++;
}
return k;
}
/** Binary log: finds the smallest power k such that 2^k>=n */
public static int binaryLogUp(long n_) {
int k = 0;
while ((1L << k) < n_) {
k++;
}
return k;
}
/** Convert an int[] to a {@link String} for printing */
public static String str(int[] ints_) {
StringBuffer s = new StringBuffer();
s.append("[");
for (int i = 0; i < ints_.length; i++) {
if (i > 0) {
s.append(", ");
}
s.append(ints_[i]);
}
s.append("]");
return s.toString();
}
public static String objArrayToString(Object[] o) {
return objArrayToString(o, "[", "]", ", ");
}
public static String objArrayToString(Object[] o, String start, String end, String sep) {
StringBuffer s = new StringBuffer();
s.append(start);
for (int i = 0; i < o.length; i++) {
if (o[i] != null) {
if (i > 0) {
s.append(sep);
}
s.append(o[i].toString());
}
}
s.append(end);
return s.toString();
}
/** Get a {@link String} representation of a {@link Throwable}. */
public static String str(Throwable thrown_) {
// create a memory buffer to which to dump the trace
ByteArrayOutputStream traceDump = new ByteArrayOutputStream();
PrintWriter w = new PrintWriter(traceDump);
logger.error(thrown_.getMessage(), thrown_);
w.close();
return traceDump.toString();
}
/**
* Test whether <em>some</em> element of the given {@link Collection} satisfies the given {@link Predicate}.
*/
public static <T> boolean forSome(Collection<T> c_, Predicate<T> p_) {
for (T t : c_) {
if (p_.test(t)) {
return true;
}
}
return false;
}
/**
* Test whether <em>some</em> element of the given {@link Collection} satisfies the given {@link Predicate}.
*
* @return The first element satisfying the predicate; otherwise null.
*/
public static <T> T find(Collection<T> c_, Predicate<T> p_) {
for (Iterator<T> iter = c_.iterator(); iter.hasNext();) {
T obj = iter.next();
if (p_.test(obj)) {
return obj;
}
}
return null;
}
/**
* Test whether <em>some</em> element of the given {@link Collection} satisfies the given {@link Predicate}.
*
* @return All the elements satisfying the predicate
*/
public static <T> Collection<T> findAll(Collection<T> c_, Predicate<T> p_) {
Collection<T> result = new LinkedList<T>();
for (Iterator<T> iter = c_.iterator(); iter.hasNext();) {
T obj = iter.next();
if (p_.test(obj)) {
result.add(obj);
}
}
return result;
}
/**
* Test whether <em>all</em> elements of the given {@link Collection} satisfy the given {@link Predicate}.
*/
public static <T> boolean forAll(Collection<T> c_, Predicate<T> p_) {
for (T t : c_) {
if (!p_.test(t)) {
return false;
}
}
return true;
}
/**
* Perform an action for all elements in a collection.
*
* @param c_
* the collection
* @param v_
* the visitor defining the action
*/
public static <T> void doForAll(Collection<T> c_, ObjectVisitor<T> v_) {
for (Iterator<T> iter = c_.iterator(); iter.hasNext();) {
v_.visit(iter.next());
}
}
/**
* Map a list: generate a new list with each element mapped. The new list is always an {@link ArrayList}; it would have
* been more precise to use {@link java.lang.reflect reflection} to create a list of the same type as 'srcList', but
* reflection works really slowly in some implementations, so it's best to avoid it.
*/
public static <T, U> List<U> map(List<T> srcList, Mapper<T, U> mapper_) {
ArrayList<U> result = new ArrayList<U>();
for (Iterator<T> srcIter = srcList.iterator(); srcIter.hasNext();) {
result.add(mapper_.map(srcIter.next()));
}
return result;
}
/**
* Filter a collection: generate a new list from an existing collection, consisting of the elements satisfying some
* predicate. The new list is always an {@link ArrayList}; it would have been more precise to use {@link java.lang.reflect
* reflection} to create a list of the same type as 'srcList', but reflection works really slowly in some implementations,
* so it's best to avoid it.
*/
public static <T> List<T> filter(Collection<T> src_, Predicate<T> pred_) {
ArrayList<T> result = new ArrayList<T>();
for (Iterator<T> srcIter = src_.iterator(); srcIter.hasNext();) {
T curElem = srcIter.next();
if (pred_.test(curElem)) {
result.add(curElem);
}
}
return result;
}
/**
* Filter a collection according to some predicate, placing the result in a List
*
* @param src_
* collection to be filtered
* @param pred_
* the predicate
* @param result_
* the list for the result. assumed to be empty
*/
public static <T> void filter(Collection<T> src_, Predicate<T> pred_, List<T> result_) {
for (T t : src_) {
if (pred_.test(t)) {
result_.add(t);
}
}
}
/**
* Map a set: generate a new set with each element mapped. The new set is always a {@link HashSet}; it would have been more
* precise to use {@link java.lang.reflect reflection} to create a set of the same type as 'srcSet', but reflection works
* really slowly in some implementations, so it's best to avoid it.
*/
public static <T, U> Set<U> mapToSet(Collection<T> srcSet, Mapper<T, U> mapper_) {
HashSet<U> result = new HashSet<U>();
for (Iterator<T> srcIter = srcSet.iterator(); srcIter.hasNext();) {
result.add(mapper_.map(srcIter.next()));
}
return result;
}
/*
* Grow an int[] -- i.e. allocate a new array of the given size, with the initial segment equal to this int[].
*/
public static int[] realloc(int[] data_, int newSize_) {
if (data_.length < newSize_) {
int[] newData = new int[newSize_];
System.arraycopy(data_, 0, newData, 0, data_.length);
return newData;
} else {
return data_;
}
}
/** Clear a {@link BitSet}. */
public static void clear(BitSet bitSet_) {
bitSet_.and(EMPTY_BITSET);
}
/** Replace all occurrences of a given substring in a given {@link String}. */
public static String replaceAll(String str_, String sub_, String newSub_) {
if (str_.indexOf(sub_) == -1) {
return str_;
}
int subLen = sub_.length();
int idx;
StringBuffer result = new StringBuffer(str_);
while ((idx = result.toString().indexOf(sub_)) >= 0) {
result.replace(idx, idx + subLen, newSub_);
}
return result.toString();
}
/** Remove all occurrences of a given substring in a given {@link String} */
public static String removeAll(String str_, String sub_) {
return replaceAll(str_, sub_, "");
}
/** Generate strings with fully qualified names or not */
public static final boolean FULLY_QUALIFIED_NAMES = false;
/** Write object fields to string */
public static String objectFieldsToString(Object obj) {
// Temporarily disable the security manager
SecurityManager oldsecurity = System.getSecurityManager();
System.setSecurityManager(new SecurityManager() {
public void checkPermission(Permission perm) {
}
});
Class c = obj.getClass();
StringBuffer buf = new StringBuffer(FULLY_QUALIFIED_NAMES ? c.getName() : removePackageName(c.getName()));
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
if (fields.length > 0) {
buf = buf.append(" (");
}
for (int i = 0; i < fields.length; i++) {
// Make this field accessible
fields[i].setAccessible(true);
try {
Class type = fields[i].getType();
String name = fields[i].getName();
Object value = fields[i].get(obj);
// name=value : type
buf = buf.append(name);
buf = buf.append("=");
buf = buf.append(value == null ? "null" : value.toString());
buf = buf.append(" : ");
buf = buf.append(FULLY_QUALIFIED_NAMES ? type.getName() : removePackageName(type.getName()));
} catch (IllegalAccessException e) {
logger.error(e.getMessage(), e);
}
buf = buf.append(i + 1 >= fields.length ? ")" : ",");
}
c = c.getSuperclass();
}
// Reinstate the security manager
System.setSecurityManager(oldsecurity);
return buf.toString();
}
/** Remove the package name from a fully qualified class name */
public static String removePackageName(String fully_qualified_name_) {
if (fully_qualified_name_ == null) {
return null;
}
int lastdot = fully_qualified_name_.lastIndexOf('.');
if (lastdot < 0) {
return "";
} else {
return fully_qualified_name_.substring(lastdot + 1);
}
}
/**
* @return
*/
public static int hashArray(Object[] objs) {
// stolen from java.util.AbstractList
int ret = 1;
for (int i = 0; i < objs.length; i++) {
ret = 31 * ret + (objs[i] == null ? 0 : objs[i].hashCode());
}
return ret;
}
public static boolean arrayContains(Object[] arr, Object obj, int size) {
assert obj != null;
for (int i = 0; i < size; i++) {
if (arr[i] != null && arr[i].equals(obj)) {
return true;
}
}
return false;
}
public static String toStringNull(Object o) {
return o == null ? "" : "[" + o.toString() + "]";
}
/**
* checks if two sets have a non-empty intersection
*
* @param s1
* @param s2
* @return <code>true</code> if the sets intersect; <code>false</code> otherwise
*/
public static <T> boolean intersecting(final Set<T> s1, final Set<T> s2) {
return forSome(s1, new Predicate<T>() {
public boolean test(T obj) {
return s2.contains(obj);
}
});
}
public static boolean stringContains(String str, String subStr) {
return str.indexOf(subStr) != -1;
}
public static int getInt(Integer i) {
return (i == null) ? 0 : i;
}
/**
* given the name of a class C, returns the name of the top-most enclosing class of class C. For example, given A$B$C, the
* method returns A
*
* @param typeStr
* @return
*/
public static String topLevelTypeString(String typeStr) {
int dollarIndex = typeStr.indexOf('$');
String topLevelTypeStr = dollarIndex == -1 ? typeStr : typeStr.substring(0, dollarIndex);
return topLevelTypeStr;
}
public static <T> void addIfNotNull(T val, Collection<T> vals) {
if (val != null) {
vals.add(val);
}
}
public static <T> List<T> pickNAtRandom(List<T> vals, int n, long seed) {
if (vals.size() <= n) {
return vals;
}
HashSet<T> elems = new HashSet<T>();
Random rand = new Random(seed);
for (int i = 0; i < n; i++) {
boolean added = true;
do {
int randIndex = rand.nextInt(n);
added = elems.add(vals.get(randIndex));
} while (!added);
}
return new ArrayList<T>(elems);
}
} // class Util
| 13,848
| 28.033543
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/pautil/AllocationSiteHandler.java
|
package soot.jimple.spark.ondemand.pautil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.Set;
import soot.AnySubType;
import soot.ArrayType;
import soot.RefType;
import soot.Scene;
import soot.SootMethod;
import soot.Type;
import soot.jimple.spark.internal.TypeManager;
import soot.jimple.spark.ondemand.genericutil.ImmutableStack;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.VirtualCalls;
/**
* Interface for handler for when an allocation site is encountered in a pointer analysis query.
*
* @author manu
*/
public interface AllocationSiteHandler {
/**
* handle a particular allocation site
*
* @param allocNode the abstract location node
* @param callStack for context-sensitive analysis, the call site; might be null
* @return true if analysis should be terminated; false otherwise
*/
public boolean handleAllocationSite(AllocNode allocNode, ImmutableStack<Integer> callStack);
public void resetState();
public static class PointsToSetHandler implements AllocationSiteHandler {
private PointsToSetInternal p2set;
/*
* (non-Javadoc)
*
* @see AAA.algs.AllocationSiteHandler#handleAllocationSite(soot.jimple.spark.pag.AllocNode, java.lang.Integer)
*/
public boolean handleAllocationSite(AllocNode allocNode, ImmutableStack<Integer> callStack) {
p2set.add(allocNode);
return false;
}
public PointsToSetInternal getP2set() {
return p2set;
}
public void setP2set(PointsToSetInternal p2set) {
this.p2set = p2set;
}
public void resetState() {
// TODO support this
throw new RuntimeException();
}
public boolean shouldHandle(VarNode dst) {
// TODO Auto-generated method stub
return false;
}
}
public static class CastCheckHandler implements AllocationSiteHandler {
private Type type;
private TypeManager manager;
private boolean castFailed = false;
/*
* (non-Javadoc)
*
* @see AAA.algs.AllocationSiteHandler#handleAllocationSite(soot.jimple.spark.pag.AllocNode, java.lang.Integer)
*/
public boolean handleAllocationSite(AllocNode allocNode, ImmutableStack<Integer> callStack) {
castFailed = !manager.castNeverFails(allocNode.getType(), type);
return castFailed;
}
public void setManager(TypeManager manager) {
this.manager = manager;
}
public void setType(Type type) {
this.type = type;
}
public void resetState() {
throw new RuntimeException();
}
public boolean shouldHandle(VarNode dst) {
// TODO Auto-generated method stub
P2SetVisitor v =
new P2SetVisitor() {
@Override
public void visit(Node n) {
if (!returnValue) {
returnValue = !manager.castNeverFails(n.getType(), type);
}
}
};
dst.getP2Set().forall(v);
return v.getReturnValue();
}
}
public static class VirtualCallHandler implements AllocationSiteHandler {
public PAG pag;
public Type receiverType;
public SootMethod callee;
public Set<SootMethod> possibleMethods = new HashSet<SootMethod>();
/**
* @param pag
* @param receiverType
*/
public VirtualCallHandler(PAG pag, Type receiverType, SootMethod callee) {
super();
this.pag = pag;
this.receiverType = receiverType;
this.callee = callee;
}
/*
* (non-Javadoc)
*
* @see AAA.algs.AllocationSiteHandler#handleAllocationSite(soot.jimple.spark.pag.AllocNode, AAA.algs.MethodContext)
*/
public boolean handleAllocationSite(AllocNode allocNode, ImmutableStack<Integer> callStack) {
Type type = allocNode.getType();
if (!pag.getTypeManager().castNeverFails(type, receiverType)) {
return false;
}
if (type instanceof AnySubType) {
AnySubType any = (AnySubType) type;
RefType refType = any.getBase();
if (pag.getTypeManager().getFastHierarchy().canStoreType(receiverType, refType)
|| pag.getTypeManager().getFastHierarchy().canStoreType(refType, receiverType)) {
return true;
}
return false;
}
if (type instanceof ArrayType) {
// we'll invoke the java.lang.Object method in this
// case
// Assert.chk(varNodeType.toString().equals("java.lang.Object"));
type = Scene.v().getSootClass("java.lang.Object").getType();
}
RefType refType = (RefType) type;
SootMethod targetMethod = null;
targetMethod = VirtualCalls.v().resolveNonSpecial(refType, callee.makeRef());
if (!possibleMethods.contains(targetMethod)) {
possibleMethods.add(targetMethod);
if (possibleMethods.size() > 1) {
return true;
}
}
return false;
}
public void resetState() {
possibleMethods.clear();
}
public boolean shouldHandle(VarNode dst) {
// TODO Auto-generated method stub
return false;
}
}
public boolean shouldHandle(VarNode dst);
}
| 6,097
| 27.900474
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/pautil/AssignEdge.java
|
package soot.jimple.spark.ondemand.pautil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.jimple.spark.pag.VarNode;
/**
* @author manu
*/
public final class AssignEdge {
private static final int PARAM_MASK = 0x00000001;
private static final int RETURN_MASK = 0x00000002;
private static final int CALL_MASK = PARAM_MASK | RETURN_MASK;
private Integer callSite = null;
private final VarNode src;
private int scratch;
private final VarNode dst;
/**
* @param from
* @param to
*/
public AssignEdge(final VarNode from, final VarNode to) {
this.src = from;
this.dst = to;
}
public boolean isParamEdge() {
return (scratch & PARAM_MASK) != 0;
}
public void setParamEdge() {
scratch |= PARAM_MASK;
}
public boolean isReturnEdge() {
return (scratch & RETURN_MASK) != 0;
}
public void setReturnEdge() {
scratch |= RETURN_MASK;
}
public boolean isCallEdge() {
return (scratch & CALL_MASK) != 0;
}
public void clearCallEdge() {
scratch = 0;
}
/**
* @return
*/
public Integer getCallSite() {
assert callSite != null : this + " is not a call edge!";
return callSite;
}
/**
* @param i
*/
public void setCallSite(Integer i) {
callSite = i;
}
public String toString() {
String ret = src + " -> " + dst;
if (isReturnEdge()) {
ret += "(* return" + callSite + " *)";
} else if (isParamEdge()) {
ret += "(* param" + callSite + " *)";
}
return ret;
}
public VarNode getSrc() {
return src;
}
public VarNode getDst() {
return dst;
}
}
| 2,370
| 19.982301
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/pautil/ContextSensitiveInfo.java
|
package soot.jimple.spark.ondemand.pautil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootMethod;
import soot.jimple.InvokeExpr;
import soot.jimple.spark.ondemand.genericutil.ArraySet;
import soot.jimple.spark.ondemand.genericutil.ArraySetMultiMap;
import soot.jimple.spark.pag.GlobalVarNode;
import soot.jimple.spark.pag.LocalVarNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.VarNode;
import soot.toolkits.scalar.Pair;
import soot.util.HashMultiMap;
/**
* Information for a context-sensitive analysis, eg. for call sites
*
* @author manu
*/
public class ContextSensitiveInfo {
private static final Logger logger = LoggerFactory.getLogger(ContextSensitiveInfo.class);
private static final boolean SKIP_STRING_NODES = false;
private static final boolean SKIP_EXCEPTION_NODES = false;
private static final boolean SKIP_THREAD_GLOBALS = false;
private static final boolean PRINT_CALL_SITE_INFO = false;
/**
* assignment edges, but properly handling multiple calls to a method VarNode -> ArraySet[AssignEdge]
*/
private final ArraySetMultiMap<VarNode, AssignEdge> contextSensitiveAssignEdges
= new ArraySetMultiMap<VarNode, AssignEdge>();
private final ArraySetMultiMap<VarNode, AssignEdge> contextSensitiveAssignBarEdges
= new ArraySetMultiMap<VarNode, AssignEdge>();
/**
* nodes in each method
*/
private final ArraySetMultiMap<SootMethod, VarNode> methodToNodes = new ArraySetMultiMap<SootMethod, VarNode>();
private final ArraySetMultiMap<SootMethod, VarNode> methodToOutPorts = new ArraySetMultiMap<SootMethod, VarNode>();
private final ArraySetMultiMap<SootMethod, VarNode> methodToInPorts = new ArraySetMultiMap<SootMethod, VarNode>();
private final ArraySetMultiMap<SootMethod, Integer> callSitesInMethod = new ArraySetMultiMap<SootMethod, Integer>();
private final ArraySetMultiMap<SootMethod, Integer> callSitesInvokingMethod = new ArraySetMultiMap<SootMethod, Integer>();
private final ArraySetMultiMap<Integer, SootMethod> callSiteToTargets = new ArraySetMultiMap<Integer, SootMethod>();
private final ArraySetMultiMap<Integer, AssignEdge> callSiteToEdges = new ArraySetMultiMap<Integer, AssignEdge>();
private final Map<Integer, LocalVarNode> virtCallSiteToReceiver = new HashMap<Integer, LocalVarNode>();
private final Map<Integer, SootMethod> callSiteToInvokedMethod = new HashMap<Integer, SootMethod>();
private final Map<Integer, SootMethod> callSiteToInvokingMethod = new HashMap<Integer, SootMethod>();
private final ArraySetMultiMap<LocalVarNode, Integer> receiverToVirtCallSites
= new ArraySetMultiMap<LocalVarNode, Integer>();
/**
*
*/
public ContextSensitiveInfo(PAG pag) {
// set up method to node map
for (Iterator iter = pag.getVarNodeNumberer().iterator(); iter.hasNext();) {
VarNode varNode = (VarNode) iter.next();
if (varNode instanceof LocalVarNode) {
LocalVarNode local = (LocalVarNode) varNode;
SootMethod method = local.getMethod();
assert method != null : local;
methodToNodes.put(method, local);
if (SootUtil.isRetNode(local)) {
methodToOutPorts.put(method, local);
}
if (SootUtil.isParamNode(local)) {
methodToInPorts.put(method, local);
}
}
}
int callSiteNum = 0;
// first, add regular assigns
Set assignSources = pag.simpleSources();
for (Iterator iter = assignSources.iterator(); iter.hasNext();) {
VarNode assignSource = (VarNode) iter.next();
if (skipNode(assignSource)) {
continue;
}
boolean sourceGlobal = assignSource instanceof GlobalVarNode;
Node[] assignTargets = pag.simpleLookup(assignSource);
for (int i = 0; i < assignTargets.length; i++) {
VarNode assignTarget = (VarNode) assignTargets[i];
if (skipNode(assignTarget)) {
continue;
}
boolean isFinalizerNode = false;
if (assignTarget instanceof LocalVarNode) {
LocalVarNode local = (LocalVarNode) assignTarget;
SootMethod method = local.getMethod();
if (method.toString().indexOf("finalize()") != -1 && SootUtil.isThisNode(local)) {
isFinalizerNode = true;
}
}
boolean targetGlobal = assignTarget instanceof GlobalVarNode;
AssignEdge assignEdge = new AssignEdge(assignSource, assignTarget);
// handle weird finalizers
if (isFinalizerNode) {
assignEdge.setParamEdge();
Integer callSite = new Integer(callSiteNum++);
assignEdge.setCallSite(callSite);
}
addAssignEdge(assignEdge);
if (sourceGlobal) {
if (targetGlobal) {
// System.err.println("G2G " + assignSource + " --> "
// + assignTarget);
} else {
SootMethod method = ((LocalVarNode) assignTarget).getMethod();
// don't want to include things assigned something that
// is already an in port
if (!methodToInPorts.get(method).contains(assignTarget)) {
methodToInPorts.put(method, assignSource);
}
}
} else {
if (targetGlobal) {
SootMethod method = ((LocalVarNode) assignSource).getMethod();
// don't want to include things assigned from something
// that
// is already an out port
if (!methodToOutPorts.get(method).contains(assignSource)) {
methodToOutPorts.put(method, assignTarget);
}
}
}
}
}
// now handle calls
HashMultiMap callAssigns = pag.callAssigns;
PrintWriter callSiteWriter = null;
if (PRINT_CALL_SITE_INFO) {
try {
callSiteWriter = new PrintWriter(new FileWriter("callSiteInfo"), true);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
for (Iterator iter = callAssigns.keySet().iterator(); iter.hasNext();) {
InvokeExpr ie = (InvokeExpr) iter.next();
Integer callSite = new Integer(callSiteNum++);
callSiteToInvokedMethod.put(callSite, ie.getMethod());
SootMethod invokingMethod = pag.callToMethod.get(ie);
callSiteToInvokingMethod.put(callSite, invokingMethod);
if (PRINT_CALL_SITE_INFO) {
callSiteWriter.println(callSite + " " + callSiteToInvokingMethod.get(callSite) + " " + ie);
}
if (pag.virtualCallsToReceivers.containsKey(ie)) {
LocalVarNode receiver = (LocalVarNode) pag.virtualCallsToReceivers.get(ie);
assert receiver != null;
virtCallSiteToReceiver.put(callSite, receiver);
receiverToVirtCallSites.put(receiver, callSite);
}
Set curEdges = callAssigns.get(ie);
for (Iterator iterator = curEdges.iterator(); iterator.hasNext();) {
Pair callAssign = (Pair) iterator.next();
// for reflective calls, the "O1" value can actually be a FieldRefNode
// we simply ignore such cases here (appears to be sound)
if (!(callAssign.getO1() instanceof VarNode)) {
continue;
}
VarNode src = (VarNode) callAssign.getO1();
VarNode dst = (VarNode) callAssign.getO2();
if (skipNode(src)) {
continue;
}
ArraySet edges = getAssignBarEdges(src);
AssignEdge edge = null;
for (int i = 0; i < edges.size() && edge == null; i++) {
AssignEdge curEdge = (AssignEdge) edges.get(i);
if (curEdge.getDst() == dst) {
edge = curEdge;
}
}
assert edge != null : "no edge from " + src + " to " + dst;
boolean edgeFromOtherCallSite = edge.isCallEdge();
if (edgeFromOtherCallSite) {
edge = new AssignEdge(src, dst);
}
edge.setCallSite(callSite);
callSiteToEdges.put(callSite, edge);
if (SootUtil.isParamNode(dst)) {
// assert src instanceof LocalVarNode : src + " " + dst;
edge.setParamEdge();
SootMethod invokedMethod = ((LocalVarNode) dst).getMethod();
callSiteToTargets.put(callSite, invokedMethod);
callSitesInvokingMethod.put(invokedMethod, callSite);
// assert src instanceof LocalVarNode : src + " NOT LOCAL";
if (src instanceof LocalVarNode) {
callSitesInMethod.put(((LocalVarNode) src).getMethod(), callSite);
}
} else if (SootUtil.isRetNode(src)) {
edge.setReturnEdge();
SootMethod invokedMethod = ((LocalVarNode) src).getMethod();
callSiteToTargets.put(callSite, invokedMethod);
callSitesInvokingMethod.put(invokedMethod, callSite);
if (dst instanceof LocalVarNode) {
callSitesInMethod.put(((LocalVarNode) dst).getMethod(), callSite);
}
} else {
assert false : "weird call edge " + callAssign;
}
if (edgeFromOtherCallSite) {
addAssignEdge(edge);
}
}
}
// System.err.println(callSiteNum + " call sites");
assert callEdgesReasonable();
if (PRINT_CALL_SITE_INFO) {
callSiteWriter.close();
}
// assert assignEdgesWellFormed(pag) == null :
// assignEdgesWellFormed(pag);
}
private boolean callEdgesReasonable() {
Set<VarNode> vars = contextSensitiveAssignEdges.keySet();
for (VarNode node : vars) {
ArraySet<AssignEdge> assigns = contextSensitiveAssignEdges.get(node);
for (AssignEdge edge : assigns) {
if (edge.isCallEdge()) {
if (edge.getCallSite() == null) {
logger.debug("" + edge + " is weird!!");
return false;
}
}
}
}
return true;
}
@SuppressWarnings("unused")
private String assignEdgesWellFormed(PAG pag) {
for (Iterator iter = pag.getVarNodeNumberer().iterator(); iter.hasNext();) {
VarNode v = (VarNode) iter.next();
Set<AssignEdge> outgoingAssigns = getAssignBarEdges(v);
for (AssignEdge edge : outgoingAssigns) {
if (edge.getSrc() != v) {
return edge + " src should be " + v;
}
}
Set<AssignEdge> incomingAssigns = getAssignEdges(v);
for (AssignEdge edge : incomingAssigns) {
if (edge.getDst() != v) {
return edge + " dst should be " + v;
}
}
}
return null;
}
/**
* @param node
* @return
*/
private boolean skipNode(VarNode node) {
return (SKIP_STRING_NODES && SootUtil.isStringNode(node)) || (SKIP_EXCEPTION_NODES && SootUtil.isExceptionNode(node))
|| (SKIP_THREAD_GLOBALS && SootUtil.isThreadGlobal(node));
}
/**
* @param assignSource
* @param assignTarget
*/
private void addAssignEdge(AssignEdge assignEdge) {
contextSensitiveAssignEdges.put(assignEdge.getSrc(), assignEdge);
contextSensitiveAssignBarEdges.put(assignEdge.getDst(), assignEdge);
}
public ArraySet<AssignEdge> getAssignBarEdges(VarNode node) {
return contextSensitiveAssignEdges.get(node);
}
/**
*
* @param node
* @return edges capturing assign flow <em>into</em> node
*/
public ArraySet<AssignEdge> getAssignEdges(VarNode node) {
return contextSensitiveAssignBarEdges.get(node);
}
public Set<SootMethod> methods() {
return methodToNodes.keySet();
}
public ArraySet<VarNode> getNodesForMethod(SootMethod method) {
return methodToNodes.get(method);
}
public ArraySet<VarNode> getInPortsForMethod(SootMethod method) {
return methodToInPorts.get(method);
}
public ArraySet<VarNode> getOutPortsForMethod(SootMethod method) {
return methodToOutPorts.get(method);
}
/**
* @param method
* @return
*/
public ArraySet<Integer> getCallSitesInMethod(SootMethod method) {
return callSitesInMethod.get(method);
}
public Set<Integer> getCallSitesInvokingMethod(SootMethod method) {
return callSitesInvokingMethod.get(method);
}
public ArraySet<AssignEdge> getCallSiteEdges(Integer callSite) {
return callSiteToEdges.get(callSite);
}
public ArraySet<SootMethod> getCallSiteTargets(Integer callSite) {
return callSiteToTargets.get(callSite);
}
public LocalVarNode getReceiverForVirtCallSite(Integer callSite) {
LocalVarNode ret = virtCallSiteToReceiver.get(callSite);
assert ret != null;
return ret;
}
public Set<Integer> getVirtCallSitesForReceiver(LocalVarNode receiver) {
return receiverToVirtCallSites.get(receiver);
}
public SootMethod getInvokedMethod(Integer callSite) {
return callSiteToInvokedMethod.get(callSite);
}
public SootMethod getInvokingMethod(Integer callSite) {
return callSiteToInvokingMethod.get(callSite);
}
public boolean isVirtCall(Integer callSite) {
return virtCallSiteToReceiver.containsKey(callSite);
}
}
| 13,847
| 34.41688
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/pautil/DumpNumAppReachableMethods.java
|
package soot.jimple.spark.ondemand.pautil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.PackManager;
import soot.Scene;
import soot.SceneTransformer;
import soot.SootMethod;
import soot.Transform;
public class DumpNumAppReachableMethods extends SceneTransformer {
private static final Logger logger = LoggerFactory.getLogger(DumpNumAppReachableMethods.class);
protected void internalTransform(String phaseName, Map options) {
int numAppMethods = 0;
for (Iterator mIt = Scene.v().getReachableMethods().listener(); mIt.hasNext();) {
final SootMethod m = (SootMethod) mIt.next();
if (isAppMethod(m)) {
// System.out.println(m);
// assert OnFlyCallGraphBuilder.processedMethods.contains(m) : m
// + " not processed!!";
numAppMethods++;
}
}
logger.debug("Number of reachable methods in application: " + numAppMethods);
}
private boolean isAppMethod(final SootMethod m) {
return !SootUtil.inLibrary(m.getDeclaringClass().getName());
}
/**
* @param args
*/
public static void main(String[] args) {
PackManager.v().getPack("wjtp").add(new Transform("wjtp.narm", new DumpNumAppReachableMethods()));
soot.Main.main(args);
}
}
| 2,098
| 29.42029
| 102
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/pautil/OTFMethodSCCManager.java
|
package soot.jimple.spark.ondemand.pautil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Set;
import soot.Scene;
import soot.SootMethod;
import soot.jimple.spark.ondemand.genericutil.DisjointSets;
public final class OTFMethodSCCManager {
private DisjointSets disj;
public OTFMethodSCCManager() {
int size = Scene.v().getMethodNumberer().size();
disj = new DisjointSets(size + 1);
}
public boolean inSameSCC(SootMethod m1, SootMethod m2) {
return disj.find(m1.getNumber()) == disj.find(m2.getNumber());
}
public void makeSameSCC(Set<SootMethod> methods) {
SootMethod prevMethod = null;
for (SootMethod method : methods) {
if (prevMethod != null) {
int prevMethodRep = disj.find(prevMethod.getNumber());
int methodRep = disj.find(method.getNumber());
if (prevMethodRep != methodRep) {
disj.union(prevMethodRep, methodRep);
}
}
prevMethod = method;
}
}
}
| 1,727
| 28.793103
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/pautil/SootUtil.java
|
package soot.jimple.spark.ondemand.pautil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.CompilationDeathException;
import soot.PointsToAnalysis;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.jimple.spark.ondemand.genericutil.ArraySet;
import soot.jimple.spark.ondemand.genericutil.ArraySetMultiMap;
import soot.jimple.spark.ondemand.genericutil.ImmutableStack;
import soot.jimple.spark.ondemand.genericutil.Predicate;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.GlobalVarNode;
import soot.jimple.spark.pag.LocalVarNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.Parm;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.StringConstantNode;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.DoublePointsToSet;
import soot.jimple.spark.sets.HybridPointsToSet;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.VirtualCalls;
import soot.options.Options;
import soot.toolkits.scalar.Pair;
import soot.util.Chain;
import soot.util.queue.ChunkedQueue;
/**
* Utility methods for dealing with Soot.
*
* @author manu_s
*
*/
public class SootUtil {
private static final Logger logger = LoggerFactory.getLogger(SootUtil.class);
public final static class CallSiteAndContext extends Pair<Integer, ImmutableStack<Integer>> {
public CallSiteAndContext(Integer callSite, ImmutableStack<Integer> callingContext) {
super(callSite, callingContext);
}
}
public static final class FieldAccessMap extends ArraySetMultiMap<SparkField, Pair<FieldRefNode, LocalVarNode>> {
}
public static FieldAccessMap buildStoreMap(PAG pag) {
FieldAccessMap ret = new FieldAccessMap();
Iterator frNodeIter = pag.storeInvSourcesIterator();
while (frNodeIter.hasNext()) {
FieldRefNode frNode = (FieldRefNode) frNodeIter.next();
SparkField field = frNode.getField();
Node[] targets = pag.storeInvLookup(frNode);
for (int i = 0; i < targets.length; i++) {
VarNode target = (VarNode) targets[i];
if (target instanceof GlobalVarNode) {
continue;
}
ret.put(field, new Pair<FieldRefNode, LocalVarNode>(frNode, (LocalVarNode) target));
}
}
return ret;
}
/**
*
* @param node
* @return <code>true</code> if <code>node</code> represents the return value of a method; <code>false</code> otherwise
*/
public static boolean isRetNode(VarNode node) {
if (node.getVariable() instanceof Parm) {
Parm parm = (Parm) node.getVariable();
return (parm.getIndex() == PointsToAnalysis.RETURN_NODE);
}
return false;
}
public static boolean isParamNode(VarNode node) {
if (node.getVariable() instanceof soot.toolkits.scalar.Pair) {
soot.toolkits.scalar.Pair pair = (soot.toolkits.scalar.Pair) node.getVariable();
return (pair.getO1() instanceof SootMethod
&& (pair.getO2() instanceof Integer || pair.getO2() == PointsToAnalysis.THIS_NODE));
}
return false;
}
/**
*
* @param node
* @return <code>true</code> if <code>node</code> represents the this parameter of a method; <code>false</code> otherwise
*/
public static boolean isThisNode(VarNode node) {
if (node.getVariable() instanceof soot.toolkits.scalar.Pair) {
soot.toolkits.scalar.Pair pair = (soot.toolkits.scalar.Pair) node.getVariable();
return (pair.getO1() instanceof SootMethod) && (pair.getO2() == PointsToAnalysis.THIS_NODE);
}
return false;
}
private static final String[] lib13Packages = { "java.applet", "java.awt", "java.awt.color", "java.awt.datatransfer",
"java.awt.dnd", "java.awt.dnd.peer", "java.awt.event", "java.awt.font", "java.awt.geom", "java.awt.im",
"java.awt.im.spi", "java.awt.image", "java.awt.image.renderable", "java.awt.peer", "java.awt.print", "java.beans",
"java.beans.beancontext", "java.io", "java.lang", "java.lang.ref", "java.lang.reflect", "java.math", "java.net",
"java.rmi", "java.rmi.activation", "java.rmi.dgc", "java.rmi.registry", "java.rmi.server", "java.security",
"java.security.acl", "java.security.cert", "java.security.interfaces", "java.security.spec", "java.sql", "java.text",
"java.text.resources", "java.util", "java.util.jar", "java.util.zip", "javax.accessibility", "javax.naming",
"javax.naming.directory", "javax.naming.event", "javax.naming.ldap", "javax.naming.spi", "javax.rmi",
"javax.rmi.CORBA", "javax.sound.midi", "javax.sound.midi.spi", "javax.sound.sampled", "javax.sound.sampled.spi",
"javax.swing", "javax.swing.border", "javax.swing.colorchooser", "javax.swing.event", "javax.swing.filechooser",
"javax.swing.plaf", "javax.swing.plaf.basic", "javax.swing.plaf.metal", "javax.swing.plaf.multi", "javax.swing.table",
"javax.swing.text", "javax.swing.text.html", "javax.swing.text.html.parser", "javax.swing.text.rtf",
"javax.swing.tree", "javax.swing.undo", "javax.transaction", "org.omg.CORBA", "org.omg.CORBA.DynAnyPackage",
"org.omg.CORBA.ORBPackage", "org.omg.CORBA.TypeCodePackage", "org.omg.CORBA.portable", "org.omg.CORBA_2_3",
"org.omg.CORBA_2_3.portable", "org.omg.CosNaming", "org.omg.CosNaming.NamingContextPackage", "org.omg.SendingContext",
"org.omg.stub.java.rmi", "sun.applet", "sun.applet.resources", "sun.audio", "sun.awt", "sun.awt.color", "sun.awt.dnd",
"sun.awt.font", "sun.awt.geom", "sun.awt.im", "sun.awt.image", "sun.awt.image.codec", "sun.awt.motif", "sun.awt.print",
"sun.beans.editors", "sun.beans.infos", "sun.dc.path", "sun.dc.pr", "sun.io", "sun.java2d", "sun.java2d.loops",
"sun.java2d.pipe", "sun.jdbc.odbc", "sun.misc", "sun.net", "sun.net.ftp", "sun.net.nntp", "sun.net.smtp",
"sun.net.www", "sun.net.www.content.audio", "sun.net.www.content.image", "sun.net.www.content.text",
"sun.net.www.http", "sun.net.www.protocol.doc", "sun.net.www.protocol.file", "sun.net.www.protocol.ftp",
"sun.net.www.protocol.gopher", "sun.net.www.protocol.http", "sun.net.www.protocol.jar", "sun.net.www.protocol.mailto",
"sun.net.www.protocol.netdoc", "sun.net.www.protocol.systemresource", "sun.net.www.protocol.verbatim", "sun.rmi.log",
"sun.rmi.registry", "sun.rmi.server", "sun.rmi.transport", "sun.rmi.transport.proxy", "sun.rmi.transport.tcp",
"sun.security.acl", "sun.security.action", "sun.security.pkcs", "sun.security.provider", "sun.security.tools",
"sun.security.util", "sun.security.x509", "sun.tools.jar", "sun.tools.util", "sunw.io", "sunw.util",
"com.sun.corba.se.internal.CosNaming", "com.sun.corba.se.internal.corba", "com.sun.corba.se.internal.core",
"com.sun.corba.se.internal.iiop", "com.sun.corba.se.internal.io", "com.sun.corba.se.internal.io.lang",
"com.sun.corba.se.internal.io.util", "com.sun.corba.se.internal.javax.rmi",
"com.sun.corba.se.internal.javax.rmi.CORBA", "com.sun.corba.se.internal.orbutil", "com.sun.corba.se.internal.util",
"com.sun.image.codec.jpeg", "com.sun.java.swing.plaf.motif", "com.sun.java.swing.plaf.windows",
"com.sun.jndi.cosnaming", "com.sun.jndi.ldap", "com.sun.jndi.rmi.registry", "com.sun.jndi.toolkit.corba",
"com.sun.jndi.toolkit.ctx", "com.sun.jndi.toolkit.dir", "com.sun.jndi.toolkit.url", "com.sun.jndi.url.iiop",
"com.sun.jndi.url.iiopname", "com.sun.jndi.url.ldap", "com.sun.jndi.url.rmi", "com.sun.media.sound",
"com.sun.naming.internal", "com.sun.org.omg.CORBA", "com.sun.org.omg.CORBA.ValueDefPackage",
"com.sun.org.omg.CORBA.portable", "com.sun.org.omg.SendingContext", "com.sun.org.omg.SendingContext.CodeBasePackage",
"com.sun.rmi.rmid", "com.sun.rsajca", "com.sun.rsasign" };
/**
* @param outerType
* @return
*/
public static boolean inLibrary(String className) {
for (int i = 0; i < lib13Packages.length; i++) {
String libPackage = lib13Packages[i];
if (className.startsWith(libPackage)) {
return true;
}
}
return false;
}
public static boolean inLibrary(RefType type) {
return inLibrary(type.getClassName());
}
public static boolean isStringNode(VarNode node) {
if (node instanceof GlobalVarNode) {
GlobalVarNode global = (GlobalVarNode) node;
if (global.getVariable() instanceof AllocNode) {
AllocNode alloc = (AllocNode) global.getVariable();
return alloc.getNewExpr() == PointsToAnalysis.STRING_NODE || alloc instanceof StringConstantNode;
}
}
return false;
}
/**
* @param node
* @return
*/
public static boolean isExceptionNode(VarNode node) {
if (node instanceof GlobalVarNode) {
GlobalVarNode global = (GlobalVarNode) node;
return global.getVariable() == PointsToAnalysis.EXCEPTION_NODE;
}
return false;
}
public static final class FieldToEdgesMap extends ArraySetMultiMap<SparkField, Pair<VarNode, VarNode>> {
}
public static FieldToEdgesMap storesOnField(PAG pag) {
FieldToEdgesMap storesOnField = new FieldToEdgesMap();
Iterator frNodeIter = pag.storeInvSourcesIterator();
while (frNodeIter.hasNext()) {
FieldRefNode frNode = (FieldRefNode) frNodeIter.next();
VarNode source = frNode.getBase();
SparkField field = frNode.getField();
Node[] targets = pag.storeInvLookup(frNode);
for (int i = 0; i < targets.length; i++) {
VarNode target = (VarNode) targets[i];
storesOnField.put(field, new Pair<VarNode, VarNode>(target, source));
}
}
return storesOnField;
}
public static FieldToEdgesMap loadsOnField(PAG pag) {
FieldToEdgesMap loadsOnField = new FieldToEdgesMap();
Iterator frNodeIter = pag.loadSourcesIterator();
while (frNodeIter.hasNext()) {
FieldRefNode frNode = (FieldRefNode) frNodeIter.next();
VarNode source = frNode.getBase();
SparkField field = frNode.getField();
Node[] targets = pag.loadLookup(frNode);
for (int i = 0; i < targets.length; i++) {
VarNode target = (VarNode) targets[i];
loadsOnField.put(field, new Pair<VarNode, VarNode>(target, source));
}
}
return loadsOnField;
}
public static PointsToSetInternal constructIntersection(final PointsToSetInternal set1, final PointsToSetInternal set2,
PAG pag) {
HybridPointsToSet hybridSet1 = null, hybridSet2 = null;
hybridSet1 = convertToHybrid(set1);
hybridSet2 = convertToHybrid(set2);
HybridPointsToSet intersection = HybridPointsToSet.intersection(hybridSet1, hybridSet2, pag);
// checkSetsEqual(intersection, set1, set2, pag);
return intersection;
}
@SuppressWarnings("unused")
private static void checkSetsEqual(final HybridPointsToSet intersection, final PointsToSetInternal set1,
final PointsToSetInternal set2, PAG pag) {
final PointsToSetInternal ret = HybridPointsToSet.getFactory().newSet(Scene.v().getObjectType(), pag);
set1.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (set2.contains(n)) {
ret.add(n);
}
}
});
ret.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
// TODO Auto-generated method stub
if (!intersection.contains(n)) {
logger.debug("" + n + " missing from intersection");
logger.debug("" + set1);
logger.debug("" + set2);
logger.debug("" + intersection);
logger.debug("" + ret);
throw new RuntimeException("intersection too small");
}
}
});
intersection.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
// TODO Auto-generated method stub
if (!ret.contains(n)) {
logger.debug("" + n + " missing from ret");
logger.debug("" + set1);
logger.debug("" + set2);
logger.debug("" + intersection);
logger.debug("" + ret);
throw new RuntimeException("old way too small???");
}
}
});
}
private static HybridPointsToSet convertToHybrid(final PointsToSetInternal set) {
HybridPointsToSet ret = null;
if (set instanceof HybridPointsToSet) {
ret = (HybridPointsToSet) set;
} else if (set instanceof DoublePointsToSet) {
assert ((DoublePointsToSet) set).getNewSet().isEmpty();
ret = (HybridPointsToSet) ((DoublePointsToSet) set).getOldSet();
}
return ret;
}
public static boolean isThreadGlobal(VarNode node) {
if (node instanceof GlobalVarNode) {
GlobalVarNode global = (GlobalVarNode) node;
return global.getVariable() == PointsToAnalysis.MAIN_THREAD_GROUP_NODE_LOCAL;
}
return false;
}
// private static final NumberedString sigStart =
// Scene.v().getSubSigNumberer().
// findOrAdd( "void start()" );
public static boolean isThreadStartMethod(SootMethod method) {
return method.toString().equals("<java.lang.Thread: void start()>");
}
public static boolean hasRecursiveField(SootClass sootClass) {
Chain fields = sootClass.getFields();
for (Iterator iter = fields.iterator(); iter.hasNext();) {
SootField sootField = (SootField) iter.next();
Type type = sootField.getType();
if (type instanceof RefType) {
RefType refType = (RefType) type;
SootClass sootClass2 = refType.getSootClass();
if (sootClass == sootClass2) {
return true;
}
}
}
return false;
}
public static void dumpVarNodeInfo(final PAG pag) {
PrintWriter varNodeWriter = null;
try {
varNodeWriter = new PrintWriter(new BufferedWriter(new FileWriter("varNodeInfo")));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
for (Iterator iter = pag.getVarNodeNumberer().iterator(); iter.hasNext();) {
VarNode varNode = (VarNode) iter.next();
varNodeWriter.println(varNode.getNumber() + " " + varNode);
}
varNodeWriter.flush();
varNodeWriter.close();
}
@SuppressWarnings("unchecked")
public static boolean noRefTypeParameters(SootMethod method) {
if (!method.isStatic()) {
return false;
}
Predicate<Type> notRefTypePred = new Predicate<Type>() {
@Override
public boolean test(Type obj_) {
return !(obj_ instanceof RefType) && !(obj_ instanceof ArrayType);
}
};
return notRefTypePred.test(method.getReturnType())
&& soot.jimple.spark.ondemand.genericutil.Util.forAll(method.getParameterTypes(), notRefTypePred);
}
public static SootMethod getMainMethod() {
return Scene.v().getMainClass().getMethod(Scene.v().getSubSigNumberer().findOrAdd("void main(java.lang.String[])"));
}
public static boolean isResolvableCall(SootMethod invokedMethod) {
// TODO make calls through invokespecial resolvable
if (invokedMethod.isStatic()) {
return true;
}
if (isConstructor(invokedMethod)) {
return true;
}
return false;
}
public static Collection<? extends SootMethod> getCallTargets(Type type, SootMethod invokedMethod) {
if (isConstructor(invokedMethod)) {
return Collections.singleton(invokedMethod);
}
Type receiverType = invokedMethod.getDeclaringClass().getType();
ChunkedQueue chunkedQueue = new ChunkedQueue();
Iterator iter = chunkedQueue.reader();
VirtualCalls.v().resolve(type, receiverType, invokedMethod.makeRef(), null, chunkedQueue);
Set<SootMethod> ret = new ArraySet<SootMethod>();
for (; iter.hasNext();) {
SootMethod target = (SootMethod) iter.next();
ret.add(target);
}
return ret;
}
private static boolean isConstructor(SootMethod invokedMethod) {
return invokedMethod.getName().equals("<init>");
}
public static String createDirIfNotExist(String dirName) {
File dir = new File(dirName);
if (!dir.exists()) {
try {
if (!Options.v().output_jar()) {
dir.mkdirs();
}
} catch (SecurityException se) {
logger.debug("Unable to create " + dirName);
throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED);
}
}
return dirName;
}
public static long getFreeLiveMemory() {
Runtime r = Runtime.getRuntime();
r.gc();
return r.freeMemory();
}
public static void printNodeNumberMapping(String fileName, PAG pag) {
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
for (Iterator iter = pag.getVarNodeNumberer().iterator(); iter.hasNext();) {
VarNode vn = (VarNode) iter.next();
pw.println(vn.getNumber() + "\t" + vn);
}
pw.close();
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
}
}
public static SootMethod getAmbiguousMethodByName(String methodName) {
SootClass sc = Scene.v().tryLoadClass(getClassName(methodName), SootClass.SIGNATURES);
SootMethod sm = sc.getMethodByName(getMethodName(methodName));
return sm;
}
/**
* This method should be removed soon.
*
* @param qualifiedName
* @return
*/
public static String fakeSignature(String qualifiedName) {
String cname = qualifiedName.substring(0, qualifiedName.lastIndexOf('.'));
String mname = qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1, qualifiedName.length());
return "<" + cname + ": " + mname + ">";
}
public static String getClassName(String qualifiedName) {
return qualifiedName.substring(0, qualifiedName.lastIndexOf('.'));
}
public static String getMethodName(String qualifiedName) {
return qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1, qualifiedName.length());
}
public static boolean isNewInstanceMethod(SootMethod method) {
return method.toString().equals("<java.lang.Class: java.lang.Object newInstance()>");
}
}
| 19,220
| 37.212724
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/ondemand/pautil/ValidMatches.java
|
package soot.jimple.spark.ondemand.pautil;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Set;
import soot.jimple.spark.ondemand.genericutil.ArraySet;
import soot.jimple.spark.ondemand.genericutil.HashSetMultiMap;
import soot.jimple.spark.ondemand.genericutil.MultiMap;
import soot.jimple.spark.ondemand.pautil.SootUtil.FieldToEdgesMap;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.toolkits.scalar.Pair;
public class ValidMatches {
// edges are in same direction as PAG, in the direction of value flow
private final MultiMap<VarNode, VarNode> vMatchEdges = new HashSetMultiMap<VarNode, VarNode>();
private final MultiMap<VarNode, VarNode> vMatchBarEdges = new HashSetMultiMap<VarNode, VarNode>();
public ValidMatches(PAG pag, FieldToEdgesMap fieldToStores) {
for (Iterator iter = pag.loadSources().iterator(); iter.hasNext();) {
FieldRefNode loadSource = (FieldRefNode) iter.next();
SparkField field = loadSource.getField();
VarNode loadBase = loadSource.getBase();
ArraySet<Pair<VarNode, VarNode>> storesOnField = fieldToStores.get(field);
for (Pair<VarNode, VarNode> store : storesOnField) {
VarNode storeBase = store.getO2();
if (loadBase.getP2Set().hasNonEmptyIntersection(storeBase.getP2Set())) {
VarNode matchSrc = store.getO1();
Node[] loadTargets = pag.loadLookup(loadSource);
for (int i = 0; i < loadTargets.length; i++) {
VarNode matchTgt = (VarNode) loadTargets[i];
vMatchEdges.put(matchSrc, matchTgt);
vMatchBarEdges.put(matchTgt, matchSrc);
}
}
}
}
}
public Set<VarNode> vMatchLookup(VarNode src) {
return vMatchEdges.get(src);
}
public Set<VarNode> vMatchInvLookup(VarNode src) {
return vMatchBarEdges.get(src);
}
}
| 2,762
| 35.84
| 100
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/AllocDotField.java
|
package soot.jimple.spark.pag;
/*-
* #%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%
*/
/**
* Represents an alloc-site-dot-field node (Yellow) in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public class AllocDotField extends Node {
/** Returns the base AllocNode. */
public AllocNode getBase() {
return base;
}
/** Returns the field of this node. */
public SparkField getField() {
return field;
}
public String toString() {
return "AllocDotField " + getNumber() + " " + base + "." + field;
}
/* End of public methods. */
AllocDotField(PAG pag, AllocNode base, SparkField field) {
super(pag, null);
if (field == null) {
throw new RuntimeException("null field");
}
this.base = base;
this.field = field;
base.addField(this, field);
pag.getAllocDotFieldNodeNumberer().add(this);
}
/* End of package methods. */
protected AllocNode base;
protected SparkField field;
}
| 1,705
| 26.079365
| 84
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/AllocNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import soot.Context;
import soot.PhaseOptions;
import soot.RefType;
import soot.SootMethod;
import soot.Type;
import soot.options.CGOptions;
/**
* Represents an allocation site node (Blue) in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public class AllocNode extends Node implements Context {
/** Returns the new expression of this allocation site. */
public Object getNewExpr() {
return newExpr;
}
/** Returns all field ref nodes having this node as their base. */
public Collection<AllocDotField> getAllFieldRefs() {
if (fields == null) {
return Collections.emptySet();
}
return fields.values();
}
/**
* Returns the field ref node having this node as its base, and field as its field; null if nonexistent.
*/
public AllocDotField dot(SparkField field) {
return fields == null ? null : fields.get(field);
}
public String toString() {
return "AllocNode " + getNumber() + " " + newExpr + " in method " + method;
}
/* End of public methods. */
AllocNode(PAG pag, Object newExpr, Type t, SootMethod m) {
super(pag, t);
this.method = m;
if (t instanceof RefType) {
RefType rt = (RefType) t;
if (rt.getSootClass().isAbstract()) {
boolean usesReflectionLog = new CGOptions(PhaseOptions.v().getPhaseOptions("cg")).reflection_log() != null;
if (!usesReflectionLog) {
throw new RuntimeException("Attempt to create allocnode with abstract type " + t);
}
}
}
this.newExpr = newExpr;
if (newExpr instanceof ContextVarNode) {
throw new RuntimeException();
}
pag.getAllocNodeNumberer().add(this);
}
/** Registers a AllocDotField as having this node as its base. */
void addField(AllocDotField adf, SparkField field) {
if (fields == null) {
fields = new HashMap<SparkField, AllocDotField>();
}
fields.put(field, adf);
}
public Set<AllocDotField> getFields() {
if (fields == null) {
return Collections.emptySet();
}
return new HashSet<AllocDotField>(fields.values());
}
/* End of package methods. */
protected Object newExpr;
protected Map<SparkField, AllocDotField> fields;
private SootMethod method;
public SootMethod getMethod() {
return method;
}
}
| 3,271
| 27.206897
| 115
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/ArrayElement.java
|
package soot.jimple.spark.pag;
/*-
* #%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 soot.G;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.Type;
/**
* Represents an array element.
*
* @author Ondrej Lhotak
*/
public class ArrayElement implements SparkField {
public ArrayElement(Singletons.Global g) {
}
public static ArrayElement v() {
return G.v().soot_jimple_spark_pag_ArrayElement();
}
public ArrayElement() {
Scene.v().getFieldNumberer().add(this);
}
public final int getNumber() {
return number;
}
public final void setNumber(int number) {
this.number = number;
}
public Type getType() {
return RefType.v("java.lang.Object");
}
private int number = 0;
}
| 1,500
| 23.209677
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/ClassConstantNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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.RefType;
import soot.jimple.ClassConstant;
/**
* Represents an allocation site node the represents a known java.lang.Class object.
*
* @author Ondrej Lhotak
*/
public class ClassConstantNode extends AllocNode {
public String toString() {
return "ClassConstantNode " + getNumber() + " " + newExpr;
}
public ClassConstant getClassConstant() {
return (ClassConstant) newExpr;
}
/* End of public methods. */
ClassConstantNode(PAG pag, ClassConstant cc) {
super(pag, cc, RefType.v("java.lang.Class"), null);
}
}
| 1,384
| 27.854167
| 84
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/ContextVarNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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 soot.Context;
/**
* Represents a simple variable node with context.
*
* @author Ondrej Lhotak
*/
public class ContextVarNode extends LocalVarNode {
private Context context;
public Context context() {
return context;
}
public String toString() {
return "ContextVarNode " + getNumber() + " " + variable + " " + method + " " + context;
}
/* End of public methods. */
ContextVarNode(PAG pag, LocalVarNode base, Context context) {
super(pag, base.getVariable(), base.getType(), base.getMethod());
this.context = context;
base.addContext(this, context);
}
}
| 1,435
| 27.156863
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/FieldRefNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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%
*/
/**
* Represents a field reference node (Red) in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public class FieldRefNode extends ValNode {
/** Returns the base of this field reference. */
public VarNode getBase() {
return base;
}
public Node getReplacement() {
if (replacement == this) {
if (base.replacement == base) {
return this;
}
Node baseRep = base.getReplacement();
FieldRefNode newRep = pag.makeFieldRefNode((VarNode) baseRep, field);
newRep.mergeWith(this);
return replacement = newRep.getReplacement();
} else {
return replacement = replacement.getReplacement();
}
}
/** Returns the field of this field reference. */
public SparkField getField() {
return field;
}
public String toString() {
return "FieldRefNode " + getNumber() + " " + base + "." + field;
}
/* End of public methods. */
FieldRefNode(PAG pag, VarNode base, SparkField field) {
super(pag, null);
if (field == null) {
throw new RuntimeException("null field");
}
this.base = base;
this.field = field;
base.addField(this, field);
pag.getFieldRefNodeNumberer().add(this);
}
/* End of package methods. */
protected VarNode base;
protected SparkField field;
}
| 2,124
| 26.597403
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/GlobalVarNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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.SootClass;
import soot.SootField;
import soot.Type;
/**
* Represents a simple variable node (Green) in the pointer assignment graph that is not associated with any particular
* method invocation.
*
* @author Ondrej Lhotak
*/
public class GlobalVarNode extends VarNode {
GlobalVarNode(PAG pag, Object variable, Type t) {
super(pag, variable, t);
}
public String toString() {
return "GlobalVarNode " + getNumber() + " " + variable;
}
public SootClass getDeclaringClass() {
if (variable instanceof SootField) {
return ((SootField) variable).getDeclaringClass();
}
return null;
}
}
| 1,467
| 27.230769
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/LocalVarNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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.HashMap;
import java.util.Map;
import soot.SootMethod;
import soot.Type;
/**
* Represents a simple variable node (Green) in the pointer assignment graph that is specific to a particular method
* invocation.
*
* @author Ondrej Lhotak
*/
public class LocalVarNode extends VarNode {
public ContextVarNode context(Object context) {
return cvns == null ? null : cvns.get(context);
}
public SootMethod getMethod() {
return method;
}
public String toString() {
return "LocalVarNode " + getNumber() + " " + variable + " " + method;
}
/* End of public methods. */
LocalVarNode(PAG pag, Object variable, Type t, SootMethod m) {
super(pag, variable, t);
this.method = m;
// if( m == null ) throw new RuntimeException( "method shouldn't be null" );
}
/** Registers a cvn as having this node as its base. */
void addContext(ContextVarNode cvn, Object context) {
if (cvns == null) {
cvns = new HashMap<Object, ContextVarNode>();
}
cvns.put(context, cvn);
}
/* End of package methods. */
protected Map<Object, ContextVarNode> cvns;
protected SootMethod method;
}
| 1,980
| 27.3
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/MethodPAG.java
|
package soot.jimple.spark.pag;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import soot.ArrayType;
import soot.Body;
import soot.Context;
import soot.EntryPoints;
import soot.G;
import soot.RefLikeType;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.VoidType;
import soot.jimple.Stmt;
import soot.jimple.spark.builder.MethodNodeFactory;
import soot.jimple.spark.internal.SparkLibraryHelper;
import soot.options.CGOptions;
import soot.util.NumberedString;
import soot.util.queue.ChunkedQueue;
import soot.util.queue.QueueReader;
/**
* Part of a pointer assignment graph for a single method.
*
* @author Ondrej Lhotak
*/
public final class MethodPAG {
private PAG pag;
public PAG pag() {
return pag;
}
protected MethodPAG(PAG pag, SootMethod m) {
this.pag = pag;
this.method = m;
this.nodeFactory = new MethodNodeFactory(pag, this);
}
private Set<Context> addedContexts;
/**
* Adds this method to the main PAG, with all VarNodes parameterized by varNodeParameter.
*/
public void addToPAG(Context varNodeParameter) {
if (!hasBeenBuilt) {
throw new RuntimeException(String.format("No PAG built for context %s and method %s", varNodeParameter, method));
}
if (varNodeParameter == null) {
if (hasBeenAdded) {
return;
}
hasBeenAdded = true;
} else {
if (addedContexts == null) {
addedContexts = new HashSet<Context>();
}
if (!addedContexts.add(varNodeParameter)) {
return;
}
}
QueueReader<Node> reader = internalReader.clone();
while (reader.hasNext()) {
Node src = reader.next();
src = parameterize(src, varNodeParameter);
Node dst = reader.next();
dst = parameterize(dst, varNodeParameter);
pag.addEdge(src, dst);
}
reader = inReader.clone();
while (reader.hasNext()) {
Node src = reader.next();
Node dst = reader.next();
dst = parameterize(dst, varNodeParameter);
pag.addEdge(src, dst);
}
reader = outReader.clone();
while (reader.hasNext()) {
Node src = reader.next();
src = parameterize(src, varNodeParameter);
Node dst = reader.next();
pag.addEdge(src, dst);
}
}
public void addInternalEdge(Node src, Node dst) {
if (src == null) {
return;
}
internalEdges.add(src);
internalEdges.add(dst);
if (hasBeenAdded) {
pag.addEdge(src, dst);
}
}
public void addInEdge(Node src, Node dst) {
if (src == null) {
return;
}
inEdges.add(src);
inEdges.add(dst);
if (hasBeenAdded) {
pag.addEdge(src, dst);
}
}
public void addOutEdge(Node src, Node dst) {
if (src == null) {
return;
}
outEdges.add(src);
outEdges.add(dst);
if (hasBeenAdded) {
pag.addEdge(src, dst);
}
}
private final ChunkedQueue<Node> internalEdges = new ChunkedQueue<Node>();
private final ChunkedQueue<Node> inEdges = new ChunkedQueue<Node>();
private final ChunkedQueue<Node> outEdges = new ChunkedQueue<Node>();
private final QueueReader<Node> internalReader = internalEdges.reader();
private final QueueReader<Node> inReader = inEdges.reader();
private final QueueReader<Node> outReader = outEdges.reader();
SootMethod method;
public SootMethod getMethod() {
return method;
}
protected MethodNodeFactory nodeFactory;
public MethodNodeFactory nodeFactory() {
return nodeFactory;
}
public static MethodPAG v(PAG pag, SootMethod m) {
MethodPAG ret = G.v().MethodPAG_methodToPag.get(m);
if (ret == null) {
ret = new MethodPAG(pag, m);
G.v().MethodPAG_methodToPag.put(m, ret);
}
return ret;
}
public void build() {
if (hasBeenBuilt) {
return;
}
hasBeenBuilt = true;
if (method.isNative()) {
if (pag().getOpts().simulate_natives()) {
buildNative();
}
} else {
if (method.isConcrete() && !method.isPhantom()) {
buildNormal();
}
}
addMiscEdges();
}
protected VarNode parameterize(LocalVarNode vn, Context varNodeParameter) {
SootMethod m = vn.getMethod();
if (m != method && m != null) {
throw new RuntimeException("VarNode " + vn + " with method " + m + " parameterized in method " + method);
}
// System.out.println( "parameterizing "+vn+" with "+varNodeParameter );
return pag().makeContextVarNode(vn, varNodeParameter);
}
protected FieldRefNode parameterize(FieldRefNode frn, Context varNodeParameter) {
return pag().makeFieldRefNode((VarNode) parameterize(frn.getBase(), varNodeParameter), frn.getField());
}
public Node parameterize(Node n, Context varNodeParameter) {
if (varNodeParameter == null) {
return n;
}
if (n instanceof LocalVarNode) {
return parameterize((LocalVarNode) n, varNodeParameter);
}
if (n instanceof FieldRefNode) {
return parameterize((FieldRefNode) n, varNodeParameter);
}
return n;
}
protected boolean hasBeenAdded = false;
protected boolean hasBeenBuilt = false;
protected void buildNormal() {
Body b = method.retrieveActiveBody();
for (Unit u : b.getUnits()) {
nodeFactory.handleStmt((Stmt) u);
}
}
protected void buildNative() {
ValNode thisNode = null;
ValNode retNode = null;
if (!method.isStatic()) {
thisNode = (ValNode) nodeFactory.caseThis();
}
if (method.getReturnType() instanceof RefLikeType) {
retNode = (ValNode) nodeFactory.caseRet();
// on library analysis we assume that the return type of an native method can
// be anything matching to the declared type.
if (pag.getCGOpts().library() != CGOptions.library_disabled) {
Type retType = method.getReturnType();
retType.apply(new SparkLibraryHelper(pag, retNode, method));
}
}
ValNode[] args = new ValNode[method.getParameterCount()];
for (int i = 0; i < method.getParameterCount(); i++) {
if (!(method.getParameterType(i) instanceof RefLikeType)) {
continue;
}
args[i] = (ValNode) nodeFactory.caseParm(i);
}
pag.nativeMethodDriver.process(method, thisNode, retNode, args);
}
private final static String mainSubSignature = SootMethod.getSubSignature("main",
Collections.<Type>singletonList(ArrayType.v(RefType.v("java.lang.String"), 1)), VoidType.v());
protected void addMiscEdges() {
// Add node for parameter (String[]) in main method
final String signature = method.getSignature();
if (method.getSubSignature().equals(mainSubSignature)) {
addInEdge(pag().nodeFactory().caseArgv(), nodeFactory.caseParm(0));
} else if (signature.equals("<java.lang.Thread: void <init>(java.lang.ThreadGroup,java.lang.String)>")) {
addInEdge(pag().nodeFactory().caseMainThread(), nodeFactory.caseThis());
addInEdge(pag().nodeFactory().caseMainThreadGroup(), nodeFactory.caseParm(0));
} else if (signature.equals("<java.lang.ref.Finalizer: void <init>(java.lang.Object)>")) {
addInEdge(nodeFactory.caseThis(), pag().nodeFactory().caseFinalizeQueue());
} else if (signature.equals("<java.lang.ref.Finalizer: void runFinalizer()>")) {
addInEdge(pag.nodeFactory().caseFinalizeQueue(), nodeFactory.caseThis());
} else if (signature.equals("<java.lang.ref.Finalizer: void access$100(java.lang.Object)>")) {
addInEdge(pag.nodeFactory().caseFinalizeQueue(), nodeFactory.caseParm(0));
} else if (signature.equals("<java.lang.ClassLoader: void <init>()>")) {
addInEdge(pag.nodeFactory().caseDefaultClassLoader(), nodeFactory.caseThis());
} else if (signature.equals("<java.lang.Thread: void exit()>")) {
addInEdge(pag.nodeFactory().caseMainThread(), nodeFactory.caseThis());
} else if (signature.equals("<java.security.PrivilegedActionException: void <init>(java.lang.Exception)>")) {
addInEdge(pag.nodeFactory().caseThrow(), nodeFactory.caseParm(0));
addInEdge(pag.nodeFactory().casePrivilegedActionException(), nodeFactory.caseThis());
}
if (method.getNumberedSubSignature().equals(sigCanonicalize)) {
SootClass cl = method.getDeclaringClass();
while (cl != null) {
if (cl.equals(Scene.v().getSootClassUnsafe("java.io.FileSystem"))) {
addInEdge(pag.nodeFactory().caseCanonicalPath(), nodeFactory.caseRet());
}
cl = cl.getSuperclassUnsafe();
}
}
boolean isImplicit = false;
for (SootMethod implicitMethod : EntryPoints.v().implicit()) {
if (implicitMethod.getNumberedSubSignature().equals(method.getNumberedSubSignature())) {
isImplicit = true;
break;
}
}
if (isImplicit) {
SootClass c = method.getDeclaringClass();
outer: do {
while (!c.getName().equals("java.lang.ClassLoader")) {
if (!c.hasSuperclass()) {
break outer;
}
c = c.getSuperclass();
}
if (method.getName().equals("<init>")) {
continue;
}
addInEdge(pag().nodeFactory().caseDefaultClassLoader(), nodeFactory.caseThis());
addInEdge(pag().nodeFactory().caseMainClassNameString(), nodeFactory.caseParm(0));
} while (false);
}
}
protected final NumberedString sigCanonicalize
= Scene.v().getSubSigNumberer().findOrAdd("java.lang.String canonicalize(java.lang.String)");
}
| 10,293
| 31.269592
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/NewInstanceNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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.Type;
import soot.Value;
/**
*
* Node that represents a call to newInstance()
*
* @author Steven Arzt
*
*/
public class NewInstanceNode extends Node {
private final Value value;
NewInstanceNode(PAG pag, Value value, Type type) {
super(pag, type);
this.value = value;
}
public Value getValue() {
return this.value;
}
}
| 1,215
| 23.816327
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/Node.java
|
package soot.jimple.spark.pag;
/*-
* #%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 soot.Type;
import soot.jimple.spark.internal.TypeManager;
import soot.jimple.spark.sets.EmptyPointsToSet;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.pointer.representations.ReferenceVariable;
import soot.options.Options;
import soot.util.Numberable;
/**
* Represents every node in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public class Node implements ReferenceVariable, Numberable {
public final int hashCode() {
return number;
}
public final boolean equals(Object other) {
return this == other;
}
/** Returns the declared type of this node, null for unknown. */
public Type getType() {
return type;
}
/** Sets the declared type of this node, null for unknown. */
public void setType(Type type) {
if (TypeManager.isUnresolved(type) && !Options.v().ignore_resolution_errors()) {
throw new RuntimeException("Unresolved type " + type);
}
this.type = type;
}
/**
* If this node has been merged with another, returns the new node to be used as the representative of this node; returns
* this if the node has not been merged.
*/
public Node getReplacement() {
if (replacement != replacement.replacement) {
replacement = replacement.getReplacement();
}
return replacement;
}
/** Merge with the node other. */
public void mergeWith(Node other) {
if (other.replacement != other) {
throw new RuntimeException("Shouldn't happen");
}
Node myRep = getReplacement();
if (other == myRep) {
return;
}
other.replacement = myRep;
if (other.p2set != p2set && other.p2set != null && !other.p2set.isEmpty()) {
if (myRep.p2set == null || myRep.p2set.isEmpty()) {
myRep.p2set = other.p2set;
} else {
myRep.p2set.mergeWith(other.p2set);
}
}
other.p2set = null;
pag.mergedWith(myRep, other);
if ((other instanceof VarNode) && (myRep instanceof VarNode) && ((VarNode) other).isInterProcTarget()) {
((VarNode) myRep).setInterProcTarget();
}
}
/** Returns the points-to set for this node. */
public PointsToSetInternal getP2Set() {
if (p2set != null) {
if (replacement != this) {
throw new RuntimeException("Node " + this + " has replacement " + replacement + " but has p2set");
}
return p2set;
}
Node rep = getReplacement();
if (rep == this) {
return EmptyPointsToSet.v();
}
return rep.getP2Set();
}
/** Returns the points-to set for this node, makes it if necessary. */
public PointsToSetInternal makeP2Set() {
if (p2set != null) {
if (replacement != this) {
throw new RuntimeException("Node " + this + " has replacement " + replacement + " but has p2set");
}
return p2set;
}
Node rep = getReplacement();
if (rep == this) {
p2set = pag.getSetFactory().newSet(type, pag);
}
return rep.makeP2Set();
}
/** Returns the pointer assignment graph that this node is a part of. */
public PAG getPag() {
return pag;
}
/** Delete current points-to set and make a new one */
public void discardP2Set() {
p2set = null;
}
/** Use the specified points-to set to replace current one */
public void setP2Set(PointsToSetInternal ptsInternal) {
p2set = ptsInternal;
}
/* End of public methods. */
/** Creates a new node of pointer assignment graph pag, with type type. */
Node(PAG pag, Type type) {
if (TypeManager.isUnresolved(type) && !Options.v().ignore_resolution_errors()) {
throw new RuntimeException("Unresolved type " + type);
}
this.type = type;
this.pag = pag;
replacement = this;
}
/* End of package methods. */
public final int getNumber() {
return number;
}
public final void setNumber(int number) {
this.number = number;
}
private int number = 0;
protected Type type;
protected Node replacement;
protected PAG pag;
protected PointsToSetInternal p2set;
}
| 4,841
| 27.650888
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/PAG.java
|
package soot.jimple.spark.pag;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Context;
import soot.FastHierarchy;
import soot.Kind;
import soot.Local;
import soot.PhaseOptions;
import soot.PointsToAnalysis;
import soot.PointsToSet;
import soot.RefLikeType;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.ClassConstant;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.NewExpr;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.spark.builder.GlobalNodeFactory;
import soot.jimple.spark.builder.MethodNodeFactory;
import soot.jimple.spark.internal.ClientAccessibilityOracle;
import soot.jimple.spark.internal.SparkLibraryHelper;
import soot.jimple.spark.internal.TypeManager;
import soot.jimple.spark.sets.BitPointsToSet;
import soot.jimple.spark.sets.DoublePointsToSet;
import soot.jimple.spark.sets.EmptyPointsToSet;
import soot.jimple.spark.sets.HashPointsToSet;
import soot.jimple.spark.sets.HybridPointsToSet;
import soot.jimple.spark.sets.P2SetFactory;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.spark.sets.SharedHybridSet;
import soot.jimple.spark.sets.SharedListSet;
import soot.jimple.spark.sets.SortedArraySet;
import soot.jimple.spark.solver.OnFlyCallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.jimple.toolkits.pointer.util.NativeMethodDriver;
import soot.options.CGOptions;
import soot.options.SparkOptions;
import soot.tagkit.LinkTag;
import soot.tagkit.StringTag;
import soot.tagkit.Tag;
import soot.toolkits.scalar.Pair;
import soot.util.ArrayNumberer;
import soot.util.HashMultiMap;
import soot.util.LargeNumberedMap;
import soot.util.MultiMap;
import soot.util.queue.ChunkedQueue;
import soot.util.queue.QueueReader;
/**
* Pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public class PAG implements PointsToAnalysis {
private static final Logger logger = LoggerFactory.getLogger(PAG.class);
public PAG(final SparkOptions opts) {
this.opts = opts;
this.cgOpts = new CGOptions(PhaseOptions.v().getPhaseOptions("cg"));
if (opts.add_tags()) {
nodeToTag = new HashMap<Node, Tag>();
}
if (opts.rta() && opts.on_fly_cg()) {
throw new RuntimeException("Incompatible options rta:true and on-fly-cg:true for cg.spark. Use -p cg-"
+ ".spark on-fly-cg:false when using RTA.");
}
typeManager = new TypeManager(this);
if (!opts.ignore_types()) {
typeManager.setFastHierarchy(() -> Scene.v().getOrMakeFastHierarchy());
}
if (opts.cs_demand()) {
virtualCallsToReceivers = new HashMap<InvokeExpr, Node>();
callToMethod = new HashMap<InvokeExpr, SootMethod>();
callAssigns = new HashMultiMap<InvokeExpr, Pair<Node, Node>>();
}
switch (opts.set_impl()) {
case SparkOptions.set_impl_hash:
setFactory = HashPointsToSet.getFactory();
break;
case SparkOptions.set_impl_hybrid:
setFactory = HybridPointsToSet.getFactory();
break;
case SparkOptions.set_impl_heintze:
setFactory = SharedHybridSet.getFactory();
break;
case SparkOptions.set_impl_sharedlist:
setFactory = SharedListSet.getFactory();
break;
case SparkOptions.set_impl_array:
setFactory = SortedArraySet.getFactory();
break;
case SparkOptions.set_impl_bit:
setFactory = BitPointsToSet.getFactory();
break;
case SparkOptions.set_impl_double:
P2SetFactory oldF;
P2SetFactory newF;
switch (opts.double_set_old()) {
case SparkOptions.double_set_old_hash:
oldF = HashPointsToSet.getFactory();
break;
case SparkOptions.double_set_old_hybrid:
oldF = HybridPointsToSet.getFactory();
break;
case SparkOptions.double_set_old_heintze:
oldF = SharedHybridSet.getFactory();
break;
case SparkOptions.double_set_old_sharedlist:
oldF = SharedListSet.getFactory();
break;
case SparkOptions.double_set_old_array:
oldF = SortedArraySet.getFactory();
break;
case SparkOptions.double_set_old_bit:
oldF = BitPointsToSet.getFactory();
break;
default:
throw new RuntimeException();
}
switch (opts.double_set_new()) {
case SparkOptions.double_set_new_hash:
newF = HashPointsToSet.getFactory();
break;
case SparkOptions.double_set_new_hybrid:
newF = HybridPointsToSet.getFactory();
break;
case SparkOptions.double_set_new_heintze:
newF = SharedHybridSet.getFactory();
break;
case SparkOptions.double_set_new_sharedlist:
newF = SharedListSet.getFactory();
break;
case SparkOptions.double_set_new_array:
newF = SortedArraySet.getFactory();
break;
case SparkOptions.double_set_new_bit:
newF = BitPointsToSet.getFactory();
break;
default:
throw new RuntimeException();
}
setFactory = DoublePointsToSet.getFactory(newF, oldF);
break;
default:
throw new RuntimeException();
}
runGeomPTA = opts.geom_pta();
}
/** Returns the set of objects pointed to by variable l. */
public PointsToSet reachingObjects(Local l) {
VarNode n = findLocalVarNode(l);
if (n == null) {
return EmptyPointsToSet.v();
}
return n.getP2Set();
}
/** Returns the set of objects pointed to by variable l in context c. */
public PointsToSet reachingObjects(Context c, Local l) {
VarNode n = findContextVarNode(l, c);
if (n == null) {
return EmptyPointsToSet.v();
}
return n.getP2Set();
}
/** Returns the set of objects pointed to by static field f. */
public PointsToSet reachingObjects(SootField f) {
if (!f.isStatic()) {
throw new RuntimeException("The parameter f must be a *static* field.");
}
VarNode n = findGlobalVarNode(f);
if (n == null) {
return EmptyPointsToSet.v();
}
return n.getP2Set();
}
/**
* Returns the set of objects pointed to by instance field f of the objects in the PointsToSet s.
*/
public PointsToSet reachingObjects(PointsToSet s, final SootField f) {
if (f.isStatic()) {
throw new RuntimeException("The parameter f must be an *instance* field.");
}
return reachingObjectsInternal(s, f);
}
/**
* Returns the set of objects pointed to by elements of the arrays in the PointsToSet s.
*/
public PointsToSet reachingObjectsOfArrayElement(PointsToSet s) {
return reachingObjectsInternal(s, ArrayElement.v());
}
private PointsToSet reachingObjectsInternal(PointsToSet s, final SparkField f) {
if (getOpts().field_based() || getOpts().vta()) {
VarNode n = findGlobalVarNode(f);
if (n == null) {
return EmptyPointsToSet.v();
}
return n.getP2Set();
}
if ((getOpts()).propagator() == SparkOptions.propagator_alias) {
throw new RuntimeException("The alias edge propagator does not compute points-to information for instance fields!"
+ "Use a different propagator.");
}
PointsToSetInternal bases = (PointsToSetInternal) s;
final PointsToSetInternal ret = setFactory.newSet((f instanceof SootField) ? ((SootField) f).getType() : null, this);
bases.forall(new P2SetVisitor() {
public final void visit(Node n) {
Node nDotF = ((AllocNode) n).dot(f);
if (nDotF != null) {
ret.addAll(nDotF.getP2Set(), null);
}
}
});
return ret;
}
public P2SetFactory getSetFactory() {
return setFactory;
}
private <K extends Node> void lookupInMap(Map<K, Object> map) {
for (K object : map.keySet()) {
lookup(map, object);
}
}
public void cleanUpMerges() {
if (opts.verbose()) {
logger.debug("Cleaning up graph for merged nodes");
}
lookupInMap(simple);
lookupInMap(alloc);
lookupInMap(store);
lookupInMap(load);
lookupInMap(simpleInv);
lookupInMap(allocInv);
lookupInMap(storeInv);
lookupInMap(loadInv);
somethingMerged = false;
if (opts.verbose()) {
logger.debug("Done cleaning up graph for merged nodes");
}
}
public boolean doAddSimpleEdge(VarNode from, VarNode to) {
return addToMap(simple, from, to) | addToMap(simpleInv, to, from);
}
public boolean doAddStoreEdge(VarNode from, FieldRefNode to) {
return addToMap(store, from, to) | addToMap(storeInv, to, from);
}
public boolean doAddLoadEdge(FieldRefNode from, VarNode to) {
return addToMap(load, from, to) | addToMap(loadInv, to, from);
}
public boolean doAddAllocEdge(AllocNode from, VarNode to) {
return addToMap(alloc, from, to) | addToMap(allocInv, to, from);
}
public boolean doAddNewInstanceEdge(VarNode from, NewInstanceNode to) {
return addToMap(newInstance, from, to) | addToMap(newInstanceInv, to, from);
}
public boolean doAddAssignInstanceEdge(NewInstanceNode from, VarNode to) {
return addToMap(assignInstance, from, to) | addToMap(assignInstanceInv, to, from);
}
/** Node uses this to notify PAG that n2 has been merged into n1. */
void mergedWith(Node n1, Node n2) {
if (n1.equals(n2)) {
throw new RuntimeException("oops");
}
somethingMerged = true;
if (ofcg() != null) {
ofcg().mergedWith(n1, n2);
}
Map[] maps = { simple, alloc, store, load, simpleInv, allocInv, storeInv, loadInv };
for (Map<Node, Object> m : maps) {
if (!m.keySet().contains(n2)) {
continue;
}
Object[] os = { m.get(n1), m.get(n2) };
int size1 = getSize(os[0]);
int size2 = getSize(os[1]);
if (size1 == 0) {
if (os[1] != null) {
m.put(n1, os[1]);
}
} else if (size2 == 0) {
// nothing needed
} else if (os[0] instanceof HashSet) {
if (os[1] instanceof HashSet) {
((HashSet) os[0]).addAll((HashSet) os[1]);
} else {
Node[] ar = (Node[]) os[1];
for (Node element0 : ar) {
((HashSet<Node>) os[0]).add(element0);
}
}
} else if (os[1] instanceof HashSet) {
Node[] ar = (Node[]) os[0];
for (Node element0 : ar) {
((HashSet<Node>) os[1]).add(element0);
}
m.put(n1, os[1]);
} else if (size1 * size2 < 1000) {
Node[] a1 = (Node[]) os[0];
Node[] a2 = (Node[]) os[1];
Node[] ret = new Node[size1 + size2];
System.arraycopy(a1, 0, ret, 0, a1.length);
int j = a1.length;
outer: for (Node rep : a2) {
for (int k = 0; k < j; k++) {
if (rep == ret[k]) {
continue outer;
}
}
ret[j++] = rep;
}
Node[] newArray = new Node[j];
System.arraycopy(ret, 0, newArray, 0, j);
m.put(n1, ret = newArray);
} else {
HashSet<Node> s = new HashSet<Node>(size1 + size2);
for (Object o : os) {
if (o == null) {
continue;
}
if (o instanceof Set) {
s.addAll((Set<Node>) o);
} else {
Node[] ar = (Node[]) o;
for (Node element1 : ar) {
s.add(element1);
}
}
}
m.put(n1, s);
}
m.remove(n2);
}
}
protected final static Node[] EMPTY_NODE_ARRAY = new Node[0];
protected <K extends Node> Node[] lookup(Map<K, Object> m, K key) {
Object valueList = m.get(key);
if (valueList == null) {
return EMPTY_NODE_ARRAY;
}
if (valueList instanceof Set) {
try {
m.put(key, valueList = ((Set) valueList).toArray(EMPTY_NODE_ARRAY));
} catch (Exception e) {
for (Iterator it = ((Set) valueList).iterator(); it.hasNext();) {
logger.debug("" + it.next());
}
throw new RuntimeException("" + valueList + e);
}
}
Node[] ret = (Node[]) valueList;
if (somethingMerged) {
for (int i = 0; i < ret.length; i++) {
Node reti = ret[i];
Node rep = reti.getReplacement();
if (rep != reti || rep == key) {
Set<Node> s;
if (ret.length <= 75) {
int j = i;
outer: for (; i < ret.length; i++) {
reti = ret[i];
rep = reti.getReplacement();
if (rep == key) {
continue;
}
for (int k = 0; k < j; k++) {
if (rep == ret[k]) {
continue outer;
}
}
ret[j++] = rep;
}
Node[] newArray = new Node[j];
System.arraycopy(ret, 0, newArray, 0, j);
m.put(key, ret = newArray);
} else {
s = new HashSet<Node>(ret.length * 2);
for (int j = 0; j < i; j++) {
s.add(ret[j]);
}
for (int j = i; j < ret.length; j++) {
rep = ret[j].getReplacement();
if (rep != key) {
s.add(rep);
}
}
m.put(key, ret = s.toArray(EMPTY_NODE_ARRAY));
}
break;
}
}
}
return ret;
}
public Node[] simpleLookup(VarNode key) {
return lookup(simple, key);
}
public Node[] simpleInvLookup(VarNode key) {
return lookup(simpleInv, key);
}
public Node[] loadLookup(FieldRefNode key) {
return lookup(load, key);
}
public Node[] loadInvLookup(VarNode key) {
return lookup(loadInv, key);
}
public Node[] storeLookup(VarNode key) {
return lookup(store, key);
}
public Node[] newInstanceLookup(VarNode key) {
return lookup(newInstance, key);
}
public Node[] assignInstanceLookup(NewInstanceNode key) {
return lookup(assignInstance, key);
}
public Node[] storeInvLookup(FieldRefNode key) {
return lookup(storeInv, key);
}
public Node[] allocLookup(AllocNode key) {
return lookup(alloc, key);
}
public Node[] allocInvLookup(VarNode key) {
return lookup(allocInv, key);
}
public Set<VarNode> simpleSources() {
return simple.keySet();
}
public Set<AllocNode> allocSources() {
return alloc.keySet();
}
public Set<VarNode> storeSources() {
return store.keySet();
}
public Set<FieldRefNode> loadSources() {
return load.keySet();
}
public Set<VarNode> newInstanceSources() {
return newInstance.keySet();
}
public Set<NewInstanceNode> assignInstanceSources() {
return assignInstance.keySet();
}
public Set<VarNode> simpleInvSources() {
return simpleInv.keySet();
}
public Set<VarNode> allocInvSources() {
return allocInv.keySet();
}
public Set<FieldRefNode> storeInvSources() {
return storeInv.keySet();
}
public Set<VarNode> loadInvSources() {
return loadInv.keySet();
}
public Iterator<VarNode> simpleSourcesIterator() {
return simple.keySet().iterator();
}
public Iterator<AllocNode> allocSourcesIterator() {
return alloc.keySet().iterator();
}
public Iterator<VarNode> storeSourcesIterator() {
return store.keySet().iterator();
}
public Iterator<FieldRefNode> loadSourcesIterator() {
return load.keySet().iterator();
}
public Iterator<VarNode> simpleInvSourcesIterator() {
return simpleInv.keySet().iterator();
}
public Iterator<VarNode> allocInvSourcesIterator() {
return allocInv.keySet().iterator();
}
public Iterator<FieldRefNode> storeInvSourcesIterator() {
return storeInv.keySet().iterator();
}
public Iterator<VarNode> loadInvSourcesIterator() {
return loadInv.keySet().iterator();
}
static private int getSize(Object set) {
if (set instanceof Set) {
return ((Set<?>) set).size();
} else if (set == null) {
return 0;
} else {
return ((Object[]) set).length;
}
}
protected P2SetFactory setFactory;
protected boolean somethingMerged = false;
/**
* Returns the set of objects pointed to by instance field f of the objects pointed to by l.
*/
public PointsToSet reachingObjects(Local l, SootField f) {
return reachingObjects(reachingObjects(l), f);
}
/**
* Returns the set of objects pointed to by instance field f of the objects pointed to by l in context c.
*/
public PointsToSet reachingObjects(Context c, Local l, SootField f) {
return reachingObjects(reachingObjects(c, l), f);
}
private void addNodeTag(Node node, SootMethod m) {
if (nodeToTag != null) {
Tag tag;
if (m == null) {
tag = new StringTag(node.toString());
} else {
tag = new LinkTag(node.toString(), m, m.getDeclaringClass().getName());
}
nodeToTag.put(node, tag);
}
}
public AllocNode makeAllocNode(Object newExpr, Type type, SootMethod m) {
if (opts.types_for_sites() || opts.vta()) {
newExpr = type;
}
AllocNode ret = valToAllocNode.get(newExpr);
if (newExpr instanceof NewExpr) {
// Do we need to create a new allocation node?
if (ret == null) {
valToAllocNode.put(newExpr, ret = new AllocNode(this, newExpr, type, m));
newAllocNodes.add(ret);
addNodeTag(ret, m);
}
// For a normal "new" expression, there may only be one type
else if (!(ret.getType().equals(type))) {
throw new RuntimeException("NewExpr " + newExpr + " of type " + type + " previously had type " + ret.getType());
}
}
// Check for reflective allocation sites
else {
ret = valToReflAllocNode.get(newExpr, type);
if (ret == null) {
valToReflAllocNode.put(newExpr, type, ret = new AllocNode(this, newExpr, type, m));
newAllocNodes.add(ret);
addNodeTag(ret, m);
}
}
return ret;
}
public AllocNode makeStringConstantNode(String s) {
if (opts.types_for_sites() || opts.vta()) {
return makeAllocNode(RefType.v("java.lang.String"), RefType.v("java.lang.String"), null);
}
StringConstantNode ret = (StringConstantNode) valToAllocNode.get(s);
if (ret == null) {
valToAllocNode.put(s, ret = new StringConstantNode(this, s));
newAllocNodes.add(ret);
addNodeTag(ret, null);
}
return ret;
}
public AllocNode makeClassConstantNode(ClassConstant cc) {
if (opts.types_for_sites() || opts.vta()) {
return makeAllocNode(RefType.v("java.lang.Class"), RefType.v("java.lang.Class"), null);
}
ClassConstantNode ret = (ClassConstantNode) valToAllocNode.get(cc);
if (ret == null) {
valToAllocNode.put(cc, ret = new ClassConstantNode(this, cc));
newAllocNodes.add(ret);
addNodeTag(ret, null);
}
return ret;
}
ChunkedQueue<AllocNode> newAllocNodes = new ChunkedQueue<AllocNode>();
public QueueReader<AllocNode> allocNodeListener() {
return newAllocNodes.reader();
}
/** Finds the GlobalVarNode for the variable value, or returns null. */
public GlobalVarNode findGlobalVarNode(Object value) {
if (opts.rta()) {
value = null;
}
return valToGlobalVarNode.get(value);
}
/** Finds the LocalVarNode for the variable value, or returns null. */
public LocalVarNode findLocalVarNode(Object value) {
if (opts.rta()) {
value = null;
} else if (value instanceof Local) {
return localToNodeMap.get((Local) value);
}
return valToLocalVarNode.get(value);
}
/**
* Finds or creates the GlobalVarNode for the variable value, of type type.
*/
public GlobalVarNode makeGlobalVarNode(Object value, Type type) {
if (opts.rta()) {
value = null;
type = RefType.v("java.lang.Object");
}
GlobalVarNode ret = valToGlobalVarNode.get(value);
if (ret == null) {
valToGlobalVarNode.put(value, ret = new GlobalVarNode(this, value, type));
// if library mode is activated, add allocation of every possible
// type to accessible fields
if (cgOpts.library() != CGOptions.library_disabled) {
if (value instanceof SootField) {
SootField sf = (SootField) value;
if (accessibilityOracle.isAccessible(sf)) {
type.apply(new SparkLibraryHelper(this, ret, null));
}
}
}
addNodeTag(ret, null);
} else if (!(ret.getType().equals(type))) {
throw new RuntimeException("Value " + value + " of type " + type + " previously had type " + ret.getType());
}
return ret;
}
/**
* Finds or creates the LocalVarNode for the variable value, of type type.
*/
public LocalVarNode makeLocalVarNode(Object value, Type type, SootMethod method) {
if (opts.rta()) {
value = null;
type = RefType.v("java.lang.Object");
method = null;
} else if (value instanceof Local) {
Local val = (Local) value;
if (val.getNumber() == 0) {
Scene.v().getLocalNumberer().add(val);
}
LocalVarNode ret = localToNodeMap.get(val);
if (ret == null) {
localToNodeMap.put((Local) value, ret = new LocalVarNode(this, value, type, method));
addNodeTag(ret, method);
} else if (!(ret.getType().equals(type))) {
throw new RuntimeException("Value " + value + " of type " + type + " previously had type " + ret.getType());
}
return ret;
}
LocalVarNode ret = valToLocalVarNode.get(value);
if (ret == null) {
valToLocalVarNode.put(value, ret = new LocalVarNode(this, value, type, method));
addNodeTag(ret, method);
} else if (!(ret.getType().equals(type))) {
throw new RuntimeException("Value " + value + " of type " + type + " previously had type " + ret.getType());
}
return ret;
}
public NewInstanceNode makeNewInstanceNode(Value value, Type type, SootMethod method) {
NewInstanceNode node = newInstToNodeMap.get(value);
if (node == null) {
node = new NewInstanceNode(this, value, type);
newInstToNodeMap.put(value, node);
addNodeTag(node, method);
}
return node;
}
/**
* Finds the ContextVarNode for base variable value and context context, or returns null.
*/
public ContextVarNode findContextVarNode(Object baseValue, Context context) {
LocalVarNode base = findLocalVarNode(baseValue);
if (base == null) {
return null;
}
return base.context(context);
}
/**
* Finds or creates the ContextVarNode for base variable baseValue and context context, of type type.
*/
public ContextVarNode makeContextVarNode(Object baseValue, Type baseType, Context context, SootMethod method) {
LocalVarNode base = makeLocalVarNode(baseValue, baseType, method);
return makeContextVarNode(base, context);
}
/**
* Finds or creates the ContextVarNode for base variable base and context context, of type type.
*/
public ContextVarNode makeContextVarNode(LocalVarNode base, Context context) {
ContextVarNode ret = base.context(context);
if (ret == null) {
ret = new ContextVarNode(this, base, context);
addNodeTag(ret, base.getMethod());
}
return ret;
}
/**
* Finds the FieldRefNode for base variable value and field field, or returns null.
*/
public FieldRefNode findLocalFieldRefNode(Object baseValue, SparkField field) {
VarNode base = findLocalVarNode(baseValue);
if (base == null) {
return null;
}
return base.dot(field);
}
/**
* Finds the FieldRefNode for base variable value and field field, or returns null.
*/
public FieldRefNode findGlobalFieldRefNode(Object baseValue, SparkField field) {
VarNode base = findGlobalVarNode(baseValue);
if (base == null) {
return null;
}
return base.dot(field);
}
/**
* Finds or creates the FieldRefNode for base variable baseValue and field field, of type type.
*/
public FieldRefNode makeLocalFieldRefNode(Object baseValue, Type baseType, SparkField field, SootMethod method) {
VarNode base = makeLocalVarNode(baseValue, baseType, method);
FieldRefNode ret = makeFieldRefNode(base, field);
// if library mode is activated, add allocation of every possible type
// to accessible fields
if (cgOpts.library() != CGOptions.library_disabled) {
if (field instanceof SootField) {
SootField sf = (SootField) field;
Type type = sf.getType();
if (accessibilityOracle.isAccessible(sf)) {
type.apply(new SparkLibraryHelper(this, ret, method));
}
}
}
return ret;
}
/**
* Finds or creates the FieldRefNode for base variable baseValue and field field, of type type.
*/
public FieldRefNode makeGlobalFieldRefNode(Object baseValue, Type baseType, SparkField field) {
VarNode base = makeGlobalVarNode(baseValue, baseType);
return makeFieldRefNode(base, field);
}
/**
* Finds or creates the FieldRefNode for base variable base and field field, of type type.
*/
public FieldRefNode makeFieldRefNode(VarNode base, SparkField field) {
FieldRefNode ret = base.dot(field);
if (ret == null) {
ret = new FieldRefNode(this, base, field);
if (base instanceof LocalVarNode) {
addNodeTag(ret, ((LocalVarNode) base).getMethod());
} else {
addNodeTag(ret, null);
}
}
return ret;
}
/**
* Finds the AllocDotField for base AllocNode an and field field, or returns null.
*/
public AllocDotField findAllocDotField(AllocNode an, SparkField field) {
return an.dot(field);
}
/**
* Finds or creates the AllocDotField for base variable baseValue and field field, of type t.
*/
public AllocDotField makeAllocDotField(AllocNode an, SparkField field) {
AllocDotField ret = an.dot(field);
if (ret == null) {
ret = new AllocDotField(this, an, field);
}
return ret;
}
public boolean addSimpleEdge(VarNode from, VarNode to) {
boolean ret = false;
if (doAddSimpleEdge(from, to)) {
edgeQueue.add(from);
edgeQueue.add(to);
ret = true;
}
if (opts.simple_edges_bidirectional()) {
if (doAddSimpleEdge(to, from)) {
edgeQueue.add(to);
edgeQueue.add(from);
ret = true;
}
}
return ret;
}
public boolean addStoreEdge(VarNode from, FieldRefNode to) {
if (!opts.rta()) {
if (doAddStoreEdge(from, to)) {
edgeQueue.add(from);
edgeQueue.add(to);
return true;
}
}
return false;
}
public boolean addLoadEdge(FieldRefNode from, VarNode to) {
if (!opts.rta()) {
if (doAddLoadEdge(from, to)) {
edgeQueue.add(from);
edgeQueue.add(to);
return true;
}
}
return false;
}
public boolean addAllocEdge(AllocNode from, VarNode to) {
FastHierarchy fh = typeManager.getFastHierarchy();
if (fh == null || to.getType() == null || fh.canStoreType(from.getType(), to.getType())) {
if (doAddAllocEdge(from, to)) {
edgeQueue.add(from);
edgeQueue.add(to);
return true;
}
}
return false;
}
public boolean addNewInstanceEdge(VarNode from, NewInstanceNode to) {
if (!opts.rta()) {
if (doAddNewInstanceEdge(from, to)) {
edgeQueue.add(from);
edgeQueue.add(to);
return true;
}
}
return false;
}
public boolean addAssignInstanceEdge(NewInstanceNode from, VarNode to) {
if (!opts.rta()) {
if (doAddAssignInstanceEdge(from, to)) {
edgeQueue.add(from);
edgeQueue.add(to);
return true;
}
}
return false;
}
/** Adds an edge to the graph, returning false if it was already there. */
public boolean addEdge(Node from, Node to) {
from = from.getReplacement();
to = to.getReplacement();
if (from instanceof VarNode) {
if (to instanceof VarNode) {
return addSimpleEdge((VarNode) from, (VarNode) to);
} else if (to instanceof FieldRefNode) {
return addStoreEdge((VarNode) from, (FieldRefNode) to);
} else if (to instanceof NewInstanceNode) {
return addNewInstanceEdge((VarNode) from, (NewInstanceNode) to);
} else {
throw new RuntimeException("Invalid node type");
}
} else if (from instanceof FieldRefNode) {
return addLoadEdge((FieldRefNode) from, (VarNode) to);
} else if (from instanceof NewInstanceNode) {
return addAssignInstanceEdge((NewInstanceNode) from, (VarNode) to);
} else {
return addAllocEdge((AllocNode) from, (VarNode) to);
}
}
protected ChunkedQueue<Node> edgeQueue = new ChunkedQueue<Node>();
public QueueReader<Node> edgeReader() {
return edgeQueue.reader();
}
public int getNumAllocNodes() {
return allocNodeNumberer.size();
}
public TypeManager getTypeManager() {
return typeManager;
}
public void setOnFlyCallGraph(OnFlyCallGraph ofcg) {
this.ofcg = ofcg;
}
public OnFlyCallGraph getOnFlyCallGraph() {
return ofcg;
}
public OnFlyCallGraph ofcg() {
return ofcg;
}
/**
* Adds the base of a dereference to the list of dereferenced variables.
*/
public void addDereference(VarNode base) {
dereferences.add(base);
}
/** Returns list of dereferences variables. */
public List<VarNode> getDereferences() {
return dereferences;
}
public Map<Node, Tag> getNodeTags() {
return nodeToTag;
}
protected final ArrayNumberer<AllocNode> allocNodeNumberer = new ArrayNumberer<AllocNode>();
public ArrayNumberer<AllocNode> getAllocNodeNumberer() {
return allocNodeNumberer;
}
private final ArrayNumberer<VarNode> varNodeNumberer = new ArrayNumberer<VarNode>();
public ArrayNumberer<VarNode> getVarNodeNumberer() {
return varNodeNumberer;
}
private final ArrayNumberer<FieldRefNode> fieldRefNodeNumberer = new ArrayNumberer<FieldRefNode>();
public ArrayNumberer<FieldRefNode> getFieldRefNodeNumberer() {
return fieldRefNodeNumberer;
}
private final ArrayNumberer<AllocDotField> allocDotFieldNodeNumberer = new ArrayNumberer<AllocDotField>();
public ArrayNumberer<AllocDotField> getAllocDotFieldNodeNumberer() {
return allocDotFieldNodeNumberer;
}
/** Returns SparkOptions for this graph. */
public SparkOptions getOpts() {
return opts;
}
/** Returns CGOptions for this graph. */
public CGOptions getCGOpts() {
return cgOpts;
}
// Must be simple edges
public Pair<Node, Node> addInterproceduralAssignment(Node from, Node to, Edge e) {
Pair<Node, Node> val = new Pair<Node, Node>(from, to);
if (runGeomPTA) {
assign2edges.put(val, e);
}
return val;
}
public Set<Edge> lookupEdgesForAssignment(Pair<Node, Node> val) {
return assign2edges.get(val);
}
public void addCallTarget(Edge e) {
if (!e.passesParameters()) {
return;
}
MethodPAG srcmpag = MethodPAG.v(this, e.src());
MethodPAG tgtmpag = MethodPAG.v(this, e.tgt());
Pair<Node, Node> pval;
if (e.isExplicit() || e.kind() == Kind.THREAD) {
addCallTarget(srcmpag, tgtmpag, (Stmt) e.srcUnit(), e.srcCtxt(), e.tgtCtxt(), e);
} else if (e.kind() == Kind.ASYNCTASK) {
addCallTarget(srcmpag, tgtmpag, (Stmt) e.srcUnit(), e.srcCtxt(), e.tgtCtxt(), e, false);
} else if (e.kind() == Kind.EXECUTOR) {
InvokeExpr ie = e.srcStmt().getInvokeExpr();
Node parm = srcmpag.nodeFactory().getNode(ie.getArg(0));
parm = srcmpag.parameterize(parm, e.srcCtxt());
parm = parm.getReplacement();
Node thiz = tgtmpag.nodeFactory().caseThis();
thiz = tgtmpag.parameterize(thiz, e.tgtCtxt());
thiz = thiz.getReplacement();
addEdge(parm, thiz);
pval = addInterproceduralAssignment(parm, thiz, e);
if (callAssigns != null) {
callToMethod.put(ie, srcmpag.getMethod());
boolean virtualCall = !callAssigns.put(ie, pval);
if (virtualCall) {
virtualCallsToReceivers.putIfAbsent(ie, parm);
}
}
} else if (e.kind() == Kind.HANDLER) {
InvokeExpr ie = e.srcStmt().getInvokeExpr();
Node base = srcmpag.nodeFactory().getNode(((VirtualInvokeExpr) ie).getBase());
base = srcmpag.parameterize(base, e.srcCtxt());
base = base.getReplacement();
Node thiz = tgtmpag.nodeFactory().caseThis();
thiz = tgtmpag.parameterize(thiz, e.tgtCtxt());
thiz = thiz.getReplacement();
addEdge(base, thiz);
pval = addInterproceduralAssignment(base, thiz, e);
if (callAssigns != null) {
boolean virtualCall = !callAssigns.put(ie, pval);
assert virtualCall == true;
callToMethod.put(ie, srcmpag.getMethod());
virtualCallsToReceivers.put(ie, base);
}
} else if (e.kind() == Kind.PRIVILEGED) {
// Flow from first parameter of doPrivileged() invocation
// to this of target, and from return of target to the
// return of doPrivileged()
InvokeExpr ie = e.srcStmt().getInvokeExpr();
Node parm = srcmpag.nodeFactory().getNode(ie.getArg(0));
parm = srcmpag.parameterize(parm, e.srcCtxt());
parm = parm.getReplacement();
Node thiz = tgtmpag.nodeFactory().caseThis();
thiz = tgtmpag.parameterize(thiz, e.tgtCtxt());
thiz = thiz.getReplacement();
addEdge(parm, thiz);
pval = addInterproceduralAssignment(parm, thiz, e);
if (callAssigns != null) {
callAssigns.put(ie, pval);
callToMethod.put(ie, srcmpag.getMethod());
}
if (e.srcUnit() instanceof AssignStmt) {
AssignStmt as = (AssignStmt) e.srcUnit();
Node ret = tgtmpag.nodeFactory().caseRet();
ret = tgtmpag.parameterize(ret, e.tgtCtxt());
ret = ret.getReplacement();
Node lhs = srcmpag.nodeFactory().getNode(as.getLeftOp());
lhs = srcmpag.parameterize(lhs, e.srcCtxt());
lhs = lhs.getReplacement();
addEdge(ret, lhs);
pval = addInterproceduralAssignment(ret, lhs, e);
if (callAssigns != null) {
callAssigns.put(ie, pval);
callToMethod.put(ie, srcmpag.getMethod());
}
}
} else if (e.kind() == Kind.FINALIZE) {
Node srcThis = srcmpag.nodeFactory().caseThis();
srcThis = srcmpag.parameterize(srcThis, e.srcCtxt());
srcThis = srcThis.getReplacement();
Node tgtThis = tgtmpag.nodeFactory().caseThis();
tgtThis = tgtmpag.parameterize(tgtThis, e.tgtCtxt());
tgtThis = tgtThis.getReplacement();
addEdge(srcThis, tgtThis);
pval = addInterproceduralAssignment(srcThis, tgtThis, e);
} else if (e.kind() == Kind.NEWINSTANCE) {
Stmt s = (Stmt) e.srcUnit();
InstanceInvokeExpr iie = (InstanceInvokeExpr) s.getInvokeExpr();
Node cls = srcmpag.nodeFactory().getNode(iie.getBase());
cls = srcmpag.parameterize(cls, e.srcCtxt());
cls = cls.getReplacement();
Node newObject = nodeFactory.caseNewInstance((VarNode) cls);
Node initThis = tgtmpag.nodeFactory().caseThis();
initThis = tgtmpag.parameterize(initThis, e.tgtCtxt());
initThis = initThis.getReplacement();
addEdge(newObject, initThis);
if (s instanceof AssignStmt) {
AssignStmt as = (AssignStmt) s;
Node asLHS = srcmpag.nodeFactory().getNode(as.getLeftOp());
asLHS = srcmpag.parameterize(asLHS, e.srcCtxt());
asLHS = asLHS.getReplacement();
addEdge(newObject, asLHS);
}
pval = addInterproceduralAssignment(newObject, initThis, e);
if (callAssigns != null) {
callAssigns.put(s.getInvokeExpr(), pval);
callToMethod.put(s.getInvokeExpr(), srcmpag.getMethod());
}
} else if (e.kind() == Kind.REFL_INVOKE) {
// Flow (1) from first parameter of invoke(..) invocation
// to this of target, (2) from the contents of the second (array)
// parameter
// to all parameters of the target, and (3) from return of target to
// the
// return of invoke(..)
// (1)
InvokeExpr ie = e.srcStmt().getInvokeExpr();
Value arg0 = ie.getArg(0);
// if "null" is passed in, omit the edge
if (arg0 != NullConstant.v()) {
Node parm0 = srcmpag.nodeFactory().getNode(arg0);
parm0 = srcmpag.parameterize(parm0, e.srcCtxt());
parm0 = parm0.getReplacement();
Node thiz = tgtmpag.nodeFactory().caseThis();
thiz = tgtmpag.parameterize(thiz, e.tgtCtxt());
thiz = thiz.getReplacement();
addEdge(parm0, thiz);
pval = addInterproceduralAssignment(parm0, thiz, e);
if (callAssigns != null) {
callAssigns.put(ie, pval);
callToMethod.put(ie, srcmpag.getMethod());
}
}
// (2)
Value arg1 = ie.getArg(1);
SootMethod tgt = e.getTgt().method();
// if "null" is passed in, or target has no parameters, omit the
// edge
if (arg1 != NullConstant.v() && tgt.getParameterCount() > 0) {
Node parm1 = srcmpag.nodeFactory().getNode(arg1);
parm1 = srcmpag.parameterize(parm1, e.srcCtxt());
parm1 = parm1.getReplacement();
FieldRefNode parm1contents = makeFieldRefNode((VarNode) parm1, ArrayElement.v());
for (int i = 0; i < tgt.getParameterCount(); i++) {
// if no reference type, create no edge
if (!(tgt.getParameterType(i) instanceof RefLikeType)) {
continue;
}
Node tgtParmI = tgtmpag.nodeFactory().caseParm(i);
tgtParmI = tgtmpag.parameterize(tgtParmI, e.tgtCtxt());
tgtParmI = tgtParmI.getReplacement();
addEdge(parm1contents, tgtParmI);
pval = addInterproceduralAssignment(parm1contents, tgtParmI, e);
if (callAssigns != null) {
callAssigns.put(ie, pval);
}
}
}
// (3)
// only create return edge if we are actually assigning the return
// value and
// the return type of the callee is actually a reference type
if (e.srcUnit() instanceof AssignStmt && (tgt.getReturnType() instanceof RefLikeType)) {
AssignStmt as = (AssignStmt) e.srcUnit();
Node ret = tgtmpag.nodeFactory().caseRet();
ret = tgtmpag.parameterize(ret, e.tgtCtxt());
ret = ret.getReplacement();
Node lhs = srcmpag.nodeFactory().getNode(as.getLeftOp());
lhs = srcmpag.parameterize(lhs, e.srcCtxt());
lhs = lhs.getReplacement();
addEdge(ret, lhs);
pval = addInterproceduralAssignment(ret, lhs, e);
if (callAssigns != null) {
callAssigns.put(ie, pval);
}
}
} else if (e.kind() == Kind.REFL_CLASS_NEWINSTANCE || e.kind() == Kind.REFL_CONSTR_NEWINSTANCE) {
// (1) create a fresh node for the new object
// (2) create edge from this object to "this" of the constructor
// (3) if this is a call to Constructor.newInstance and not
// Class.newInstance,
// create edges passing the contents of the arguments array of the
// call
// to all possible parameters of the target
// (4) if we are inside an assign statement,
// assign the fresh object from (1) to the LHS of the assign
// statement
Stmt s = (Stmt) e.srcUnit();
InstanceInvokeExpr iie = (InstanceInvokeExpr) s.getInvokeExpr();
// (1)
Node cls = srcmpag.nodeFactory().getNode(iie.getBase());
cls = srcmpag.parameterize(cls, e.srcCtxt());
cls = cls.getReplacement();
if (cls instanceof ContextVarNode) {
cls = findLocalVarNode(((VarNode) cls).getVariable());
}
VarNode newObject = makeGlobalVarNode(cls, RefType.v("java.lang.Object"));
SootClass tgtClass = e.getTgt().method().getDeclaringClass();
RefType tgtType = tgtClass.getType();
AllocNode site = makeAllocNode(new Pair<Node, SootClass>(cls, tgtClass), tgtType, null);
addEdge(site, newObject);
// (2)
Node initThis = tgtmpag.nodeFactory().caseThis();
initThis = tgtmpag.parameterize(initThis, e.tgtCtxt());
initThis = initThis.getReplacement();
addEdge(newObject, initThis);
addInterproceduralAssignment(newObject, initThis, e);
// (3)
if (e.kind() == Kind.REFL_CONSTR_NEWINSTANCE) {
Value arg = iie.getArg(0);
SootMethod tgt = e.getTgt().method();
// if "null" is passed in, or target has no parameters, omit the
// edge
if (arg != NullConstant.v() && tgt.getParameterCount() > 0) {
Node parm0 = srcmpag.nodeFactory().getNode(arg);
parm0 = srcmpag.parameterize(parm0, e.srcCtxt());
parm0 = parm0.getReplacement();
FieldRefNode parm1contents = makeFieldRefNode((VarNode) parm0, ArrayElement.v());
for (int i = 0; i < tgt.getParameterCount(); i++) {
// if no reference type, create no edge
if (!(tgt.getParameterType(i) instanceof RefLikeType)) {
continue;
}
Node tgtParmI = tgtmpag.nodeFactory().caseParm(i);
tgtParmI = tgtmpag.parameterize(tgtParmI, e.tgtCtxt());
tgtParmI = tgtParmI.getReplacement();
addEdge(parm1contents, tgtParmI);
pval = addInterproceduralAssignment(parm1contents, tgtParmI, e);
if (callAssigns != null) {
callAssigns.put(iie, pval);
}
}
}
}
// (4)
if (s instanceof AssignStmt) {
AssignStmt as = (AssignStmt) s;
Node asLHS = srcmpag.nodeFactory().getNode(as.getLeftOp());
asLHS = srcmpag.parameterize(asLHS, e.srcCtxt());
asLHS = asLHS.getReplacement();
addEdge(newObject, asLHS);
}
pval = addInterproceduralAssignment(newObject, initThis, e);
if (callAssigns != null) {
callAssigns.put(s.getInvokeExpr(), pval);
callToMethod.put(s.getInvokeExpr(), srcmpag.getMethod());
}
} else {
throw new RuntimeException("Unhandled edge " + e);
}
}
/**
* Adds method target as a possible target of the invoke expression in s. If target is null, only creates the nodes for the
* call site, without actually connecting them to any target method.
**/
public void addCallTarget(MethodPAG srcmpag, MethodPAG tgtmpag, Stmt s, Context srcContext, Context tgtContext, Edge e) {
addCallTarget(srcmpag, tgtmpag, s, srcContext, tgtContext, e, true);
}
/**
* Adds method target as a possible target of the invoke expression in s. If target is null, only creates the nodes for the
* call site, without actually connecting them to any target method.
**/
public void addCallTarget(MethodPAG srcmpag, MethodPAG tgtmpag, Stmt s, Context srcContext, Context tgtContext, Edge e,
boolean propagateReturn) {
MethodNodeFactory srcnf = srcmpag.nodeFactory();
MethodNodeFactory tgtnf = tgtmpag.nodeFactory();
InvokeExpr ie = s.getInvokeExpr();
int numArgs = ie.getArgCount();
for (int i = 0; i < numArgs; i++) {
Value arg = ie.getArg(i);
if (!(arg.getType() instanceof RefLikeType)) {
continue;
}
if (arg instanceof NullConstant) {
continue;
}
Node argNode = srcnf.getNode(arg);
argNode = srcmpag.parameterize(argNode, srcContext);
argNode = argNode.getReplacement();
// target method's argument number may be less than source method, i.e. AsyncTask.execute(1) vs onPreExecute(0)
// check for param return here, or NPE in paramTypes will be thrown
Node parm = tgtnf.caseParm(i);
if (parm == null) {
continue;
}
parm = tgtmpag.parameterize(parm, tgtContext);
parm = parm.getReplacement();
addEdge(argNode, parm);
Pair<Node, Node> pval = addInterproceduralAssignment(argNode, parm, e);
if (callAssigns != null) {
callAssigns.put(ie, pval);
callToMethod.put(ie, srcmpag.getMethod());
}
}
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
Node baseNode = srcnf.getNode(iie.getBase());
baseNode = srcmpag.parameterize(baseNode, srcContext);
baseNode = baseNode.getReplacement();
Node thisRef = tgtnf.caseThis();
thisRef = tgtmpag.parameterize(thisRef, tgtContext);
thisRef = thisRef.getReplacement();
addEdge(baseNode, thisRef);
Pair<Node, Node> pval = addInterproceduralAssignment(baseNode, thisRef, e);
if (callAssigns != null) {
boolean virtualCall = !callAssigns.put(ie, pval);
callToMethod.put(ie, srcmpag.getMethod());
if (virtualCall) {
virtualCallsToReceivers.putIfAbsent(ie, baseNode);
}
}
}
if (propagateReturn && s instanceof AssignStmt) {
Value dest = ((AssignStmt) s).getLeftOp();
if (dest.getType() instanceof RefLikeType && !(dest instanceof NullConstant)) {
Node destNode = srcnf.getNode(dest);
destNode = srcmpag.parameterize(destNode, srcContext);
destNode = destNode.getReplacement();
Node retNode = tgtnf.caseRet();
retNode = tgtmpag.parameterize(retNode, tgtContext);
retNode = retNode.getReplacement();
addEdge(retNode, destNode);
Pair<Node, Node> pval = addInterproceduralAssignment(retNode, destNode, e);
if (callAssigns != null) {
callAssigns.put(ie, pval);
callToMethod.put(ie, srcmpag.getMethod());
}
}
}
}
/**
* Delete all the assignment edges.
*/
public void cleanPAG() {
simple.clear();
load.clear();
store.clear();
alloc.clear();
simpleInv.clear();
loadInv.clear();
storeInv.clear();
allocInv.clear();
}
/* End of package methods. */
protected SparkOptions opts;
protected CGOptions cgOpts;
protected ClientAccessibilityOracle accessibilityOracle = Scene.v().getClientAccessibilityOracle();
protected Map<VarNode, Object> simple = new HashMap<VarNode, Object>();
protected Map<FieldRefNode, Object> load = new HashMap<FieldRefNode, Object>();
protected Map<VarNode, Object> store = new HashMap<VarNode, Object>();
protected Map<AllocNode, Object> alloc = new HashMap<AllocNode, Object>();
protected Map<VarNode, Object> newInstance = new HashMap<VarNode, Object>();
protected Map<NewInstanceNode, Object> assignInstance = new HashMap<NewInstanceNode, Object>();
protected Map<VarNode, Object> simpleInv = new HashMap<VarNode, Object>();
protected Map<VarNode, Object> loadInv = new HashMap<VarNode, Object>();
protected Map<FieldRefNode, Object> storeInv = new HashMap<FieldRefNode, Object>();
protected Map<VarNode, Object> allocInv = new HashMap<VarNode, Object>();
protected Map<NewInstanceNode, Object> newInstanceInv = new HashMap<NewInstanceNode, Object>();
protected Map<VarNode, Object> assignInstanceInv = new HashMap<VarNode, Object>();
protected <K extends Node> boolean addToMap(Map<K, Object> m, K key, Node value) {
Object valueList = m.get(key);
if (valueList == null) {
m.put(key, valueList = new HashSet(4));
} else if (!(valueList instanceof Set)) {
Node[] ar = (Node[]) valueList;
HashSet<Node> vl = new HashSet<Node>(ar.length + 4);
m.put(key, vl);
for (Node element : ar) {
vl.add(element);
}
return vl.add(value);
}
return ((Set<Node>) valueList).add(value);
}
private boolean runGeomPTA = false;
protected MultiMap<Pair<Node, Node>, Edge> assign2edges = new HashMultiMap<>();
private final Map<Object, LocalVarNode> valToLocalVarNode = new HashMap<>(1000);
private final Map<Object, GlobalVarNode> valToGlobalVarNode = new HashMap<>(1000);
private final Map<Object, AllocNode> valToAllocNode = new HashMap<>(1000);
private final Table<Object, Type, AllocNode> valToReflAllocNode = HashBasedTable.create();
private OnFlyCallGraph ofcg;
private final ArrayList<VarNode> dereferences = new ArrayList<VarNode>();
protected TypeManager typeManager;
private final LargeNumberedMap<Local, LocalVarNode> localToNodeMap = new LargeNumberedMap<>(Scene.v().getLocalNumberer());
private final Map<Value, NewInstanceNode> newInstToNodeMap = new HashMap<>();
public int maxFinishNumber = 0;
private Map<Node, Tag> nodeToTag;
private final GlobalNodeFactory nodeFactory = new GlobalNodeFactory(this);
public GlobalNodeFactory nodeFactory() {
return nodeFactory;
}
public NativeMethodDriver nativeMethodDriver;
public HashMultiMap<InvokeExpr, Pair<Node, Node>> callAssigns;
public Map<InvokeExpr, SootMethod> callToMethod;
public Map<InvokeExpr, Node> virtualCallsToReceivers;
}
| 50,045
| 31.709804
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/PAG2HTML.java
|
package soot.jimple.spark.pag;
/*-
* #%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.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import soot.SootMethod;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
/**
* Dumps a pointer assignment graph to a html files.
*
* @author Ondrej Lhotak
*/
public class PAG2HTML {
public PAG2HTML(PAG pag, String output_dir) {
this.pag = pag;
this.output_dir = output_dir;
}
public void dump() {
for (Iterator vIt = pag.getVarNodeNumberer().iterator(); vIt.hasNext();) {
final VarNode v = (VarNode) vIt.next();
mergedNodes.put(v.getReplacement(), v);
if (v instanceof LocalVarNode) {
SootMethod m = ((LocalVarNode) v).getMethod();
if (m != null) {
methodToNodes.put(m, v);
}
}
}
try {
JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(new File(output_dir, "pag.jar")));
for (Iterator vIt = mergedNodes.keySet().iterator(); vIt.hasNext();) {
final VarNode v = (VarNode) vIt.next();
dumpVarNode(v, jarOut);
}
for (Iterator mIt = methodToNodes.keySet().iterator(); mIt.hasNext();) {
final SootMethod m = (SootMethod) mIt.next();
dumpMethod(m, jarOut);
}
addSymLinks(pag.getVarNodeNumberer().iterator(), jarOut);
jarOut.close();
} catch (IOException e) {
throw new RuntimeException("Couldn't dump html" + e);
}
}
/* End of public methods. */
/* End of package methods. */
protected PAG pag;
protected String output_dir;
protected MultiMap mergedNodes = new HashMultiMap();
protected MultiMap methodToNodes = new HashMultiMap();
protected void dumpVarNode(VarNode v, JarOutputStream jarOut) throws IOException {
jarOut.putNextEntry(new ZipEntry("nodes/n" + v.getNumber() + ".html"));
final PrintWriter out = new PrintWriter(jarOut);
out.println("<html>");
out.println("Green node for:");
out.println(varNodeReps(v));
out.println("Declared type: " + v.getType());
out.println("<hr>Reaching blue nodes:");
out.println("<ul>");
v.getP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
out.println("<li>" + htmlify(n.toString()));
}
});
out.println("</ul>");
out.println("<hr>Outgoing edges:");
Node[] succs = pag.simpleLookup(v);
for (Node element : succs) {
VarNode succ = (VarNode) element;
out.println(varNodeReps(succ));
}
out.println("<hr>Incoming edges: ");
succs = pag.simpleInvLookup(v);
for (Node element : succs) {
VarNode succ = (VarNode) element;
out.println(varNodeReps(succ));
}
out.println("</html>");
out.flush();
}
protected String varNodeReps(VarNode v) {
StringBuffer ret = new StringBuffer();
ret.append("<ul>\n");
for (Iterator vvIt = mergedNodes.get(v).iterator(); vvIt.hasNext();) {
final VarNode vv = (VarNode) vvIt.next();
ret.append(varNode("", vv));
}
ret.append("</ul>\n");
return ret.toString();
}
protected String varNode(String dirPrefix, VarNode vv) {
StringBuffer ret = new StringBuffer();
ret.append("<li><a href=\"" + dirPrefix + "n" + vv.getNumber() + ".html\">");
if (vv.getVariable() != null) {
ret.append("" + htmlify(vv.getVariable().toString()));
}
ret.append("GlobalVarNode");
ret.append("</a><br>");
ret.append("<li>Context: ");
ret.append("" + (vv.context() == null ? "null" : htmlify(vv.context().toString())));
ret.append("</a><br>");
if (vv instanceof LocalVarNode) {
LocalVarNode lvn = (LocalVarNode) vv;
SootMethod m = lvn.getMethod();
if (m != null) {
ret.append("<a href=\"../" + toFileName(m.toString()) + ".html\">");
ret.append(htmlify(m.toString()) + "</a><br>");
}
}
ret.append(htmlify(vv.getType().toString()) + "\n");
return ret.toString();
}
protected static String htmlify(String s) {
StringBuffer b = new StringBuffer(s);
for (int i = 0; i < b.length(); i++) {
if (b.charAt(i) == '<') {
b.replace(i, i + 1, "<");
}
if (b.charAt(i) == '>') {
b.replace(i, i + 1, ">");
}
}
return b.toString();
}
protected void dumpMethod(SootMethod m, JarOutputStream jarOut) throws IOException {
jarOut.putNextEntry(new ZipEntry("" + toFileName(m.toString()) + ".html"));
final PrintWriter out = new PrintWriter(jarOut);
out.println("<html>");
out.println("This is method " + htmlify(m.toString()) + "<hr>");
for (Iterator it = methodToNodes.get(m).iterator(); it.hasNext();) {
out.println(varNode("nodes/", (VarNode) it.next()));
}
out.println("</html>");
out.flush();
}
protected void addSymLinks(Iterator nodes, JarOutputStream jarOut) throws IOException {
jarOut.putNextEntry(new ZipEntry("symlinks.sh"));
final PrintWriter out = new PrintWriter(jarOut);
out.println("#!/bin/sh");
while (nodes.hasNext()) {
VarNode v = (VarNode) nodes.next();
VarNode rep = (VarNode) v.getReplacement();
if (v != rep) {
out.println("ln -s n" + rep.getNumber() + ".html n" + v.getNumber() + ".html");
}
}
out.flush();
}
protected String toFileName(String s) {
StringBuffer ret = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '<') {
ret.append('{');
} else if (c == '>') {
ret.append('}');
} else {
ret.append(c);
}
}
return ret.toString();
}
}
| 6,560
| 30.094787
| 106
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/PAGDumper.java
|
package soot.jimple.spark.pag;
/*-
* #%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.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.spark.solver.TopoSorter;
/**
* Dumps a pointer assignment graph to a file.
*
* @author Ondrej Lhotak
*/
public class PAGDumper {
private static final Logger logger = LoggerFactory.getLogger(PAGDumper.class);
public PAGDumper(PAG pag, String output_dir) {
this.pag = pag;
this.output_dir = output_dir;
}
public void dumpPointsToSets() {
try {
final PrintWriter file = new PrintWriter(new FileOutputStream(new File(output_dir, "solution")));
file.println("Solution:");
for (Iterator vnIt = pag.getVarNodeNumberer().iterator(); vnIt.hasNext();) {
final VarNode vn = (VarNode) vnIt.next();
if (vn.getReplacement() != vn) {
continue;
}
PointsToSetInternal p2set = vn.getP2Set();
if (p2set == null) {
continue;
}
p2set.forall(new P2SetVisitor() {
public final void visit(Node n) {
try {
dumpNode(vn, file);
file.print(" ");
dumpNode(n, file);
file.println("");
} catch (IOException e) {
throw new RuntimeException("Couldn't dump solution." + e);
}
}
});
}
file.close();
} catch (IOException e) {
throw new RuntimeException("Couldn't dump solution." + e);
}
}
public void dump() {
try {
PrintWriter file = new PrintWriter(new FileOutputStream(new File(output_dir, "pag")));
if (pag.getOpts().topo_sort()) {
new TopoSorter(pag, false).sort();
}
file.println("Allocations:");
for (Object object : pag.allocSources()) {
final AllocNode n = (AllocNode) object;
if (n.getReplacement() != n) {
continue;
}
Node[] succs = pag.allocLookup(n);
for (Node element0 : succs) {
dumpNode(n, file);
file.print(" ");
dumpNode(element0, file);
file.println("");
}
}
file.println("Assignments:");
for (Object object : pag.simpleSources()) {
final VarNode n = (VarNode) object;
if (n.getReplacement() != n) {
continue;
}
Node[] succs = pag.simpleLookup(n);
for (Node element0 : succs) {
dumpNode(n, file);
file.print(" ");
dumpNode(element0, file);
file.println("");
}
}
file.println("Loads:");
for (Object object : pag.loadSources()) {
final FieldRefNode n = (FieldRefNode) object;
Node[] succs = pag.loadLookup(n);
for (Node element0 : succs) {
dumpNode(n, file);
file.print(" ");
dumpNode(element0, file);
file.println("");
}
}
file.println("Stores:");
for (Object object : pag.storeSources()) {
final VarNode n = (VarNode) object;
if (n.getReplacement() != n) {
continue;
}
Node[] succs = pag.storeLookup(n);
for (Node element0 : succs) {
dumpNode(n, file);
file.print(" ");
dumpNode(element0, file);
file.println("");
}
}
if (pag.getOpts().dump_types()) {
dumpTypes(file);
}
file.close();
} catch (IOException e) {
throw new RuntimeException("Couldn't dump PAG." + e);
}
}
/* End of public methods. */
/* End of package methods. */
protected PAG pag;
protected String output_dir;
protected int fieldNum = 0;
protected HashMap<SparkField, Integer> fieldMap = new HashMap<SparkField, Integer>();
protected ObjectNumberer root = new ObjectNumberer(null, 0);
protected void dumpTypes(PrintWriter file) throws IOException {
HashSet<Type> declaredTypes = new HashSet<Type>();
HashSet<Type> actualTypes = new HashSet<Type>();
HashSet<SparkField> allFields = new HashSet<SparkField>();
for (Iterator nIt = pag.getVarNodeNumberer().iterator(); nIt.hasNext();) {
final Node n = (Node) nIt.next();
Type t = n.getType();
if (t != null) {
declaredTypes.add(t);
}
}
for (Object object : pag.loadSources()) {
final Node n = (Node) object;
if (n.getReplacement() != n) {
continue;
}
Type t = n.getType();
if (t != null) {
declaredTypes.add(t);
}
allFields.add(((FieldRefNode) n).getField());
}
for (Object object : pag.storeInvSources()) {
final Node n = (Node) object;
if (n.getReplacement() != n) {
continue;
}
Type t = n.getType();
if (t != null) {
declaredTypes.add(t);
}
allFields.add(((FieldRefNode) n).getField());
}
for (Object object : pag.allocSources()) {
final Node n = (Node) object;
if (n.getReplacement() != n) {
continue;
}
Type t = n.getType();
if (t != null) {
actualTypes.add(t);
}
}
HashMap<Type, Integer> typeToInt = new HashMap<Type, Integer>();
int nextint = 1;
for (Type type : declaredTypes) {
typeToInt.put(type, new Integer(nextint++));
}
for (Type t : actualTypes) {
if (!typeToInt.containsKey(t)) {
typeToInt.put(t, new Integer(nextint++));
}
}
file.println("Declared Types:");
for (Type declType : declaredTypes) {
for (Type actType : actualTypes) {
if (pag.getTypeManager().castNeverFails(actType, declType)) {
file.println("" + typeToInt.get(declType) + " " + typeToInt.get(actType));
}
}
}
file.println("Allocation Types:");
for (Object object : pag.allocSources()) {
final Node n = (Node) object;
if (n.getReplacement() != n) {
continue;
}
Type t = n.getType();
dumpNode(n, file);
if (t == null) {
throw new RuntimeException("allocnode with null type");
// file.println( " 0" );
} else {
file.println(" " + typeToInt.get(t));
}
}
file.println("Variable Types:");
for (Iterator nIt = pag.getVarNodeNumberer().iterator(); nIt.hasNext();) {
final Node n = (Node) nIt.next();
if (n.getReplacement() != n) {
continue;
}
Type t = n.getType();
dumpNode(n, file);
if (t == null) {
file.println(" 0");
} else {
file.println(" " + typeToInt.get(t));
}
}
}
protected int fieldToNum(SparkField f) {
Integer ret = fieldMap.get(f);
if (ret == null) {
ret = new Integer(++fieldNum);
fieldMap.put(f, ret);
}
return ret.intValue();
}
protected void dumpNode(Node n, PrintWriter out) throws IOException {
if (n.getReplacement() != n) {
throw new RuntimeException("Attempt to dump collapsed node.");
}
if (n instanceof FieldRefNode) {
FieldRefNode fn = (FieldRefNode) n;
dumpNode(fn.getBase(), out);
out.print(" " + fieldToNum(fn.getField()));
} else if (pag.getOpts().class_method_var() && n instanceof VarNode) {
VarNode vn = (VarNode) n;
SootMethod m = null;
if (vn instanceof LocalVarNode) {
m = ((LocalVarNode) vn).getMethod();
}
SootClass c = null;
if (m != null) {
c = m.getDeclaringClass();
}
ObjectNumberer cl = root.findOrAdd(c);
ObjectNumberer me = cl.findOrAdd(m);
ObjectNumberer vr = me.findOrAdd(vn);
/*
* if( vr.num > 256 ) { logger.debug(""+ "Var with num: "+vr.num+" is "+vn+ " in method "+m+" in class "+c ); }
*/
out.print("" + cl.num + " " + me.num + " " + vr.num);
} else if (pag.getOpts().topo_sort() && n instanceof VarNode) {
out.print("" + ((VarNode) n).finishingNumber);
} else {
out.print("" + n.getNumber());
}
}
class ObjectNumberer {
Object o = null;
int num = 0;
int nextChildNum = 1;
HashMap<Object, ObjectNumberer> children = null;
ObjectNumberer(Object o, int num) {
this.o = o;
this.num = num;
}
ObjectNumberer findOrAdd(Object child) {
if (children == null) {
children = new HashMap<Object, ObjectNumberer>();
}
ObjectNumberer ret = children.get(child);
if (ret == null) {
ret = new ObjectNumberer(child, nextChildNum++);
children.put(child, ret);
}
return ret;
}
}
}
| 9,595
| 28.526154
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/PagToDotDumper.java
|
package soot.jimple.spark.pag;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Manu Sridharan
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootField;
import soot.SootMethod;
import soot.jimple.spark.ondemand.genericutil.Predicate;
import soot.jimple.spark.sets.P2SetVisitor;
/**
* Utilities for dumping dot representations of parts of a {@link PAG}.
*
* @author msridhar
*
*/
public class PagToDotDumper {
private static final Logger logger = LoggerFactory.getLogger(PagToDotDumper.class);
public static final int TRACE_MAX_LVL = 99;
private PAG pag;
private HashMap<Node, Node[]> vmatches;
private HashMap<Node, Node[]> invVmatches;
public PagToDotDumper(PAG pag) {
this.pag = pag;
this.vmatches = new HashMap<Node, Node[]>();
this.invVmatches = new HashMap<Node, Node[]>();
}
/**
* Build vmatchEdges and store them in vmatches field
*
*/
private void buildVmatchEdges() {
// for each store and load pair
for (Iterator iter = pag.loadSourcesIterator(); iter.hasNext();) {
final FieldRefNode frn1 = (FieldRefNode) iter.next();
for (Iterator iter2 = pag.storeInvSourcesIterator(); iter2.hasNext();) {
final FieldRefNode frn2 = (FieldRefNode) iter2.next();
VarNode base1 = frn1.getBase();
VarNode base2 = frn2.getBase();
// debug(frn1, frn2, base1, base2);
// if they store & load the same field
if (frn1.getField().equals(frn2.getField())) {
if (base1.getP2Set().hasNonEmptyIntersection(base2.getP2Set())) {
// System.err.println("srcs:");
Node[] src = pag.loadLookup(frn1);
Node[] dst = pag.storeInvLookup(frn2);
for (int i = 0; i < src.length; i++) {
// System.err.println(src[i]);
vmatches.put(src[i], dst);
}
// System.err.println("dst:");
for (int i = 0; i < dst.length; i++) {
// System.err.println(dst[i]);
invVmatches.put(dst[i], src);
}
}
}
}
}
}
/**
* @param frn1
* @param frn2
* @param base1
* @param base2
* @param lvn
* @param mName
* TODO
*/
@SuppressWarnings("unused")
private void debug(final FieldRefNode frn1, final FieldRefNode frn2, VarNode base1, VarNode base2) {
if (base1 instanceof LocalVarNode && base2 instanceof LocalVarNode) {
LocalVarNode lvn1 = (LocalVarNode) base1;
LocalVarNode lvn2 = (LocalVarNode) base2;
if (lvn1.getMethod().getDeclaringClass().getName().equals("java.util.Hashtable$ValueCollection")
&& lvn1.getMethod().getName().equals("contains")
&& lvn2.getMethod().getDeclaringClass().getName().equals("java.util.Hashtable$ValueCollection")
&& lvn2.getMethod().getName().equals("<init>")) {
System.err.println("Method: " + lvn1.getMethod().getName());
System.err.println(makeLabel(frn1));
System.err.println("Base: " + base1.getVariable());
System.err.println("Field: " + frn1.getField());
System.err.println(makeLabel(frn2));
System.err.println("Base: " + base2.getVariable());
System.err.println("Field: " + frn2.getField());
if (frn1.getField().equals(frn2.getField())) {
System.err.println("field match");
if (base1.getP2Set().hasNonEmptyIntersection(base2.getP2Set())) {
System.err.println("non empty");
} else {
System.err.println("b1: " + base1.getP2Set());
System.err.println("b2: " + base2.getP2Set());
}
}
}
}
}
/**
* @param lvNode
* @param node
* @return
*/
private static String translateEdge(Node src, Node dest, String label) {
return makeNodeName(src) + " -> " + makeNodeName(dest) + " [label=\"" + label + "\"];";
}
private final static Predicate<Node> emptyP2SetPred = new Predicate<Node>() {
public boolean test(Node n) {
return !(n instanceof AllocNode) && n.getP2Set().isEmpty();
}
};
/**
* Generate a node declaration for a dot file.
*
* @param node
* the node
* @param p
* a predicate over nodes, which, if true, will cause the node to appear red
* @return the appropriate {@link String} for the dot file
*/
public static String makeDotNodeLabel(Node n, Predicate<Node> p) {
String color = "";
String label;
if (p.test(n)) {
color = ", color=red";
}
if (n instanceof LocalVarNode) {
label = makeLabel((LocalVarNode) n);
} else if (n instanceof AllocNode) {
label = makeLabel((AllocNode) n);
} else if (n instanceof FieldRefNode) {
label = makeLabel((FieldRefNode) n);
} else {
label = n.toString();
}
return makeNodeName(n) + "[label=\"" + label + "\"" + color + "];";
}
private static String translateLabel(Node n) {
return makeDotNodeLabel(n, emptyP2SetPred);
}
/**
* @param lvNode
* @param cName
* @param mName
* @return
*/
private boolean isDefinedIn(LocalVarNode lvNode, String cName, String mName) {
return lvNode.getMethod() != null && lvNode.getMethod().getDeclaringClass().getName().equals(cName)
&& lvNode.getMethod().getName().equals(mName);
}
private void printOneNode(VarNode node) {
PrintStream ps = System.err;
ps.println(makeLabel(node));
Node[] succs = pag.simpleInvLookup(node);
ps.println("assign");
ps.println("======");
for (int i = 0; i < succs.length; i++) {
ps.println(succs[i]);
}
succs = pag.allocInvLookup(node);
ps.println("new");
ps.println("======");
for (int i = 0; i < succs.length; i++) {
ps.println(succs[i]);
}
succs = pag.loadInvLookup(node);
ps.println("load");
ps.println("======");
for (int i = 0; i < succs.length; i++) {
ps.println(succs[i]);
}
succs = pag.storeLookup(node);
ps.println("store");
ps.println("======");
for (int i = 0; i < succs.length; i++) {
ps.println(succs[i]);
}
}
/**
* dumps the points-to sets for all locals in a method in a dot representation. The graph has edges from each local to all
* {@link AllocNode}s in its points-to set
*
* @param fName
* a name for the output file
* @param mName
* the name of the method whose locals should be dumped
* @throws FileNotFoundException
* if unable to output to specified file
*/
public void dumpP2SetsForLocals(String fName, String mName) throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream(new File(fName));
PrintStream ps = new PrintStream(fos);
ps.println("digraph G {");
dumpLocalP2Set(mName, ps);
ps.print("}");
}
private void dumpLocalP2Set(String mName, final PrintStream ps) {
for (Iterator iter = pag.getVarNodeNumberer().iterator(); iter.hasNext();) {
VarNode vNode = (VarNode) iter.next();
if (vNode instanceof LocalVarNode) {
final LocalVarNode lvNode = (LocalVarNode) vNode;
if (lvNode.getMethod() != null && lvNode.getMethod().getName().equals(mName)) {
ps.println("\t" + makeNodeName(lvNode) + " [label=\"" + makeLabel(lvNode) + "\"];");
lvNode.getP2Set().forall(new P2SetToDotPrinter(lvNode, ps));
}
}
}
}
/**
* Dump the PAG for some method in the program in dot format
*
* @param fName
* The filename for the output
* @param cName
* The name of the declaring class for the method
* @param mName
* The name of the method
* @throws FileNotFoundException
* if output file cannot be written
*/
public void dumpPAGForMethod(String fName, String cName, String mName) throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream(new File(fName));
PrintStream ps = new PrintStream(fos);
ps.println("digraph G {");
ps.println("\trankdir=LR;");
dumpLocalPAG(cName, mName, ps);
ps.print("}");
try {
fos.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
ps.close();
}
private void dumpLocalPAG(String cName, String mName, final PrintStream ps) {
// this.queryMethod = mName;
// iterate over all variable nodes
for (Iterator iter = pag.getVarNodeNumberer().iterator(); iter.hasNext();) {
final Node node = (Node) iter.next();
if (!(node instanceof LocalVarNode)) {
continue;
}
final LocalVarNode lvNode = (LocalVarNode) node;
// nodes that is defined in the specified class and method
if (isDefinedIn(lvNode, cName, mName)) {
dumpForwardReachableNodesFrom(lvNode, ps);
}
}
// for (Iterator iter = pag.getFieldRefNodeNumberer().iterator(); iter
// .hasNext();) {
// final FieldRefNode frNode = (FieldRefNode) iter.next();
//
// if (frNode.getBase().)
// Node[] succs = pag.storeInvLookup(frNode);
// for (int i = 0; i < succs.length; i++) {
// ps.println("\t" + translateLabel(succs[i]));
// // print edge
// ps.println("\t" + translateEdge(frNode, succs[i], "store"));
// }
// }
}
/**
* @param lvNode
* @param ps
*/
private void dumpForwardReachableNodesFrom(final LocalVarNode lvNode, final PrintStream ps) {
ps.println("\t" + translateLabel(lvNode));
Node[] succs = pag.simpleInvLookup(lvNode);
for (int i = 0; i < succs.length; i++) {
ps.println("\t" + translateLabel(succs[i]));
// print edge
ps.println("\t" + translateEdge(lvNode, succs[i], "assign"));
}
succs = pag.allocInvLookup(lvNode);
for (int i = 0; i < succs.length; i++) {
ps.println("\t" + translateLabel(succs[i]));
// print edge
ps.println("\t" + translateEdge(lvNode, succs[i], "new"));
}
succs = pag.loadInvLookup(lvNode);
for (int i = 0; i < succs.length; i++) {
final FieldRefNode frNode = (FieldRefNode) succs[i];
ps.println("\t" + translateLabel(frNode));
ps.println("\t" + translateLabel(frNode.getBase()));
// print edge
ps.println("\t" + translateEdge(lvNode, frNode, "load"));
ps.println("\t" + translateEdge(frNode, frNode.getBase(), "getBase"));
}
succs = pag.storeLookup(lvNode);
for (int i = 0; i < succs.length; i++) {
final FieldRefNode frNode = (FieldRefNode) succs[i];
ps.println("\t" + translateLabel(frNode));
ps.println("\t" + translateLabel(frNode.getBase()));
// print edge
ps.println("\t" + translateEdge(frNode, lvNode, "store"));
ps.println("\t" + translateEdge(frNode, frNode.getBase(), "getBase"));
}
}
public void traceNode(int id) {
buildVmatchEdges();
String fName = "trace." + id + ".dot";
try {
FileOutputStream fos = new FileOutputStream(new File(fName));
PrintStream ps = new PrintStream(fos);
ps.println("digraph G {");
// iterate over all variable nodes
for (Iterator iter = pag.getVarNodeNumberer().iterator(); iter.hasNext();) {
final VarNode n = (VarNode) iter.next();
if (n.getNumber() == id) {
LocalVarNode lvn = (LocalVarNode) n;
printOneNode(lvn);
trace(lvn, ps, new HashSet<Node>(), TRACE_MAX_LVL);
}
}
ps.print("}");
ps.close();
fos.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
public void traceNode(String cName, String mName, String varName) {
String mName2 = mName;
if (mName.indexOf('<') == 0) {
mName2 = mName.substring(1, mName.length() - 1);
}
traceLocalVarNode("trace." + cName + "." + mName2 + "." + varName + ".dot", cName, mName, varName);
}
public void traceLocalVarNode(String fName, String cName, String mName, String varName) {
PrintStream ps;
buildVmatchEdges();
try {
FileOutputStream fos = new FileOutputStream(new File(fName));
ps = new PrintStream(fos);
ps.println("digraph G {");
// iterate over all variable nodes
for (Iterator iter = pag.getVarNodeNumberer().iterator(); iter.hasNext();) {
final VarNode n = (VarNode) iter.next();
if (!(n instanceof LocalVarNode)) {
continue;
}
LocalVarNode lvn = (LocalVarNode) n;
// HACK
if (lvn.getMethod() == null) {
continue;
}
if (isDefinedIn(lvn, cName, mName)) {
// System.err.println("class match");
// System.err.println(lvn.getVariable());
if (lvn.getVariable().toString().equals(varName)) {
// System.err.println(lvn);
trace(lvn, ps, new HashSet<Node>(), 10);
}
}
}
ps.print("}");
ps.close();
fos.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
/**
*
* Do a DFS traversal
*
* @param name
* @param name2
* @param ps2
*/
private void trace(VarNode node, PrintStream ps, HashSet<Node> visitedNodes, int level) {
if (level < 1) {
return;
}
ps.println("\t" + translateLabel(node));
// // assign value to others
// Node[] preds = pag.storeLookup(node);
// for (int i = 0; i < preds.length; i++) {
// if (visitedNodes.contains(preds[i]))
// continue;
// ps.println("\t" + translateLabel(preds[i]));
// // print edge
// ps.println("\t" + translateEdge(preds[i], node, "store"));
// visitedNodes.add(preds[i]);
// // trace((VarNode) preds[i], ps, visitedNodes);
// }
// get other's value
Node[] succs = pag.simpleInvLookup(node);
for (int i = 0; i < succs.length; i++) {
if (visitedNodes.contains(succs[i])) {
continue;
}
ps.println("\t" + translateLabel(succs[i]));
// print edge
ps.println("\t" + translateEdge(node, succs[i], "assign"));
visitedNodes.add(succs[i]);
trace((VarNode) succs[i], ps, visitedNodes, level - 1);
}
succs = pag.allocInvLookup(node);
for (int i = 0; i < succs.length; i++) {
if (visitedNodes.contains(succs[i])) {
continue;
}
ps.println("\t" + translateLabel(succs[i]));
// print edge
ps.println("\t" + translateEdge(node, succs[i], "new"));
}
succs = vmatches.get(node);
if (succs != null) {
// System.err.println(succs.length);
for (int i = 0; i < succs.length; i++) {
// System.err.println(succs[i]);
if (visitedNodes.contains(succs[i])) {
continue;
}
ps.println("\t" + translateLabel(succs[i]));
// print edge
ps.println("\t" + translateEdge(node, succs[i], "vmatch"));
trace((VarNode) succs[i], ps, visitedNodes, level - 1);
}
}
}
public static String makeNodeName(Node n) {
return "node_" + n.getNumber();
}
public static String makeLabel(AllocNode n) {
return n.getNewExpr().toString();
}
public static String makeLabel(LocalVarNode n) {
SootMethod sm = n.getMethod();
return "LV " + n.getVariable().toString() + " " + n.getNumber() + "\\n" + sm.getDeclaringClass() + "\\n" + sm.getName();
}
/**
* @param node
* @return
*/
public static String makeLabel(FieldRefNode node) {
if (node.getField() instanceof SootField) {
final SootField sf = (SootField) node.getField();
return "FNR " + makeLabel(node.getBase()) + "." + sf.getName();
} else {
return "FNR " + makeLabel(node.getBase()) + "." + node.getField();
}
}
/**
* @param base
* @return
*/
public static String makeLabel(VarNode base) {
if (base instanceof LocalVarNode) {
return makeLabel((LocalVarNode) base);
} else {
return base.toString();
}
}
class P2SetToDotPrinter extends P2SetVisitor {
private final Node curNode;
private final PrintStream ps;
P2SetToDotPrinter(Node curNode, PrintStream ps) {
this.curNode = curNode;
this.ps = ps;
}
public void visit(Node n) {
ps.println("\t" + makeNodeName(n) + " [label=\"" + makeLabel((AllocNode) n) + "\"];");
ps.print("\t" + makeNodeName(curNode) + " -> ");
ps.println(makeNodeName(n) + ";");
}
}
}
| 17,303
| 28.378608
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/Parm.java
|
package soot.jimple.spark.pag;
/*-
* #%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 soot.G;
import soot.PointsToAnalysis;
import soot.Scene;
import soot.SootMethod;
import soot.Type;
import soot.toolkits.scalar.Pair;
/**
* Represents a method parameter.
*
* @author Ondrej Lhotak
*/
public class Parm implements SparkField {
private final int index;
private final SootMethod method;
private Parm(SootMethod m, int i) {
index = i;
method = m;
Scene.v().getFieldNumberer().add(this);
}
public static Parm v(SootMethod m, int index) {
Pair<SootMethod, Integer> p = new Pair<SootMethod, Integer>(m, new Integer(index));
Parm ret = (Parm) G.v().Parm_pairToElement.get(p);
if (ret == null) {
G.v().Parm_pairToElement.put(p, ret = new Parm(m, index));
}
return ret;
}
public static final void delete() {
G.v().Parm_pairToElement = null;
}
public String toString() {
return "Parm " + index + " to " + method;
}
public final int getNumber() {
return number;
}
public final void setNumber(int number) {
this.number = number;
}
public int getIndex() {
return index;
}
public Type getType() {
if (index == PointsToAnalysis.RETURN_NODE) {
return method.getReturnType();
}
return method.getParameterType(index);
}
private int number = 0;
}
| 2,109
| 23.534884
| 87
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/SparkField.java
|
package soot.jimple.spark.pag;
/*-
* #%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 soot.Type;
import soot.util.Numberable;
/**
* Represents a field.
*
* @author Ondrej Lhotak
*/
public interface SparkField extends Numberable {
public Type getType();
}
| 1,014
| 27.194444
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/StringConstantNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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.RefType;
/**
* Represents an allocation site node the represents a constant string.
*
* @author Ondrej Lhotak
*/
public class StringConstantNode extends AllocNode {
public String toString() {
return "StringConstantNode " + getNumber() + " " + newExpr;
}
public String getString() {
return (String) newExpr;
}
/* End of public methods. */
StringConstantNode(PAG pag, String sc) {
super(pag, sc, RefType.v("java.lang.String"), null);
}
}
| 1,313
| 26.957447
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/ValNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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 soot.Type;
/**
* Represents a simple of field ref node (Green or Red) in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public class ValNode extends Node {
protected ValNode(PAG pag, Type t) {
super(pag, t);
}
}
| 1,075
| 28.081081
| 88
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/pag/VarNode.java
|
package soot.jimple.spark.pag;
/*-
* #%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.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.AnySubType;
import soot.Context;
import soot.RefLikeType;
import soot.Type;
import soot.toolkits.scalar.Pair;
/**
* Represents a simple variable node (Green) in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public abstract class VarNode extends ValNode implements Comparable {
private static final Logger logger = LoggerFactory.getLogger(VarNode.class);
public Context context() {
return null;
}
/** Returns all field ref nodes having this node as their base. */
public Collection<FieldRefNode> getAllFieldRefs() {
if (fields == null) {
return Collections.emptyList();
}
return fields.values();
}
/**
* Returns the field ref node having this node as its base, and field as its field; null if nonexistent.
*/
public FieldRefNode dot(SparkField field) {
return fields == null ? null : fields.get(field);
}
public int compareTo(Object o) {
VarNode other = (VarNode) o;
if (other.finishingNumber == finishingNumber && other != this) {
logger.debug("" + "This is: " + this + " with id " + getNumber() + " and number " + finishingNumber);
logger.debug("" + "Other is: " + other + " with id " + other.getNumber() + " and number " + other.finishingNumber);
throw new RuntimeException("Comparison error");
}
return other.finishingNumber - finishingNumber;
}
public void setFinishingNumber(int i) {
finishingNumber = i;
if (i > pag.maxFinishNumber) {
pag.maxFinishNumber = i;
}
}
/** Returns the underlying variable that this node represents. */
public Object getVariable() {
return variable;
}
/**
* Designates this node as the potential target of a interprocedural assignment edge which may be added during on-the-fly
* call graph updating.
*/
public void setInterProcTarget() {
interProcTarget = true;
}
/**
* Returns true if this node is the potential target of a interprocedural assignment edge which may be added during
* on-the-fly call graph updating.
*/
public boolean isInterProcTarget() {
return interProcTarget;
}
/**
* Designates this node as the potential source of a interprocedural assignment edge which may be added during on-the-fly
* call graph updating.
*/
public void setInterProcSource() {
interProcSource = true;
}
/**
* Returns true if this node is the potential source of a interprocedural assignment edge which may be added during
* on-the-fly call graph updating.
*/
public boolean isInterProcSource() {
return interProcSource;
}
/** Returns true if this VarNode represents the THIS pointer */
public boolean isThisPtr() {
if (variable instanceof Pair) {
Pair o = (Pair) variable;
return o.isThisParameter();
}
return false;
}
/* End of public methods. */
VarNode(PAG pag, Object variable, Type t) {
super(pag, t);
if (!(t instanceof RefLikeType) || t instanceof AnySubType) {
throw new RuntimeException("Attempt to create VarNode of type " + t);
}
this.variable = variable;
pag.getVarNodeNumberer().add(this);
setFinishingNumber(++pag.maxFinishNumber);
}
/** Registers a frn as having this node as its base. */
void addField(FieldRefNode frn, SparkField field) {
if (fields == null) {
fields = new HashMap<SparkField, FieldRefNode>();
}
fields.put(field, frn);
}
/* End of package methods. */
protected Object variable;
protected Map<SparkField, FieldRefNode> fields;
protected int finishingNumber = 0;
protected boolean interProcTarget = false;
protected boolean interProcSource = false;
protected int numDerefs = 0;
}
| 4,681
| 28.446541
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/AllSharedHybridNodes.java
|
package soot.jimple.spark.sets;
/*-
* #%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.LinkedList;
import soot.G;
import soot.Singletons;
/** A singleton to hold the hash table for SharedHybridSet */
public class AllSharedHybridNodes {
public AllSharedHybridNodes(Singletons.Global g) {
}
public static AllSharedHybridNodes v() {
return G.v().soot_jimple_spark_sets_AllSharedHybridNodes();
}
public class BitVectorLookupMap {
// Each element i is a list of BitVectors which have i 1s
// (i elements in the set).
// But should this be a LinkedList or some kind of Set?
// I'll try LinkedList
// TODO: Maybe implement my own linked list here
// -it would need an add method and an iterator
public LinkedList[] map = new LinkedList[1];
private final static int INCREASE_FACTOR = 2; // change to affect the
// speed/memory tradeoff
public void add(int size, PointsToBitVector toAdd) {
if (map.length < size + 1)
// if the `map' array isn't big enough
{
// TODO: The paper says it does some rearranging at this point
LinkedList[] newMap = new LinkedList[size * INCREASE_FACTOR];
System.arraycopy(map, 0, newMap, 0, map.length);
map = newMap;
}
if (map[size] == null) {
map[size] = new LinkedList();
}
map[size].add(toAdd);
}
public void remove(int size, PointsToBitVector toRemove) {
/*
* if (map[size] == null) { //Can't happen System.out.println(toRemove.cardinality()); }
*/
map[size].remove(toRemove);
}
}
public BitVectorLookupMap lookupMap = new BitVectorLookupMap(); // A hash table of all
// the bit vectors for all points-to sets.
// It can keep growing as more bit vectors are added to it, which
// means it will have to occasionally double in size, which is expensive.
}
| 2,654
| 30.987952
| 94
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/AllSharedListNodes.java
|
package soot.jimple.spark.sets;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import soot.G;
import soot.Singletons;
import soot.jimple.spark.sets.SharedListSet.ListNode;
import soot.jimple.spark.sets.SharedListSet.Pair;
/** A singleton to hold the hash table for SharedListSet */
public class AllSharedListNodes {
public AllSharedListNodes(Singletons.Global g) {
}
public static AllSharedListNodes v() {
return G.v().soot_jimple_spark_sets_AllSharedListNodes();
}
public Map<Pair, ListNode> allNodes = new HashMap<Pair, ListNode>();
}
| 1,376
| 29.6
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/BitPointsToSet.java
|
package soot.jimple.spark.sets;
/*-
* #%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 soot.Type;
import soot.jimple.spark.internal.TypeManager;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.util.BitSetIterator;
import soot.util.BitVector;
/**
* Implementation of points-to set using a bit vector.
*
* @author Ondrej Lhotak
*/
public final class BitPointsToSet extends PointsToSetInternal {
public BitPointsToSet(Type type, PAG pag) {
super(type);
this.pag = pag;
bits = new BitVector(pag.getAllocNodeNumberer().size());
}
/** Returns true if this set contains no run-time objects. */
public final boolean isEmpty() {
return empty;
}
private final boolean superAddAll(PointsToSetInternal other, PointsToSetInternal exclude) {
boolean ret = super.addAll(other, exclude);
if (ret) {
empty = false;
}
return ret;
}
private final boolean nativeAddAll(BitPointsToSet other, BitPointsToSet exclude) {
BitVector mask = null;
TypeManager typeManager = pag.getTypeManager();
if (!typeManager.castNeverFails(other.getType(), this.getType())) {
mask = typeManager.get(this.getType());
}
BitVector obits = (other == null ? null : other.bits);
BitVector ebits = (exclude == null ? null : exclude.bits);
boolean ret = bits.orAndAndNot(obits, mask, ebits);
if (ret) {
empty = false;
}
return ret;
}
/**
* Adds contents of other into this set, returns true if this set changed.
*/
public final boolean addAll(PointsToSetInternal other, PointsToSetInternal exclude) {
if (other != null && !(other instanceof BitPointsToSet)) {
return superAddAll(other, exclude);
}
if (exclude != null && !(exclude instanceof BitPointsToSet)) {
return superAddAll(other, exclude);
}
return nativeAddAll((BitPointsToSet) other, (BitPointsToSet) exclude);
}
/** Calls v's visit method on all nodes in this set. */
public final boolean forall(P2SetVisitor v) {
for (BitSetIterator it = bits.iterator(); it.hasNext();) {
v.visit((Node) pag.getAllocNodeNumberer().get(it.next()));
}
return v.getReturnValue();
}
/** Adds n to this set, returns true if n was not already in this set. */
public final boolean add(Node n) {
if (pag.getTypeManager().castNeverFails(n.getType(), type)) {
return fastAdd(n);
}
return false;
}
/** Returns true iff the set contains n. */
public final boolean contains(Node n) {
return bits.get(n.getNumber());
}
public static P2SetFactory getFactory() {
return new P2SetFactory() {
public PointsToSetInternal newSet(Type type, PAG pag) {
return new BitPointsToSet(type, pag);
}
};
}
/* End of public methods. */
/* End of package methods. */
private boolean fastAdd(Node n) {
boolean ret = bits.set(n.getNumber());
if (ret) {
empty = false;
}
return ret;
}
private BitVector bits = null;
private boolean empty = true;
private PAG pag = null;
}
| 3,812
| 28.55814
| 93
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/DoublePointsToSet.java
|
package soot.jimple.spark.sets;
/*-
* #%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.HashSet;
import java.util.Set;
import soot.G;
import soot.PointsToSet;
import soot.Type;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
/**
* Implementation of points-to set that holds two sets: one for new elements that have not yet been propagated, and the other
* for elements that have already been propagated.
*
* @author Ondrej Lhotak
*/
public class DoublePointsToSet extends PointsToSetInternal {
public DoublePointsToSet(Type type, PAG pag) {
super(type);
newSet = G.v().newSetFactory.newSet(type, pag);
oldSet = G.v().oldSetFactory.newSet(type, pag);
this.pag = pag;
}
/** Returns true if this set contains no run-time objects. */
public boolean isEmpty() {
return oldSet.isEmpty() && newSet.isEmpty();
}
/** Returns true if this set shares some objects with other. */
public boolean hasNonEmptyIntersection(PointsToSet other) {
return oldSet.hasNonEmptyIntersection(other) || newSet.hasNonEmptyIntersection(other);
}
/** Set of all possible run-time types of objects in the set. */
public Set<Type> possibleTypes() {
Set<Type> ret = new HashSet<Type>();
ret.addAll(oldSet.possibleTypes());
ret.addAll(newSet.possibleTypes());
return ret;
}
/**
* Adds contents of other into this set, returns true if this set changed.
*/
public boolean addAll(PointsToSetInternal other, PointsToSetInternal exclude) {
if (exclude != null) {
throw new RuntimeException("NYI");
}
return newSet.addAll(other, oldSet);
}
/** Calls v's visit method on all nodes in this set. */
public boolean forall(P2SetVisitor v) {
oldSet.forall(v);
newSet.forall(v);
return v.getReturnValue();
}
/** Adds n to this set, returns true if n was not already in this set. */
public boolean add(Node n) {
if (oldSet.contains(n)) {
return false;
}
return newSet.add(n);
}
/** Returns set of nodes already present before last call to flushNew. */
public PointsToSetInternal getOldSet() {
return oldSet;
}
/** Returns set of newly-added nodes since last call to flushNew. */
public PointsToSetInternal getNewSet() {
return newSet;
}
/** Sets all newly-added nodes to old nodes. */
public void flushNew() {
oldSet.addAll(newSet, null);
newSet = G.v().newSetFactory.newSet(type, pag);
}
/** Sets all nodes to newly-added nodes. */
public void unFlushNew() {
newSet.addAll(oldSet, null);
oldSet = G.v().oldSetFactory.newSet(type, pag);
}
/** Merges other into this set. */
public void mergeWith(PointsToSetInternal other) {
if (!(other instanceof DoublePointsToSet)) {
throw new RuntimeException("NYI");
}
final DoublePointsToSet o = (DoublePointsToSet) other;
if (other.type != null && !(other.type.equals(type))) {
throw new RuntimeException("different types " + type + " and " + other.type);
}
if (other.type == null && type != null) {
throw new RuntimeException("different types " + type + " and " + other.type);
}
final PointsToSetInternal newNewSet = G.v().newSetFactory.newSet(type, pag);
final PointsToSetInternal newOldSet = G.v().oldSetFactory.newSet(type, pag);
oldSet.forall(new P2SetVisitor() {
public final void visit(Node n) {
if (o.oldSet.contains(n)) {
newOldSet.add(n);
}
}
});
newNewSet.addAll(this, newOldSet);
newNewSet.addAll(o, newOldSet);
newSet = newNewSet;
oldSet = newOldSet;
}
/** Returns true iff the set contains n. */
public boolean contains(Node n) {
return oldSet.contains(n) || newSet.contains(n);
}
private static P2SetFactory defaultP2SetFactory = new P2SetFactory() {
public PointsToSetInternal newSet(Type type, PAG pag) {
return new DoublePointsToSet(type, pag);
}
};
public static P2SetFactory getFactory(P2SetFactory newFactory, P2SetFactory oldFactory) {
G.v().newSetFactory = newFactory;
G.v().oldSetFactory = oldFactory;
return defaultP2SetFactory;
}
/* End of public methods. */
/* End of package methods. */
private PAG pag;
protected PointsToSetInternal newSet;
protected PointsToSetInternal oldSet;
}
| 5,064
| 29.884146
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/EmptyPointsToSet.java
|
package soot.jimple.spark.sets;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collections;
import java.util.Set;
import soot.G;
import soot.PointsToSet;
import soot.Singletons;
import soot.Type;
import soot.jimple.ClassConstant;
import soot.jimple.spark.pag.Node;
/**
* Implementation of an empty, immutable points-to set.
*
* @author Ondrej Lhotak
*/
public class EmptyPointsToSet extends PointsToSetInternal {
public EmptyPointsToSet(Singletons.Global g) {
super(null);
}
public static EmptyPointsToSet v() {
return G.v().soot_jimple_spark_sets_EmptyPointsToSet();
}
public EmptyPointsToSet(Singletons.Global g, Type type) {
super(type);
}
/** Returns true if this set contains no run-time objects. */
public boolean isEmpty() {
return true;
}
/** Returns true if this set shares some objects with other. */
public boolean hasNonEmptyIntersection(PointsToSet other) {
return false;
}
/** Set of all possible run-time types of objects in the set. */
public Set<Type> possibleTypes() {
return Collections.emptySet();
}
/**
* Adds contents of other into this set, returns true if this set changed.
*/
public boolean addAll(PointsToSetInternal other, PointsToSetInternal exclude) {
throw new RuntimeException("can't add into empty immutable set");
}
/** Calls v's visit method on all nodes in this set. */
public boolean forall(P2SetVisitor v) {
return false;
}
/** Adds n to this set, returns true if n was not already in this set. */
public boolean add(Node n) {
throw new RuntimeException("can't add into empty immutable set");
}
/** Returns true iff the set contains n. */
public boolean contains(Node n) {
return false;
}
public Set<String> possibleStringConstants() {
return Collections.emptySet();
}
public Set<ClassConstant> possibleClassConstants() {
return Collections.emptySet();
}
/**
* {@inheritDoc}
*/
public String toString() {
return "{}";
}
}
| 2,780
| 25.235849
| 81
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/EqualsSupportingPointsToSet.java
|
package soot.jimple.spark.sets;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.PointsToSet;
/**
* A points-to set supporting deep equals and hashCode operations.
*
* @author Eric Bodden
* @see PointsToSetEqualsWrapper
*/
public interface EqualsSupportingPointsToSet extends PointsToSet {
/**
* Computes a hash code based on the contents of the points-to set. Note that hashCode() is not overwritten on purpose.
* This is because Spark relies on comparison by object identity.
*/
public int pointsToSetHashCode();
/**
* Returns <code>true</code> if and only if other holds the same alloc nodes as this. Note that equals() is not overwritten
* on purpose. This is because Spark relies on comparison by object identity.
*/
public boolean pointsToSetEquals(Object other);
}
| 1,567
| 31.666667
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/HashPointsToSet.java
|
package soot.jimple.spark.sets;
/*-
* #%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.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import soot.Type;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
/**
* HashSet implementation of points-to set.
*
* @author Ondrej Lhotak
*/
public final class HashPointsToSet extends PointsToSetInternal {
public HashPointsToSet(Type type, PAG pag) {
super(type);
this.pag = pag;
}
/** Returns true if this set contains no run-time objects. */
public final boolean isEmpty() {
return s.isEmpty();
}
/**
* Adds contents of other into this set, returns true if this set changed.
*/
public final boolean addAll(final PointsToSetInternal other, final PointsToSetInternal exclude) {
if (other instanceof HashPointsToSet && exclude == null
&& (pag.getTypeManager().getFastHierarchy() == null || type == null || type.equals(other.type))) {
return s.addAll(((HashPointsToSet) other).s);
} else {
return super.addAll(other, exclude);
}
}
/** Calls v's visit method on all nodes in this set. */
public final boolean forall(P2SetVisitor v) {
for (Iterator<Node> it = new ArrayList<Node>(s).iterator(); it.hasNext();) {
v.visit(it.next());
}
return v.getReturnValue();
}
/** Adds n to this set, returns true if n was not already in this set. */
public final boolean add(Node n) {
if (pag.getTypeManager().castNeverFails(n.getType(), type)) {
return s.add(n);
}
return false;
}
/** Returns true iff the set contains n. */
public final boolean contains(Node n) {
return s.contains(n);
}
public static P2SetFactory getFactory() {
return new P2SetFactory() {
public PointsToSetInternal newSet(Type type, PAG pag) {
return new HashPointsToSet(type, pag);
}
};
}
/* End of public methods. */
/* End of package methods. */
private final HashSet<Node> s = new HashSet<Node>(4);
private PAG pag = null;
}
| 2,798
| 27.85567
| 106
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/HybridPointsToSet.java
|
package soot.jimple.spark.sets;
/*-
* #%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 soot.Scene;
import soot.Type;
import soot.jimple.spark.internal.TypeManager;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.util.BitSetIterator;
import soot.util.BitVector;
/**
* Hybrid implementation of points-to set, which uses an explicit array for small sets, and a bit vector for large sets.
*
* @author Ondrej Lhotak
*/
public class HybridPointsToSet extends PointsToSetInternal {
private static P2SetFactory<HybridPointsToSet> HYBRID_PTS_FACTORY = new P2SetFactory<HybridPointsToSet>() {
@Override
public final HybridPointsToSet newSet(Type type, PAG pag) {
return new HybridPointsToSet(type, pag);
}
};
public HybridPointsToSet(Type type, PAG pag) {
super(type);
this.pag = pag;
}
public static void setPointsToSetFactory(P2SetFactory<HybridPointsToSet> factory) {
HYBRID_PTS_FACTORY = factory;
}
/** Returns true if this set contains no run-time objects. */
public final boolean isEmpty() {
return empty;
}
private boolean superAddAll(PointsToSetInternal other, PointsToSetInternal exclude) {
boolean ret = super.addAll(other, exclude);
if (ret) {
empty = false;
}
return ret;
}
private boolean nativeAddAll(HybridPointsToSet other, HybridPointsToSet exclude) {
boolean ret = false;
TypeManager typeManager = pag.getTypeManager();
if (other.bits != null) {
convertToBits();
if (exclude != null) {
exclude.convertToBits();
}
BitVector mask = null;
if (!typeManager.castNeverFails(other.getType(), this.getType())) {
mask = typeManager.get(this.getType());
}
BitVector ebits = (exclude == null ? null : exclude.bits);
ret = bits.orAndAndNot(other.bits, mask, ebits);
} else {
for (int i = 0; i < nodes.length; i++) {
if (other.nodes[i] == null) {
break;
}
if (exclude == null || !exclude.contains(other.nodes[i])) {
ret = add(other.nodes[i]) | ret;
}
}
}
if (ret) {
empty = false;
}
return ret;
}
/**
* Adds contents of other into this set, returns true if this set changed.
*/
public boolean addAll(final PointsToSetInternal other, final PointsToSetInternal exclude) {
if (other != null && !(other instanceof HybridPointsToSet)) {
return superAddAll(other, exclude);
}
if (exclude != null && !(exclude instanceof HybridPointsToSet)) {
return superAddAll(other, exclude);
}
return nativeAddAll((HybridPointsToSet) other, (HybridPointsToSet) exclude);
}
/** Calls v's visit method on all nodes in this set. */
public boolean forall(P2SetVisitor v) {
if (bits == null) {
for (Node node : nodes) {
if (node == null) {
return v.getReturnValue();
}
v.visit(node);
}
} else {
for (BitSetIterator it = bits.iterator(); it.hasNext();) {
v.visit(pag.getAllocNodeNumberer().get(it.next()));
}
}
return v.getReturnValue();
}
/** Adds n to this set, returns true if n was not already in this set. */
public boolean add(Node n) {
if (pag.getTypeManager().castNeverFails(n.getType(), type)) {
return fastAdd(n);
}
return false;
}
/** Returns true iff the set contains n. */
public boolean contains(Node n) {
if (bits == null) {
for (Node node : nodes) {
if (node == n) {
return true;
}
if (node == null) {
break;
}
}
return false;
} else {
return bits.get(n.getNumber());
}
}
public static P2SetFactory<HybridPointsToSet> getFactory() {
return HYBRID_PTS_FACTORY;
}
/* End of public methods. */
/* End of package methods. */
protected boolean fastAdd(Node n) {
if (bits == null) {
for (int i = 0; i < nodes.length; i++) {
if (nodes[i] == null) {
empty = false;
nodes[i] = n;
return true;
} else if (nodes[i] == n) {
return false;
}
}
convertToBits();
}
boolean ret = bits.set(n.getNumber());
if (ret) {
empty = false;
}
return ret;
}
protected void convertToBits() {
if (bits != null) {
return;
}
// ++numBitVectors;
bits = new BitVector(pag.getAllocNodeNumberer().size());
for (Node node : nodes) {
if (node != null) {
fastAdd(node);
}
}
}
// public static int numBitVectors = 0;
protected Node[] nodes = new Node[16];
protected BitVector bits = null;
protected PAG pag;
protected boolean empty = true;
public static HybridPointsToSet intersection(final HybridPointsToSet set1, final HybridPointsToSet set2, PAG pag) {
final HybridPointsToSet ret = HybridPointsToSet.getFactory().newSet(Scene.v().getObjectType(), pag);
BitVector s1Bits = set1.bits;
BitVector s2Bits = set2.bits;
if (s1Bits == null || s2Bits == null) {
if (s1Bits != null) {
// set2 is smaller
set2.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (set1.contains(n)) {
ret.add(n);
}
}
});
} else {
// set1 smaller, or both small
set1.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (set2.contains(n)) {
ret.add(n);
}
}
});
}
} else {
// both big; do bit-vector operation
// potential issue: if intersection is small, might
// use inefficient bit-vector operations later
ret.bits = BitVector.and(s1Bits, s2Bits);
ret.empty = false;
}
return ret;
}
}
| 6,600
| 26.852321
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/P2SetFactory.java
|
package soot.jimple.spark.sets;
/*-
* #%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 soot.Type;
import soot.jimple.spark.pag.PAG;
/**
* Abstract base class for points-to set factory.
*
* @author Ondrej Lhotak
*/
public abstract class P2SetFactory<T extends PointsToSetInternal> {
/** Returns a newly-created set. */
public abstract T newSet(Type type, PAG pag);
}
| 1,127
| 29.486486
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/P2SetVisitor.java
|
package soot.jimple.spark.sets;
/*-
* #%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 soot.jimple.spark.pag.Node;
/**
* Abstract base class for points-to set visitors used to enumerate points-to sets.
*
* @author Ondrej Lhotak
*/
public abstract class P2SetVisitor {
public abstract void visit(Node n);
public boolean getReturnValue() {
return returnValue;
}
protected boolean returnValue = false;
}
| 1,172
| 27.609756
| 83
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/PointsToBitVector.java
|
package soot.jimple.spark.sets;
/*-
* #%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.jimple.spark.pag.Node;
import soot.util.BitVector;
/**
* An extension of a bit vector which is convenient to use to represent points-to sets. Used by SharedHybridSet.
*
* We have to extend soot.util.BitVector rather than java.util.BitSet because PointsToSetInternal.getBitMask() returns a
* soot.util.BitVector. which must be combined with other bit vectors.
*
* @author Adam Richard
*
*/
public class PointsToBitVector extends BitVector {
public PointsToBitVector(int size) {
super(size);
}
/**
* Adds n to this
*
* @return Whether this actually changed
*/
public boolean add(Node n) {
int num = n.getNumber();
if (!get(num))
// if it's not already in this
{
set(num);
return true;
} else {
return false;
}
}
public boolean contains(Node n) {
// Ripped from the HybridPointsToSet implementation
// I'm assuming `number' in Node is the location of the node out of all
// possible nodes.
return get(n.getNumber());
}
/**
* Adds the Nodes in arr to this bitvector, adding at most size Nodes.
*
* @return The number of new nodes actually added.
*/
/*
* public int add(Node[] arr, int size) { //assert size <= arr.length; int retVal = 0; for (int i = 0; i < size; ++i) { int
* num = arr[i].getNumber(); if (!get(num)) { set(num); ++retVal; } } return retVal; }
*/
/** Returns true iff other is a subset of this bitvector */
public boolean isSubsetOf(PointsToBitVector other) {
// B is a subset of A iff the "and" of A and B gives A.
BitVector andResult = BitVector.and(this, other); // Don't want to modify either one
return andResult.equals(this);
}
/**
* @return number of 1 bits in the bitset. Call this sparingly because it's probably expensive.
*/
/*
* Old algorithm: public int cardinality() { int retVal = 0; BitSetIterator it = iterator(); while (it.hasNext()) {
* it.next(); ++retVal; } return retVal; }
*/
public PointsToBitVector(PointsToBitVector other) {
super(other);
/*
* PointsToBitVector retVal = (PointsToBitVector)(other.clone()); return retVal;
*/
}
// Reference counting:
private int refCount = 0;
public void incRefCount() {
++refCount;
// An estimate of how much sharing is going on (but it should be 1 less
// than the printed value in some cases, because incRefCount is called
// for an intermediate result in nativeAddAll.
// System.out.println("Reference count = " + refCount);
}
public void decRefCount() {
--refCount;
}
public boolean unused() {
return refCount == 0;
}
}
| 3,497
| 28.394958
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/PointsToSetEqualsWrapper.java
|
package soot.jimple.spark.sets;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Set;
import soot.PointsToSet;
import soot.Type;
import soot.jimple.ClassConstant;
/**
* A decorator that implements equals/hashCode for {@link PointsToSet} supporting the {@link EqualsSupportingPointsToSet}
* interface.
*
* @author Eric Bodden
*/
public class PointsToSetEqualsWrapper implements PointsToSet {
protected EqualsSupportingPointsToSet pts;
public PointsToSetEqualsWrapper(EqualsSupportingPointsToSet pts) {
this.pts = pts;
}
public EqualsSupportingPointsToSet unwarp() {
return this.pts;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
// delegate
return pts.pointsToSetHashCode();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj || this.pts == obj) {
return true;
}
// unwrap other
obj = unwrapIfNecessary(obj);
// delegate
return pts.pointsToSetEquals(obj);
}
/**
* @param other
* @return
* @see soot.PointsToSet#hasNonEmptyIntersection(soot.PointsToSet)
*/
public boolean hasNonEmptyIntersection(PointsToSet other) {
// unwrap other
other = (PointsToSet) unwrapIfNecessary(other);
return pts.hasNonEmptyIntersection(other);
}
/**
* @return
* @see soot.PointsToSet#isEmpty()
*/
public boolean isEmpty() {
return pts.isEmpty();
}
/**
* @return
* @see soot.PointsToSet#possibleClassConstants()
*/
public Set<ClassConstant> possibleClassConstants() {
return pts.possibleClassConstants();
}
/**
* @return
* @see soot.PointsToSet#possibleStringConstants()
*/
public Set<String> possibleStringConstants() {
return pts.possibleStringConstants();
}
/**
* @return
* @see soot.PointsToSet#possibleTypes()
*/
public Set<Type> possibleTypes() {
return pts.possibleTypes();
}
protected Object unwrapIfNecessary(Object obj) {
if (obj instanceof PointsToSetEqualsWrapper) {
PointsToSetEqualsWrapper wrapper = (PointsToSetEqualsWrapper) obj;
obj = wrapper.pts;
}
return obj;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return pts.toString();
}
}
| 3,015
| 21.848485
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/PointsToSetInternal.java
|
package soot.jimple.spark.sets;
/*-
* #%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.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.G;
import soot.PointsToSet;
import soot.RefType;
import soot.Type;
import soot.jimple.ClassConstant;
import soot.jimple.spark.internal.TypeManager;
import soot.jimple.spark.pag.ClassConstantNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.StringConstantNode;
import soot.jimple.toolkits.pointer.FullObjectSet;
import soot.util.BitVector;
/**
* Abstract base class for implementations of points-to sets.
*
* @author Ondrej Lhotak
*/
public abstract class PointsToSetInternal implements PointsToSet, EqualsSupportingPointsToSet {
private static final Logger logger = LoggerFactory.getLogger(PointsToSetInternal.class);
/**
* Adds contents of other minus the contents of exclude into this set; returns true if this set changed.
*/
public boolean addAll(PointsToSetInternal other, final PointsToSetInternal exclude) {
if (other instanceof DoublePointsToSet) {
return addAll(other.getNewSet(), exclude) | addAll(other.getOldSet(), exclude);
} else if (other instanceof EmptyPointsToSet) {
return false;
} else if (exclude instanceof EmptyPointsToSet) {
return addAll(other, null);
}
if (!G.v().PointsToSetInternal_warnedAlready) {
logger.warn("using default implementation of addAll. You should implement a faster specialized implementation.");
logger.debug("" + "this is of type " + getClass().getName());
logger.debug("" + "other is of type " + other.getClass().getName());
if (exclude == null) {
logger.debug("" + "exclude is null");
} else {
logger.debug("" + "exclude is of type " + exclude.getClass().getName());
}
G.v().PointsToSetInternal_warnedAlready = true;
}
return other.forall(new P2SetVisitor() {
public final void visit(Node n) {
if (exclude == null || !exclude.contains(n)) {
returnValue = add(n) | returnValue;
}
}
});
}
/** Calls v's visit method on all nodes in this set. */
public abstract boolean forall(P2SetVisitor v);
/** Adds n to this set, returns true if n was not already in this set. */
public abstract boolean add(Node n);
/** Returns set of newly-added nodes since last call to flushNew. */
public PointsToSetInternal getNewSet() {
return this;
}
/** Returns set of nodes already present before last call to flushNew. */
public PointsToSetInternal getOldSet() {
return EmptyPointsToSet.v();
}
/** Sets all newly-added nodes to old nodes. */
public void flushNew() {
}
/** Sets all nodes to newly-added nodes. */
public void unFlushNew() {
}
/** Merges other into this set. */
public void mergeWith(PointsToSetInternal other) {
addAll(other, null);
}
/** Returns true iff the set contains n. */
public abstract boolean contains(Node n);
public PointsToSetInternal(Type type) {
this.type = type;
}
public boolean hasNonEmptyIntersection(PointsToSet other) {
if (other instanceof PointsToSetInternal) {
final PointsToSetInternal o = (PointsToSetInternal) other;
return forall(new P2SetVisitor() {
public void visit(Node n) {
if (o.contains(n)) {
returnValue = true;
}
}
});
} else if (other instanceof FullObjectSet) {
final FullObjectSet fos = (FullObjectSet) other;
return fos.possibleTypes().contains(type);
} else {
// We don't really know
return false;
}
}
public Set<Type> possibleTypes() {
final HashSet<Type> ret = new HashSet<>();
forall(new P2SetVisitor() {
public void visit(Node n) {
Type t = n.getType();
if (t instanceof RefType) {
RefType rt = (RefType) t;
if (rt.getSootClass().isAbstract()) {
return;
}
}
ret.add(t);
}
});
return ret;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public int size() {
final int[] ret = new int[1];
forall(new P2SetVisitor() {
public void visit(Node n) {
ret[0]++;
}
});
return ret[0];
}
public String toString() {
final StringBuffer ret = new StringBuffer();
this.forall(new P2SetVisitor() {
public final void visit(Node n) {
ret.append("" + n + ",");
}
});
return ret.toString();
}
public Set<String> possibleStringConstants() {
final HashSet<String> ret = new HashSet<String>();
return this.forall(new P2SetVisitor() {
public final void visit(Node n) {
if (n instanceof StringConstantNode) {
ret.add(((StringConstantNode) n).getString());
} else {
returnValue = true;
}
}
}) ? null : ret;
}
public Set<ClassConstant> possibleClassConstants() {
final HashSet<ClassConstant> ret = new HashSet<ClassConstant>();
return this.forall(new P2SetVisitor() {
public final void visit(Node n) {
if (n instanceof ClassConstantNode) {
ret.add(((ClassConstantNode) n).getClassConstant());
} else {
returnValue = true;
}
}
}) ? null : ret;
}
/* End of public methods. */
/* End of package methods. */
protected Type type;
// Added by Adam Richard
protected BitVector getBitMask(PointsToSetInternal other, PAG pag) {
/*
* Prevents propogating points-to sets of inappropriate type. E.g. if you have in the code being analyzed: Shape s =
* (Circle)c; then the points-to set of s is only the elements in the points-to set of c that have type Circle.
*/
// Code ripped from BitPointsToSet
BitVector mask = null;
TypeManager typeManager = pag.getTypeManager();
if (!typeManager.castNeverFails(other.getType(), this.getType())) {
mask = typeManager.get(this.getType());
}
return mask;
}
/**
* {@inheritDoc}
*/
public int pointsToSetHashCode() {
P2SetVisitorInt visitor = new P2SetVisitorInt(1) {
final int PRIME = 31;
public void visit(Node n) {
intValue = PRIME * intValue + n.hashCode();
}
};
this.forall(visitor);
return visitor.intValue;
}
/**
* {@inheritDoc}
*/
public boolean pointsToSetEquals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof PointsToSetInternal)) {
return false;
}
PointsToSetInternal otherPts = (PointsToSetInternal) other;
// both sets are equal if they are supersets of each other
return superSetOf(otherPts, this) && superSetOf(this, otherPts);
}
/**
* Returns <code>true</code> if <code>onePts</code> is a (non-strict) superset of <code>otherPts</code>.
*/
private boolean superSetOf(PointsToSetInternal onePts, final PointsToSetInternal otherPts) {
return onePts.forall(new P2SetVisitorDefaultTrue() {
public final void visit(Node n) {
returnValue = returnValue && otherPts.contains(n);
}
});
}
/**
* A P2SetVisitor with a default return value of <code>true</code>.
*
* @author Eric Bodden
*/
public static abstract class P2SetVisitorDefaultTrue extends P2SetVisitor {
public P2SetVisitorDefaultTrue() {
returnValue = true;
}
}
/**
* A P2SetVisitor with an int value.
*
* @author Eric Bodden
*/
public static abstract class P2SetVisitorInt extends P2SetVisitor {
protected int intValue;
public P2SetVisitorInt(int i) {
intValue = 1;
}
}
}
| 8,497
| 26.953947
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/SharedHybridSet.java
|
package soot.jimple.spark.sets;
/*-
* #%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.Type;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.util.BitSetIterator;
import soot.util.BitVector;
/*
* Possible sources of inefficiency:
* -It seems like there must be a way to immediately know which subset bitvector
* will exist, since sets are shared when a node with a smaller points-to set is
* pointing to another node. Why not just take that node's bitvector as a base?
* -addAll could probably use many improvements.
* -Cast masking - calling typeManager.get
* -An interesting problem is that when merging a bitvector into an overflow list, if
* the one being merged
* in has a bitvector, the mask or exclude might mask it down to a bitvector with very
* few ones. (In fact, this might even result in one with 0 ones!)
* Should that new bitvector stay as a bitvector, or be converted to an
* overflow list? And how can we tell when it will have few ones? (Modify BitVector?)
*
*/
/**
* A shared representation of a points-to set which uses a bit vector + a list of extra elements, an "overflow list", to make
* adding single elements fast in most cases.
*
* The bit vector may be shared by multiple points-to sets, while the overflow list is specific to each points-to set.
*
* To facilitate sharing of the bitvectors, there is a "hash table" of all existing bitvectors kept, called
* BitVectorLookupMap, where the ith element contains a list of all existing bitvectors of cardinality i (i.e. has i one
* bits).
*
* @author Adam Richard
*
*/
public class SharedHybridSet extends PointsToSetInternal {
public SharedHybridSet(Type type, PAG pag) {
// I'm not sure what "type" is for, but this is the way the other set
// representations
// did it
super(type);
this.pag = pag;
// System.out.println("Using new heintze set");
}
// The following 2 constants should be tweaked for efficiency
public final static int OVERFLOW_SIZE = 16;
/**
* The max number of elements allowed in the set before creating a new bitvector for it.
*/
public final static int OVERFLOW_THRESHOLD = 5;
/**
* When the overflow list overflows, the maximum number of elements that may remain in the overflow list (the rest are
* moved into the base bit vector)
*/
public boolean contains(Node n) {
// Which should be checked first, bitVector or overflow? (for
// performance)
// I think the bit vector, since it only takes O(1) to check many
// elements
// Check the bit vector
if (bitVector != null && bitVector.contains(n)) {
return true;
}
// Check overflow
if (overflow.contains(n)) {
return true;
}
return false;
}
public boolean isEmpty() {
return numElements == 0;
}
/**
* @return an overflow list of all elements in a that aren't in b (b is assumed to be a subset of a)
*/
private OverflowList remainder(PointsToBitVector a, PointsToBitVector b) {
// Since a contains everything b contains, doing an XOR will give
// everything
// in a not in b
PointsToBitVector xorResult = new PointsToBitVector(a);
xorResult.xor(b);
// xorResult must now contain <= 20 elements, assuming
// OVERFLOW_THRESHOLD <= OVERFLOW_SIZE
return new OverflowList(xorResult);
}
// Look for an existing bitvector in the lookupMap which is a subset of the
// newBitVector (the bitVector to set as the new points-to set), with only a
// few
// elements missing. If we find one, make that set the new `bitVector', and
// the leftovers the new `overflow'
// szBitVector is the size of the ORIGINAL bit vector, NOT the size of newBitVector
private void findAppropriateBitVector(PointsToBitVector newBitVector, PointsToBitVector otherBitVector, int otherSize,
int szBitvector) {
// First check "other" and "this"'s bitvector, to maximize sharing and
// minimize searching for a new bitvector
if (otherBitVector != null && otherSize <= numElements && otherSize + OVERFLOW_THRESHOLD >= numElements
&& otherBitVector.isSubsetOf(newBitVector)) {
setNewBitVector(szBitvector, otherBitVector);
overflow = remainder(newBitVector, otherBitVector);
} else if (bitVector != null && szBitvector <= numElements && szBitvector + OVERFLOW_THRESHOLD >= numElements
&& bitVector.isSubsetOf(newBitVector)) {
overflow = remainder(newBitVector, bitVector);
} else {
for (int overFlowSize = 0; overFlowSize < OVERFLOW_THRESHOLD; ++overFlowSize) {
int bitVectorCardinality = numElements - overFlowSize;
if (bitVectorCardinality < 0) {
break; // We might be trying to add a bitvector
}
// with <OVERFLOW_THRESHOLD ones (in fact, there might be bitvectors with 0
// ones). This results from merging bitvectors and masking out certain values.
if (bitVectorCardinality < AllSharedHybridNodes.v().lookupMap.map.length
&& AllSharedHybridNodes.v().lookupMap.map[bitVectorCardinality] != null) {
List<PointsToBitVector> lst = AllSharedHybridNodes.v().lookupMap.map[bitVectorCardinality];
for (PointsToBitVector candidate : lst) {
// for each existing bit vector with bitVectorCardinality
// ones
if (candidate.isSubsetOf(newBitVector)) {
setNewBitVector(szBitvector, candidate);
overflow = remainder(newBitVector, candidate);
return;
}
}
}
}
// Didn't find an appropriate bit vector to use as a base; add the new
// bit vector to the map of all bit vectors and set it as the new base
// bit vector
setNewBitVector(szBitvector, newBitVector);
overflow.removeAll();
AllSharedHybridNodes.v().lookupMap.add(numElements, newBitVector);
}
}
// Allows for reference counting and deleting the old bit vector if it
// isn't being shared
private void setNewBitVector(int size, PointsToBitVector newBitVector) {
newBitVector.incRefCount();
if (bitVector != null) {
bitVector.decRefCount();
if (bitVector.unused()) {
// delete bitVector from lookupMap
AllSharedHybridNodes.v().lookupMap.remove(size, bitVector);
}
}
bitVector = newBitVector;
}
public boolean add(Node n) {
/*
* This algorithm is described in the paper "IBM Research Report: Fast Pointer Analysis" by Hirzel, Dincklage, Diwan, and
* Hind, pg. 11
*/
if (contains(n)) {
return false;
}
++numElements;
if (!overflow.full()) {
overflow.add(n);
} else {
// Put everything in the bitvector
PointsToBitVector newBitVector;
if (bitVector == null) {
newBitVector = new PointsToBitVector(pag.getAllocNodeNumberer().size());
} else {
newBitVector = new PointsToBitVector(bitVector);
}
newBitVector.add(n); // add n to it
add(newBitVector, overflow);
// Now everything is in newBitVector, and it must have numElements
// ones
// The algorithm would still work without this step, but wouldn't be
// a
// shared implmentation at all.
findAppropriateBitVector(newBitVector, null, 0, numElements - overflow.size() - 1);
}
return true;
}
private boolean nativeAddAll(SharedHybridSet other, SharedHybridSet exclude) {
/*
* If one of the shared hybrid sets has a bitvector but the other doesn't, set that bitvector as the base bitvector and
* add the stuff from the other overflow list. If they both have a bitvector, AND them together, then add it to the
* lookupMap. If neither of them has a bitvector, just combine the overflow lists.
*/
BitVector mask = getBitMask(other, pag);
if (exclude != null) {
if (exclude.overflow.size() > 0) {
// Make exclude only a bitvector, for simplicity
PointsToBitVector newBitVector;
if (exclude.bitVector == null) {
newBitVector = new PointsToBitVector(pag.getAllocNodeNumberer().size());
} else {
newBitVector = new PointsToBitVector(exclude.bitVector);
}
add(newBitVector, exclude.overflow);
exclude = new SharedHybridSet(type, pag);
exclude.bitVector = newBitVector;
}
// It's possible at this point that exclude could have been passed in non-null,
// but with no elements. Simplify the rest of the algorithm by setting it to null
// in that case.
else if (exclude.bitVector == null) {
exclude = null;
}
}
int originalSize = size(), originalOnes = originalSize - overflow.size(),
otherBitVectorSize = other.size() - other.overflow.size();
// Decide on the base bitvector
if (bitVector == null) {
bitVector = other.bitVector;
if (bitVector != null) { // Maybe both bitvectors were null; in
// that case, no need to do this
bitVector.incRefCount();
// Since merging in new bits might add elements that
// were
// already in the overflow list, we have to remove and re-add
// them all.
// TODO: Can this be avoided somehow?
// Maybe by allowing an element to be both in the overflow set
// and
// the bitvector?
// Or could it be better done by checking just the bitvector and
// removing elements that are there?
OverflowList toReAdd = overflow;
overflow = new OverflowList();
boolean newBitVectorCreated = false; // whether a new bit vector
// was created, which is used to decide whether to re-add the
// overflow list as an overflow list again or merge it into the
// new bit vector.
numElements = otherBitVectorSize;
if (exclude != null || mask != null) {
PointsToBitVector result = new PointsToBitVector(bitVector);
if (exclude != null) {
result.andNot(exclude.bitVector);
}
if (mask != null) {
result.and(mask);
}
if (!result.equals(bitVector)) {
add(result, toReAdd);
int newBitVectorSize = result.cardinality();
numElements = newBitVectorSize;
findAppropriateBitVector(result, other.bitVector, otherBitVectorSize, otherBitVectorSize);
newBitVectorCreated = true;
}
}
if (!newBitVectorCreated) // if it was, then toReAdd has
// already been re-added
{
for (OverflowList.ListNode i = toReAdd.overflow; i != null; i = i.next) {
add(i.elem);
}
}
}
} else if (other.bitVector != null) {
// Now both bitvectors are non-null; merge them
PointsToBitVector newBitVector = new PointsToBitVector(other.bitVector);
if (exclude != null) {
newBitVector.andNot(exclude.bitVector);
}
if (mask != null) {
newBitVector.and(mask);
}
newBitVector.or(bitVector);
if (!newBitVector.equals(bitVector)) // if some elements were
// actually added
{
// At this point newBitVector is bitVector + some new bits
// Have to make a tough choice - is it better at this point to
// put both overflow lists into this bitvector (which involves
// recalculating bitVector.cardinality() again since there might
// have been overlap), or is it better to re-add both the
// overflow lists to the set?
// I suspect the former, so I'll do that.
// Basically we now want to merge both overflow lists into this
// new
// bitvector (if it is indeed a new bitvector), then add that
// resulting
// huge bitvector to the lookupMap, unless a subset of it is
// already there.
if (other.overflow.size() != 0) {
PointsToBitVector toAdd = new PointsToBitVector(newBitVector.size());
add(toAdd, other.overflow);
if (mask != null) {
toAdd.and(mask);
}
if (exclude != null) {
toAdd.andNot(exclude.bitVector);
}
newBitVector.or(toAdd);
}
// At this point newBitVector is still bitVector + some new bits
int numOnes = newBitVector.cardinality(); // # of bits in the
// new bitvector
int numAdded = add(newBitVector, overflow);
numElements += numOnes - originalOnes // number of new bits
+ numAdded - overflow.size(); // might be negative due to
// elements in overflow already being in the new bits
if (size() > originalSize) {
findAppropriateBitVector(newBitVector, other.bitVector, otherBitVectorSize, originalOnes);
// checkSize();
return true;
} else {
// checkSize();
return false; // It might happen that the bitvector being merged in adds some bits
// to the existing bitvector, but that those new bits are all elements that were already
// in the overflow list. In that case, the set might not change, and if not we return false.
// We also leave the set the way it was by not calling findAppropriateBitvector,
// which maximizes sharing and is fastest in the short term. I'm not sure whether it
// would be faster overall to keep the already calculated bitvector anyway.
}
}
}
// Add all the elements in the overflow list of other, unless they're in
// exclude
OverflowList overflow = other.overflow;
for (OverflowList.ListNode i = overflow.overflow; i != null; i = i.next) {
// for (int i = 0; i < overflow.size(); ++i) {
Node nodeToMaybeAdd = i.elem;
if ((exclude == null) || !exclude.contains(nodeToMaybeAdd)) {
if (mask == null || mask.get(nodeToMaybeAdd.getNumber())) {
add(nodeToMaybeAdd);
}
}
}
// checkSize();
return size() > originalSize;
}
/**
* @ Adds the Nodes in arr to this bitvector.
*
* @return The number of new nodes actually added.
*/
private int add(PointsToBitVector p, OverflowList arr) {
// assert size <= arr.length;
int retVal = 0;
for (OverflowList.ListNode i = arr.overflow; i != null; i = i.next) {
if (p.add(i.elem)) {
++retVal;
/*
* int num = arr[i].getNumber(); if (!get(num)) { set(num); ++retVal; }
*/
}
}
return retVal;
}
/*
* //A class invariant - numElements correctly holds the size //Only used for testing private void checkSize() { int
* realSize = overflow.size(); if (bitVector != null) realSize += bitVector.cardinality(); if (numElements != realSize) {
* throw new RuntimeException("Assertion failed."); } }
*/
public boolean addAll(PointsToSetInternal other, final PointsToSetInternal exclude) {
// Look at the sort of craziness we have to do just because of a lack of
// multimethods
if (other == null) {
return false;
}
if ((!(other instanceof SharedHybridSet)) || (exclude != null && !(exclude instanceof SharedHybridSet))) {
return super.addAll(other, exclude);
} else {
return nativeAddAll((SharedHybridSet) other, (SharedHybridSet) exclude);
}
}
public boolean forall(P2SetVisitor v) {
// Iterate through the bit vector. Ripped from BitPointsToSet again.
// It seems there should be a way to share code between BitPointsToSet
// and
// SharedHybridSet, but I don't know how at the moment.
if (bitVector != null) {
for (BitSetIterator it = bitVector.iterator(); it.hasNext();) {
v.visit((Node) pag.getAllocNodeNumberer().get(it.next()));
}
}
// Iterate through the overflow list
for (OverflowList.ListNode i = overflow.overflow; i != null; i = i.next) {
v.visit(i.elem);
}
return v.getReturnValue();
}
// Ripped from the other points-to sets - returns a factory that can be
// used to construct SharedHybridSets
public final static P2SetFactory getFactory() {
return new P2SetFactory() {
public final PointsToSetInternal newSet(Type type, PAG pag) {
return new SharedHybridSet(type, pag);
}
};
}
private PointsToBitVector bitVector = null; // Shared with other points-to
// sets
private OverflowList overflow = new OverflowList();
private PAG pag; // I think this is needed to get the size of the bit
// vector and the mask for casting
private int numElements = 0; // # of elements in the set
public int size() {
return numElements;
}
private class OverflowList {
public class ListNode {
public Node elem;
public ListNode next;
public ListNode(Node elem, ListNode next) {
this.elem = elem;
this.next = next;
}
}
public OverflowList() {
}
public OverflowList(PointsToBitVector bv) {
BitSetIterator it = bv.iterator(); // Iterates over only the 1 bits
while (it.hasNext()) {
// Get the next node in the bitset by looking it up in the
// pointer assignment graph.
// Ripped from BitPointsToSet.
Node n = (Node) (pag.getAllocNodeNumberer().get(it.next()));
add(n);
}
}
public void add(Node n) {
if (full()) {
throw new RuntimeException("Can't add an element to a full overflow list.");
}
overflow = new ListNode(n, overflow);
++overflowElements;
}
public int size() {
return overflowElements;
}
public boolean full() {
return overflowElements == OVERFLOW_SIZE;
}
public boolean contains(Node n) {
for (ListNode l = overflow; l != null; l = l.next) {
if (n == l.elem) {
return true;
}
}
return false;
}
public void removeAll() {
overflow = null;
overflowElements = 0;
}
/*
* public ListNode next() { return overflow.next; } public Node elem() { return overflow.elem; }
*/
public ListNode overflow = null; // Not shared with
// other points-to sets - the extra elements besides the ones in bitVector
private int overflowElements = 0; // # of elements actually in the
// array `overflow'
}
}
| 19,148
| 34.659218
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/SharedListSet.java
|
package soot.jimple.spark.sets;
/*-
* #%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.Type;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.util.BitVector;
/*
* Reference counting was amazingly difficult to get right, for the number of lines of
* code it makes up.
* Reference counting keeps track of how many things are pointing to a ListNode. When
* it has no more things pointing to it, it needs to be deleted from the HashMap.
*
* I think I finally got the correct algorithm for when to increase and when to decrease
* a node's reference count. It is:
* -When a new node is created (in makeNode), its "next" pointer will have an extra thing
* pointing at it, so increase its reference count.
* -When a new top-level pointer (a "SharedListSet.data member) is assigned to a node, it
* has one extra thing pointing at it, so increase its reference count.
* -Reference count decreases when a chain is detached. Detachment is bit of a complicated
* process; it should be described in my thesis.
*
*/
//Can't use java.lang.ref.WeakReferences instead because:
//The HashMap will now map WeakReferences (containing
//Pairs) to ListNodes, so its object will be null. But will it then hash to the same
//value after its object has become null?
//And it still seems like I'd have to remove the WeakReferences from the HashMap whose references
//have become null.
/*
* Ideas to speed things up:
* -For contains(), first check the index of all nodes to see whether the node exists
* in *any* points-to set.
* -I don't think this one will be very fast because if 2 lists are similar but differ in an
* element at the end of them, they can't be shared.
*/
/*
List is sorted.
Therefore:
contains: O(n)
add: O(n), and might add things to other lists too
*/
/**
* Implementation of a points-to set as a sorted list of elements, but where similar lists share parts of their data.
*/
public class SharedListSet extends PointsToSetInternal {
public SharedListSet(Type type, PAG pag) {
super(type);
this.pag = pag;
}
// Ripped from the other points-to sets - returns a factory that can be
// used to construct SharedHybridSets
public final static P2SetFactory getFactory() {
return new P2SetFactory() {
public final PointsToSetInternal newSet(Type type, PAG pag) {
return new SharedListSet(type, pag);
}
};
}
public boolean contains(Node n) {
for (ListNode i = data; i != null; i = i.next) {
if (i.elem == n) {
return true;
}
}
return false;
}
public boolean isEmpty() {
return data == null;
}
public boolean forall(P2SetVisitor v) {
for (ListNode i = data; i != null; i = i.next) {
v.visit(i.elem);
}
return v.getReturnValue();
}
private ListNode advanceExclude(ListNode exclude, ListNode other) {
// If exclude's node is less than other's first node, then there
// are elements to exclude that aren't in other, so keep advancing exclude
final int otherNum = other.elem.getNumber();
while (exclude != null && exclude.elem.getNumber() < otherNum) {
exclude = exclude.next;
}
return exclude;
}
private boolean excluded(ListNode exclude, ListNode other, BitVector mask) {
return (exclude != null && other.elem == exclude.elem) || (mask != null && (!(mask.get(other.elem.getNumber()))));
}
private ListNode union(ListNode first, ListNode other, ListNode exclude, BitVector mask, boolean detachChildren) {
// This algorithm must be recursive because we don't know whether to detach until
// we know the rest of the list.
if (first == null) {
if (other == null) {
return null;
}
// Normally, we could just return other in this case.
// But the problem is that there might be elements to exclude from other.
// We also can't modify other and remove elements from it, because that would
// remove elements from the points-to set whose elements are being added to this
// one.
// So we have to create a new list from scratch of the copies of the elements
// of other.
if (exclude == null && mask == null) {
return makeNode(other.elem, other.next);
// Can't just do:
// return other;
// because of the reference counting going on. (makeNode might increment
// the reference count.)
} else {
exclude = advanceExclude(exclude, other);
if (excluded(exclude, other, mask))
// If the first element of other is to be excluded
{
return union(first, other.next, exclude, mask, detachChildren);
} else {
return makeNode(other.elem, union(first, other.next, exclude, mask, detachChildren));
}
}
} else if (other == null) {
return first;
} else if (first == other) {
// We've found sharing - don't need to add any more
return first; // Doesn't matter what's being excluded, since it's all in first
} else {
ListNode retVal;
if (first.elem.getNumber() > other.elem.getNumber()) {
// Adding a new node, other.elem. But we might not have to add it if
// it's to be excluded.
exclude = advanceExclude(exclude, other);
if (excluded(exclude, other, mask))
// If the first element of other is to be excluded
{
retVal = union(first, other.next, exclude, mask, detachChildren);
} else {
retVal = makeNode(other.elem, union(first, other.next, exclude, mask, detachChildren));
}
} else {
if (first.refCount > 1) {
// if we're dealing with a shared node, stop detaching.
detachChildren = false;
}
// Doesn't matter whether it's being excluded; just add it once and advance
// both lists to the next node
if (first.elem == other.elem) {
// if both lists contain the element being added, only add it once
other = other.next;
}
retVal = makeNode(first.elem, union(first.next, other, exclude, mask, detachChildren));
if (detachChildren && first != retVal && first.next != null) {
first.next.decRefCount(); // When we advance "first" and copy its node into the
// output list, the old "first" will eventually be thrown away (unless other
// stuff points to it).
}
}
return retVal;
}
}
// Common function to prevent repeated code in add and addAll
private boolean addOrAddAll(ListNode first, ListNode other, ListNode exclude, BitVector mask) {
ListNode result = union(first, other, exclude, mask, true);
if (result == data) {
return false;
} else {
// result is about to have an extra thing pointing at it, and data is about to
// have one less thing pointing at it, so adjust the reference counts.
result.incRefCount();
if (data != null) {
data.decRefCount();
}
data = result;
return true;
}
}
public boolean add(Node n) {
// Prevent repeated code by saying add() is just a union() with one element in the
// set being merged in. add isn't called frequently anyway.
// However, we have to call makeNode() to get the node, in case it was already there
// and because union() assumes "other" is an existing node in another set. So we
// create the node for the duration of the call to addOrAddAll(), after which we
// delete it unless it was already there
ListNode other = makeNode(n, null);
other.incRefCount();
boolean added = addOrAddAll(data, other, null, null);
other.decRefCount(); // undo its creation
return added;
}
public boolean addAll(PointsToSetInternal other, PointsToSetInternal exclude) {
if (other == null) {
return false;
}
if ((!(other instanceof SharedListSet)) || (exclude != null && !(exclude instanceof SharedListSet))) {
return super.addAll(other, exclude);
} else {
SharedListSet realOther = (SharedListSet) other, realExclude = (SharedListSet) exclude;
BitVector mask = getBitMask(realOther, pag);
ListNode excludeData = (realExclude == null) ? null : realExclude.data;
return addOrAddAll(data, realOther.data, excludeData, mask);
}
}
// Holds pairs of (Node, ListNode)
public class Pair {
public Node first;
public ListNode second;
public Pair(Node first, ListNode second) {
this.first = first;
this.second = second;
}
public int hashCode() {
// I don't think the Node will ever be null
if (second == null) {
return first.hashCode();
} else {
return first.hashCode() + second.hashCode();
}
}
public boolean equals(Object other) {
if (!(other instanceof Pair)) {
return false;
}
Pair o = (Pair) other;
return ((first == null && o.first == null) || first == o.first)
&& ((second == null && o.second == null) || second == o.second);
}
}
// It's a bit confusing because there are nodes in the list and nodes in the PAG.
// Node means a node in the PAG, ListNode is for nodes in the list (each of which
// contains a Node as its data)
public class ListNode {
private Node elem;
private ListNode next = null;
public long refCount;
public ListNode(Node elem, ListNode next) {
this.elem = elem;
this.next = next;
refCount = 0; // When it's first created, it's being used exactly once
}
public void incRefCount() {
++refCount;
// Get an idea of how much sharing is taking place
// System.out.println(refCount);
}
public void decRefCount() {
if (--refCount == 0)
// if it's not being shared
{
// Remove the list from the HashMap if it's no longer used; otherwise
// the sharing won't really gain us memory.
AllSharedListNodes.v().allNodes.remove(new Pair(elem, next));
}
}
}
// I wanted to make this a static method of ListNode, but it
// wasn't working for some reason
private ListNode makeNode(Node elem, ListNode next) {
Pair p = new Pair(elem, next);
ListNode retVal = (AllSharedListNodes.v().allNodes.get(p));
if (retVal == null)
// if it's not an existing node
{
retVal = new ListNode(elem, next);
if (next != null) {
next.incRefCount(); // next now has an extra
}
// thing pointing at it (the newly created node)
AllSharedListNodes.v().allNodes.put(p, retVal);
}
return retVal;
}
// private final Map allNodes = AllSharedListNodes.v().allNodes;
// private static Map allNodes = new HashMap();
private PAG pag; // I think this is needed to get the size of the bit
// vector and the mask for casting
private ListNode data = null;
}
| 11,654
| 34
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/sets/SortedArraySet.java
|
package soot.jimple.spark.sets;
/*-
* #%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 soot.Type;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.util.BitVector;
/**
* Implementation of points-to set using a sorted array.
*
* @author Ondrej Lhotak
*/
public final class SortedArraySet extends PointsToSetInternal {
public SortedArraySet(Type type, PAG pag) {
super(type);
this.pag = pag;
}
/** Returns true if this set contains no run-time objects. */
public final boolean isEmpty() {
return size == 0;
}
/**
* Adds contents of other into this set, returns true if this set changed.
*/
public final boolean addAll(final PointsToSetInternal other, final PointsToSetInternal exclude) {
boolean ret = false;
BitVector typeMask = (pag.getTypeManager()).get(type);
if (other instanceof SortedArraySet) {
SortedArraySet o = (SortedArraySet) other;
Node[] mya = nodes;
Node[] oa = o.nodes;
int osize = o.size;
Node[] newa = new Node[size + osize];
int myi = 0;
int oi = 0;
int newi = 0;
for (;;) {
if (myi < size) {
if (oi < osize) {
int myhc = mya[myi].getNumber();
int ohc = oa[oi].getNumber();
if (myhc < ohc) {
newa[newi++] = mya[myi++];
} else if (myhc > ohc) {
if ((type == null || typeMask == null || typeMask.get(ohc))
&& (exclude == null || !exclude.contains(oa[oi]))) {
newa[newi++] = oa[oi];
ret = true;
}
oi++;
} else {
newa[newi++] = mya[myi++];
oi++;
}
} else { // oi >= osize
newa[newi++] = mya[myi++];
}
} else { // myi >= size
if (oi < osize) {
int ohc = oa[oi].getNumber();
if ((type == null || typeMask == null || typeMask.get(ohc)) && (exclude == null || !exclude.contains(oa[oi]))) {
newa[newi++] = oa[oi];
ret = true;
}
oi++;
} else {
break;
}
}
}
nodes = newa;
size = newi;
return ret;
}
return super.addAll(other, exclude);
}
/** Calls v's visit method on all nodes in this set. */
public final boolean forall(P2SetVisitor v) {
for (int i = 0; i < size; i++) {
v.visit(nodes[i]);
}
return v.getReturnValue();
}
/** Adds n to this set, returns true if n was not already in this set. */
public final boolean add(Node n) {
if (pag.getTypeManager().castNeverFails(n.getType(), type)) {
if (contains(n)) {
return false;
}
int left = 0;
int right = size;
int mid;
int hc = n.getNumber();
while (left < right) {
mid = (left + right) / 2;
int midhc = nodes[mid].getNumber();
if (midhc < hc) {
left = mid + 1;
} else if (midhc > hc) {
right = mid;
} else {
break;
}
}
if (nodes == null) {
nodes = new Node[size + 4];
} else if (size == nodes.length) {
Node[] newNodes = new Node[size + 4];
System.arraycopy(nodes, 0, newNodes, 0, nodes.length);
nodes = newNodes;
}
System.arraycopy(nodes, left, nodes, left + 1, size - left);
nodes[left] = n;
size++;
return true;
}
return false;
}
/** Returns true iff the set contains n. */
public final boolean contains(Node n) {
int left = 0;
int right = size;
int hc = n.getNumber();
while (left < right) {
int mid = (left + right) / 2;
int midhc = nodes[mid].getNumber();
if (midhc < hc) {
left = mid + 1;
} else if (midhc > hc) {
right = mid;
} else {
return true;
}
}
return false;
}
public final static P2SetFactory getFactory() {
return new P2SetFactory() {
public final PointsToSetInternal newSet(Type type, PAG pag) {
return new SortedArraySet(type, pag);
}
};
}
/* End of public methods. */
/* End of package methods. */
private Node[] nodes = null;
private int size = 0;
private PAG pag = null;
}
| 5,053
| 27.077778
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/Checker.java
|
package soot.jimple.spark.solver;
/*-
* #%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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.FastHierarchy;
import soot.jimple.spark.pag.AllocDotField;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
/**
* Checks points-to sets with pointer assignment graph to make sure everything has been correctly propagated.
*
* @author Ondrej Lhotak
*/
public class Checker {
private static final Logger logger = LoggerFactory.getLogger(Checker.class);
public Checker(PAG pag) {
this.pag = pag;
}
/** Actually does the propagation. */
public void check() {
for (Object object : pag.allocSources()) {
handleAllocNode((AllocNode) object);
}
for (Object object : pag.simpleSources()) {
handleSimples((VarNode) object);
}
for (Object object : pag.loadSources()) {
handleLoads((FieldRefNode) object);
}
for (Object object : pag.storeSources()) {
handleStores((VarNode) object);
}
}
/* End of public methods. */
/* End of package methods. */
protected void checkAll(final Node container, PointsToSetInternal nodes, final Node upstream) {
nodes.forall(new P2SetVisitor() {
public final void visit(Node n) {
checkNode(container, n, upstream);
}
});
}
protected void checkNode(Node container, Node n, Node upstream) {
if (container.getReplacement() != container) {
throw new RuntimeException("container " + container + " is illegal");
}
if (upstream.getReplacement() != upstream) {
throw new RuntimeException("upstream " + upstream + " is illegal");
}
PointsToSetInternal p2set = container.getP2Set();
FastHierarchy fh = pag.getTypeManager().getFastHierarchy();
if (!p2set.contains(n)
&& (fh == null || container.getType() == null || fh.canStoreType(n.getType(), container.getType()))) {
logger.debug("Check failure: " + container + " does not have " + n + "; upstream is " + upstream);
}
}
protected void handleAllocNode(AllocNode src) {
Node[] targets = pag.allocLookup(src);
for (Node element : targets) {
checkNode(element, src, src);
}
}
protected void handleSimples(VarNode src) {
PointsToSetInternal srcSet = src.getP2Set();
if (srcSet.isEmpty()) {
return;
}
final Node[] simpleTargets = pag.simpleLookup(src);
for (Node element : simpleTargets) {
checkAll(element, srcSet, src);
}
}
protected void handleStores(final VarNode src) {
final PointsToSetInternal srcSet = src.getP2Set();
if (srcSet.isEmpty()) {
return;
}
Node[] storeTargets = pag.storeLookup(src);
for (Node element : storeTargets) {
final FieldRefNode fr = (FieldRefNode) element;
final SparkField f = fr.getField();
fr.getBase().getP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, f);
checkAll(nDotF, srcSet, src);
}
});
}
}
protected void handleLoads(final FieldRefNode src) {
final Node[] loadTargets = pag.loadLookup(src);
final SparkField f = src.getField();
src.getBase().getP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = ((AllocNode) n).dot(f);
if (nDotF == null) {
return;
}
PointsToSetInternal set = nDotF.getP2Set();
if (set.isEmpty()) {
return;
}
for (Node element : loadTargets) {
VarNode target = (VarNode) element;
checkAll(target, set, src);
}
}
});
}
protected PAG pag;
}
| 4,733
| 29.941176
| 110
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/EBBCollapser.java
|
package soot.jimple.spark.solver;
/*-
* #%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.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Type;
import soot.jimple.spark.internal.TypeManager;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.VarNode;
/**
* Collapses nodes that are members of simple trees (EBBs) in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public class EBBCollapser {
private static final Logger logger = LoggerFactory.getLogger(EBBCollapser.class);
/** Actually collapse the EBBs in the PAG. */
public void collapse() {
boolean verbose = pag.getOpts().verbose();
if (verbose) {
logger.debug("" + "Total VarNodes: " + pag.getVarNodeNumberer().size() + ". Collapsing EBBs...");
}
collapseAlloc();
collapseLoad();
collapseSimple();
if (verbose) {
logger.debug("" + "" + numCollapsed + " nodes were collapsed.");
}
}
public EBBCollapser(PAG pag) {
this.pag = pag;
}
/* End of public methods. */
/* End of package methods. */
protected int numCollapsed = 0;
protected PAG pag;
protected void collapseAlloc() {
final boolean ofcg = (pag.getOnFlyCallGraph() != null);
for (Object object : pag.allocSources()) {
final AllocNode n = (AllocNode) object;
Node[] succs = pag.allocLookup(n);
VarNode firstSucc = null;
for (Node element0 : succs) {
VarNode succ = (VarNode) element0;
if (pag.allocInvLookup(succ).length > 1) {
continue;
}
if (pag.loadInvLookup(succ).length > 0) {
continue;
}
if (pag.simpleInvLookup(succ).length > 0) {
continue;
}
if (ofcg && succ.isInterProcTarget()) {
continue;
}
if (firstSucc == null) {
firstSucc = succ;
} else {
if (firstSucc.getType().equals(succ.getType())) {
firstSucc.mergeWith(succ);
numCollapsed++;
}
}
}
}
}
protected void collapseSimple() {
final boolean ofcg = (pag.getOnFlyCallGraph() != null);
final TypeManager typeManager = pag.getTypeManager();
boolean change;
do {
change = false;
for (Iterator<Object> nIt = new ArrayList<Object>(pag.simpleSources()).iterator(); nIt.hasNext();) {
final VarNode n = (VarNode) nIt.next();
Type nType = n.getType();
Node[] succs = pag.simpleLookup(n);
for (Node element : succs) {
VarNode succ = (VarNode) element;
Type sType = succ.getType();
if (!typeManager.castNeverFails(nType, sType)) {
continue;
}
if (pag.allocInvLookup(succ).length > 0) {
continue;
}
if (pag.loadInvLookup(succ).length > 0) {
continue;
}
if (pag.simpleInvLookup(succ).length > 1) {
continue;
}
if (ofcg && (succ.isInterProcTarget() || n.isInterProcSource())) {
continue;
}
n.mergeWith(succ);
change = true;
numCollapsed++;
}
}
} while (change);
}
protected void collapseLoad() {
final boolean ofcg = (pag.getOnFlyCallGraph() != null);
final TypeManager typeManager = pag.getTypeManager();
for (Iterator<Object> nIt = new ArrayList<Object>(pag.loadSources()).iterator(); nIt.hasNext();) {
final FieldRefNode n = (FieldRefNode) nIt.next();
Type nType = n.getType();
Node[] succs = pag.loadLookup(n);
Node firstSucc = null;
HashMap<Type, VarNode> typeToSucc = new HashMap<Type, VarNode>();
for (Node element : succs) {
VarNode succ = (VarNode) element;
Type sType = succ.getType();
if (pag.allocInvLookup(succ).length > 0) {
continue;
}
if (pag.loadInvLookup(succ).length > 1) {
continue;
}
if (pag.simpleInvLookup(succ).length > 0) {
continue;
}
if (ofcg && succ.isInterProcTarget()) {
continue;
}
if (typeManager.castNeverFails(nType, sType)) {
if (firstSucc == null) {
firstSucc = succ;
} else {
firstSucc.mergeWith(succ);
numCollapsed++;
}
} else {
VarNode rep = typeToSucc.get(succ.getType());
if (rep == null) {
typeToSucc.put(succ.getType(), succ);
} else {
rep.mergeWith(succ);
numCollapsed++;
}
}
}
}
}
}
| 5,532
| 28.908108
| 106
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/MergeChecker.java
|
package soot.jimple.spark.solver;
/*-
* #%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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.FastHierarchy;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
/**
* Checks points-to sets with pointer assignment graph to make sure everything has been correctly propagated.
*
* @author Ondrej Lhotak
*/
public class MergeChecker {
private static final Logger logger = LoggerFactory.getLogger(MergeChecker.class);
public MergeChecker(PAG pag) {
this.pag = pag;
}
/** Actually does the propagation. */
public void check() {
for (Object object : pag.allocSources()) {
handleAllocNode((AllocNode) object);
}
for (Object object : pag.simpleSources()) {
handleSimples((VarNode) object);
}
for (Object object : pag.loadSources()) {
handleLoads((FieldRefNode) object);
}
for (Object object : pag.storeSources()) {
handleStores((VarNode) object);
}
for (Object object : pag.loadSources()) {
final FieldRefNode fr = (FieldRefNode) object;
fieldToBase.put(fr.getField(), fr.getBase());
}
for (Object object : pag.storeInvSources()) {
final FieldRefNode fr = (FieldRefNode) object;
fieldToBase.put(fr.getField(), fr.getBase());
}
for (final VarNode src : pag.getVarNodeNumberer()) {
for (FieldRefNode fr : src.getAllFieldRefs()) {
for (VarNode dst : fieldToBase.get(fr.getField())) {
if (!src.getP2Set().hasNonEmptyIntersection(dst.getP2Set())) {
continue;
}
FieldRefNode fr2 = dst.dot(fr.getField());
if (fr2.getReplacement() != fr.getReplacement()) {
logger.debug("Check failure: " + fr + " should be merged with " + fr2);
}
}
}
}
}
/* End of public methods. */
/* End of package methods. */
protected void checkAll(final Node container, PointsToSetInternal nodes, final Node upstream) {
nodes.forall(new P2SetVisitor() {
public final void visit(Node n) {
checkNode(container, n, upstream);
}
});
}
protected void checkNode(Node container, Node n, Node upstream) {
if (container.getReplacement() != container) {
throw new RuntimeException("container " + container + " is illegal");
}
if (upstream.getReplacement() != upstream) {
throw new RuntimeException("upstream " + upstream + " is illegal");
}
PointsToSetInternal p2set = container.getP2Set();
FastHierarchy fh = pag.getTypeManager().getFastHierarchy();
if (!p2set.contains(n)
&& (fh == null || container.getType() == null || fh.canStoreType(n.getType(), container.getType()))) {
logger.debug("Check failure: " + container + " does not have " + n + "; upstream is " + upstream);
}
}
protected void handleAllocNode(AllocNode src) {
Node[] targets = pag.allocLookup(src);
for (Node element : targets) {
checkNode(element, src, src);
}
}
protected void handleSimples(VarNode src) {
PointsToSetInternal srcSet = src.getP2Set();
if (srcSet.isEmpty()) {
return;
}
final Node[] simpleTargets = pag.simpleLookup(src);
for (Node element : simpleTargets) {
checkAll(element, srcSet, src);
}
}
protected void handleStores(final VarNode src) {
final PointsToSetInternal srcSet = src.getP2Set();
if (srcSet.isEmpty()) {
return;
}
Node[] storeTargets = pag.storeLookup(src);
for (Node element : storeTargets) {
final FieldRefNode fr = (FieldRefNode) element;
checkAll(fr, srcSet, src);
}
}
protected void handleLoads(final FieldRefNode src) {
final Node[] loadTargets = pag.loadLookup(src);
PointsToSetInternal set = src.getP2Set();
if (set.isEmpty()) {
return;
}
for (Node element : loadTargets) {
VarNode target = (VarNode) element;
checkAll(target, set, src);
}
}
protected PAG pag;
protected MultiMap<SparkField, VarNode> fieldToBase = new HashMultiMap<SparkField, VarNode>();
}
| 5,150
| 30.796296
| 110
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/OnFlyCallGraph.java
|
package soot.jimple.spark.solver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 - 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Context;
import soot.Local;
import soot.MethodOrMethodContext;
import soot.Scene;
import soot.Type;
import soot.jimple.IntConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.spark.pag.AllocDotField;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.ArrayElement;
import soot.jimple.spark.pag.MethodPAG;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.StringConstantNode;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.CallGraphBuilder;
import soot.jimple.toolkits.callgraph.ContextManager;
import soot.jimple.toolkits.callgraph.Edge;
import soot.jimple.toolkits.callgraph.OnFlyCallGraphBuilder;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.options.Options;
import soot.util.queue.QueueReader;
/**
* The interface between the pointer analysis engine and the on-the-fly call graph builder.
*
* @author Ondrej Lhotak
*/
public class OnFlyCallGraph {
protected final OnFlyCallGraphBuilder ofcgb;
protected final ReachableMethods reachableMethods;
protected final QueueReader<MethodOrMethodContext> reachablesReader;
protected final QueueReader<Edge> callEdges;
protected final CallGraph callGraph;
private static final Logger logger = LoggerFactory.getLogger(OnFlyCallGraph.class);
public ReachableMethods reachableMethods() {
return reachableMethods;
}
public CallGraph callGraph() {
return callGraph;
}
public OnFlyCallGraph(PAG pag, boolean appOnly) {
this.pag = pag;
callGraph = Scene.v().internalMakeCallGraph();
Scene.v().setCallGraph(callGraph);
ContextManager cm = CallGraphBuilder.makeContextManager(callGraph);
reachableMethods = Scene.v().getReachableMethods();
ofcgb = createOnFlyCallGraphBuilder(cm, reachableMethods, appOnly);
reachablesReader = reachableMethods.listener();
callEdges = cm.callGraph().listener();
}
/**
* Factory method for creating a new on-fly callgraph builder. Custom implementations can override this method for
* injecting own callgraph builders without having to modify Soot.
*
* @param cm
* The context manager
* @param reachableMethods
* The reachable method set
* @param appOnly
* True to only consider application code
* @return The new on-fly callgraph builder
*/
protected OnFlyCallGraphBuilder createOnFlyCallGraphBuilder(ContextManager cm, ReachableMethods reachableMethods,
boolean appOnly) {
return new OnFlyCallGraphBuilder(cm, reachableMethods, appOnly);
}
public void build() {
ofcgb.processReachables();
processReachables();
processCallEdges();
}
private void processReachables() {
reachableMethods.update();
while (reachablesReader.hasNext()) {
MethodOrMethodContext m = reachablesReader.next();
MethodPAG mpag = MethodPAG.v(pag, m.method());
try {
mpag.build();
} catch (Exception e) {
String msg = String.format("An error occurred while processing %s in callgraph", mpag.getMethod());
if (Options.v().allow_cg_errors()) {
logger.error(msg, e);
} else {
throw new RuntimeException(msg, e);
}
}
mpag.addToPAG(m.context());
}
}
private void processCallEdges() {
while (callEdges.hasNext()) {
Edge e = callEdges.next();
MethodPAG amp = MethodPAG.v(pag, e.tgt());
amp.build();
amp.addToPAG(e.tgtCtxt());
pag.addCallTarget(e);
}
}
public OnFlyCallGraphBuilder ofcgb() {
return ofcgb;
}
public void updatedFieldRef(final AllocDotField df, PointsToSetInternal ptsi) {
if (df.getField() != ArrayElement.v()) {
return;
}
if (ofcgb.wantArrayField(df)) {
ptsi.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
ofcgb.addInvokeArgType(df, null, n.getType());
}
});
}
}
public void updatedNode(VarNode vn) {
Object r = vn.getVariable();
if (!(r instanceof Local)) {
return;
}
final Local receiver = (Local) r;
final Context context = vn.context();
PointsToSetInternal p2set = vn.getP2Set().getNewSet();
if (ofcgb.wantTypes(receiver)) {
p2set.forall(new P2SetVisitor() {
public final void visit(Node n) {
if (n instanceof AllocNode) {
ofcgb.addType(receiver, context, n.getType(), (AllocNode) n);
}
}
});
}
if (ofcgb.wantStringConstants(receiver)) {
p2set.forall(new P2SetVisitor() {
public final void visit(Node n) {
if (n instanceof StringConstantNode) {
String constant = ((StringConstantNode) n).getString();
ofcgb.addStringConstant(receiver, context, constant);
} else {
ofcgb.addStringConstant(receiver, context, null);
}
}
});
}
if (ofcgb.wantInvokeArg(receiver)) {
p2set.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (n instanceof AllocNode) {
AllocNode an = ((AllocNode) n);
ofcgb.addInvokeArgDotField(receiver, pag.makeAllocDotField(an, ArrayElement.v()));
assert an.getNewExpr() instanceof NewArrayExpr;
NewArrayExpr nae = (NewArrayExpr) an.getNewExpr();
if (!(nae.getSize() instanceof IntConstant)) {
ofcgb.setArgArrayNonDetSize(receiver, context);
} else {
IntConstant sizeConstant = (IntConstant) nae.getSize();
ofcgb.addPossibleArgArraySize(receiver, sizeConstant.value, context);
}
}
}
});
for (Type ty : pag.reachingObjectsOfArrayElement(p2set).possibleTypes()) {
ofcgb.addInvokeArgType(receiver, context, ty);
}
}
}
/** Node uses this to notify PAG that n2 has been merged into n1. */
public void mergedWith(Node n1, Node n2) {
}
/* End of public methods. */
/* End of package methods. */
private PAG pag;
}
| 7,123
| 31.381818
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/PropAlias.java
|
package soot.jimple.spark.solver;
/*-
* #%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.HashSet;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.Type;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.ClassConstantNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.NewInstanceNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.EmptyPointsToSet;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.util.HashMultiMap;
import soot.util.LargeNumberedMap;
import soot.util.MultiMap;
import soot.util.queue.QueueReader;
/**
* Propagates points-to sets along pointer assignment graph using a relevant aliases.
*
* @author Ondrej Lhotak
*/
public class PropAlias extends Propagator {
private static final Logger logger = LoggerFactory.getLogger(PropAlias.class);
protected final Set<VarNode> varNodeWorkList = new TreeSet<VarNode>();
protected Set<VarNode> aliasWorkList;
protected Set<FieldRefNode> fieldRefWorkList = new HashSet<FieldRefNode>();
protected Set<FieldRefNode> outFieldRefWorkList = new HashSet<FieldRefNode>();
public PropAlias(PAG pag) {
this.pag = pag;
loadSets = new LargeNumberedMap<FieldRefNode, PointsToSetInternal>(pag.getFieldRefNodeNumberer());
}
/** Actually does the propagation. */
public void propagate() {
ofcg = pag.getOnFlyCallGraph();
new TopoSorter(pag, false).sort();
for (Object object : pag.loadSources()) {
final FieldRefNode fr = (FieldRefNode) object;
fieldToBase.put(fr.getField(), fr.getBase());
}
for (Object object : pag.storeInvSources()) {
final FieldRefNode fr = (FieldRefNode) object;
fieldToBase.put(fr.getField(), fr.getBase());
}
for (Object object : pag.allocSources()) {
handleAllocNode((AllocNode) object);
}
boolean verbose = pag.getOpts().verbose();
do {
if (verbose) {
logger.debug("Worklist has " + varNodeWorkList.size() + " nodes.");
}
aliasWorkList = new HashSet<VarNode>();
while (!varNodeWorkList.isEmpty()) {
VarNode src = varNodeWorkList.iterator().next();
varNodeWorkList.remove(src);
aliasWorkList.add(src);
handleVarNode(src);
}
if (verbose) {
logger.debug("Now handling field references");
}
for (VarNode src : aliasWorkList) {
for (FieldRefNode srcFr : src.getAllFieldRefs()) {
SparkField field = srcFr.getField();
for (VarNode dst : fieldToBase.get(field)) {
if (src.getP2Set().hasNonEmptyIntersection(dst.getP2Set())) {
FieldRefNode dstFr = dst.dot(field);
aliasEdges.put(srcFr, dstFr);
aliasEdges.put(dstFr, srcFr);
fieldRefWorkList.add(srcFr);
fieldRefWorkList.add(dstFr);
if (makeP2Set(dstFr).addAll(srcFr.getP2Set().getOldSet(), null)) {
outFieldRefWorkList.add(dstFr);
}
if (makeP2Set(srcFr).addAll(dstFr.getP2Set().getOldSet(), null)) {
outFieldRefWorkList.add(srcFr);
}
}
}
}
}
for (FieldRefNode src : fieldRefWorkList) {
for (FieldRefNode dst : aliasEdges.get(src)) {
if (makeP2Set(dst).addAll(src.getP2Set().getNewSet(), null)) {
outFieldRefWorkList.add(dst);
}
}
src.getP2Set().flushNew();
}
fieldRefWorkList = new HashSet<FieldRefNode>();
for (FieldRefNode src : outFieldRefWorkList) {
PointsToSetInternal set = getP2Set(src).getNewSet();
if (set.isEmpty()) {
continue;
}
Node[] targets = pag.loadLookup(src);
for (Node element0 : targets) {
VarNode target = (VarNode) element0;
if (target.makeP2Set().addAll(set, null)) {
addToWorklist(target);
}
}
getP2Set(src).flushNew();
}
outFieldRefWorkList = new HashSet<FieldRefNode>();
} while (!varNodeWorkList.isEmpty());
}
/* End of public methods. */
/* End of package methods. */
/**
* Propagates new points-to information of node src to all its successors.
*/
protected boolean handleAllocNode(AllocNode src) {
boolean ret = false;
Node[] targets = pag.allocLookup(src);
for (Node element : targets) {
if (element.makeP2Set().add(src)) {
addToWorklist((VarNode) element);
ret = true;
}
}
return ret;
}
/**
* Propagates new points-to information of node src to all its successors.
*/
protected boolean handleVarNode(final VarNode src) {
boolean ret = false;
if (src.getReplacement() != src) {
throw new RuntimeException("Got bad node " + src + " with rep " + src.getReplacement());
}
final PointsToSetInternal newP2Set = src.getP2Set().getNewSet();
if (newP2Set.isEmpty()) {
return false;
}
if (ofcg != null) {
QueueReader<Node> addedEdges = pag.edgeReader();
ofcg.updatedNode(src);
ofcg.build();
while (addedEdges.hasNext()) {
Node addedSrc = (Node) addedEdges.next();
Node addedTgt = (Node) addedEdges.next();
ret = true;
if (addedSrc instanceof VarNode) {
VarNode edgeSrc = (VarNode) addedSrc;
if (addedTgt instanceof VarNode) {
VarNode edgeTgt = (VarNode) addedTgt;
if (edgeTgt.makeP2Set().addAll(edgeSrc.getP2Set(), null)) {
addToWorklist(edgeTgt);
}
} else if (addedTgt instanceof NewInstanceNode) {
NewInstanceNode edgeTgt = (NewInstanceNode) addedTgt.getReplacement();
if (edgeTgt.makeP2Set().addAll(edgeSrc.getP2Set(), null)) {
for (Node element : pag.assignInstanceLookup(edgeTgt)) {
addToWorklist((VarNode) element);
}
}
}
} else if (addedSrc instanceof AllocNode) {
AllocNode edgeSrc = (AllocNode) addedSrc;
VarNode edgeTgt = (VarNode) addedTgt;
if (edgeTgt.makeP2Set().add(edgeSrc)) {
addToWorklist(edgeTgt);
}
} else if (addedSrc instanceof NewInstanceNode && addedTgt instanceof VarNode) {
final NewInstanceNode edgeSrc = (NewInstanceNode) addedSrc.getReplacement();
final VarNode edgeTgt = (VarNode) addedTgt.getReplacement();
addedSrc.getP2Set().forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (n instanceof ClassConstantNode) {
ClassConstantNode ccn = (ClassConstantNode) n;
Type ccnType = ccn.getClassConstant().toSootType();
// If the referenced class has not been loaded,
// we do this now
SootClass targetClass = ((RefType) ccnType).getSootClass();
if (targetClass.resolvingLevel() == SootClass.DANGLING) {
Scene.v().forceResolve(targetClass.getName(), SootClass.SIGNATURES);
}
edgeTgt.makeP2Set().add(pag.makeAllocNode(edgeSrc.getValue(), ccnType, ccn.getMethod()));
addToWorklist(edgeTgt);
}
}
});
}
FieldRefNode frn = null;
if (addedSrc instanceof FieldRefNode) {
frn = (FieldRefNode) addedSrc;
}
if (addedTgt instanceof FieldRefNode) {
frn = (FieldRefNode) addedTgt;
}
if (frn != null) {
VarNode base = frn.getBase();
if (fieldToBase.put(frn.getField(), base)) {
aliasWorkList.add(base);
}
}
}
}
Node[] simpleTargets = pag.simpleLookup(src);
for (Node element : simpleTargets) {
if (element.makeP2Set().addAll(newP2Set, null)) {
addToWorklist((VarNode) element);
ret = true;
}
}
Node[] storeTargets = pag.storeLookup(src);
for (Node element : storeTargets) {
final FieldRefNode fr = (FieldRefNode) element;
if (fr.makeP2Set().addAll(newP2Set, null)) {
fieldRefWorkList.add(fr);
ret = true;
}
}
src.getP2Set().flushNew();
return ret;
}
protected final PointsToSetInternal makeP2Set(FieldRefNode n) {
PointsToSetInternal ret = loadSets.get(n);
if (ret == null) {
ret = pag.getSetFactory().newSet(null, pag);
loadSets.put(n, ret);
}
return ret;
}
protected final PointsToSetInternal getP2Set(FieldRefNode n) {
PointsToSetInternal ret = loadSets.get(n);
if (ret == null) {
return EmptyPointsToSet.v();
}
return ret;
}
private boolean addToWorklist(VarNode n) {
if (n.getReplacement() != n) {
throw new RuntimeException("Adding bad node " + n + " with rep " + n.getReplacement());
}
return varNodeWorkList.add(n);
}
protected PAG pag;
protected MultiMap<SparkField, VarNode> fieldToBase = new HashMultiMap<SparkField, VarNode>();
protected MultiMap<FieldRefNode, FieldRefNode> aliasEdges = new HashMultiMap<FieldRefNode, FieldRefNode>();
protected LargeNumberedMap<FieldRefNode, PointsToSetInternal> loadSets;
protected OnFlyCallGraph ofcg;
}
| 10,297
| 32.653595
| 109
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/PropCycle.java
|
package soot.jimple.spark.solver;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.jimple.spark.pag.AllocDotField;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.util.LargeNumberedMap;
/**
* Propagates points-to sets using an on-line cycle detection algorithm based on Heintze and Tardieu, PLDI 2000.
*
* @author Ondrej Lhotak
*/
public class PropCycle extends Propagator {
private static final Logger logger = LoggerFactory.getLogger(PropCycle.class);
public PropCycle(PAG pag) {
this.pag = pag;
varNodeToIteration = new LargeNumberedMap<VarNode, Integer>(pag.getVarNodeNumberer());
}
/** Actually does the propagation. */
public void propagate() {
ofcg = pag.getOnFlyCallGraph();
boolean verbose = pag.getOpts().verbose();
Collection<VarNode> bases = new HashSet<VarNode>();
for (FieldRefNode frn : pag.getFieldRefNodeNumberer()) {
bases.add(frn.getBase());
}
bases = new ArrayList<VarNode>(bases);
int iteration = 0;
boolean changed;
boolean finalIter = false;
do {
changed = false;
iteration++;
currentIteration = new Integer(iteration);
if (verbose) {
logger.debug("Iteration: " + iteration);
}
for (VarNode v : bases) {
changed = computeP2Set((VarNode) v.getReplacement(), new ArrayList<VarNode>()) | changed;
}
if (ofcg != null) {
throw new RuntimeException("NYI");
}
if (verbose) {
logger.debug("Processing stores");
}
for (Object object : pag.storeSources()) {
final VarNode src = (VarNode) object;
Node[] targets = pag.storeLookup(src);
for (Node element0 : targets) {
final FieldRefNode target = (FieldRefNode) element0;
changed = target.getBase().makeP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, target.getField());
nDotF.makeP2Set().addAll(src.getP2Set(), null);
}
}) | changed;
}
}
if (!changed && !finalIter) {
finalIter = true;
if (verbose) {
logger.debug("Doing full graph");
}
bases = new ArrayList<VarNode>(pag.getVarNodeNumberer().size());
for (VarNode v : pag.getVarNodeNumberer()) {
bases.add(v);
}
changed = true;
}
} while (changed);
}
/* End of public methods. */
/* End of package methods. */
private boolean computeP2Set(final VarNode v, ArrayList<VarNode> path) {
boolean ret = false;
if (path.contains(v)) {
// for( Iterator<VarNode> nIt = path.iterator(); nIt.hasNext(); ) {
// final Node n = nIt.next();
// if( n != v ) n.mergeWith( v );
// }
return false;
}
final Integer vnIteration = varNodeToIteration.get(v);
if (currentIteration != null && vnIteration != null && currentIteration.intValue() == vnIteration.intValue()) {
return false;
}
varNodeToIteration.put(v, currentIteration);
path.add(v);
if (v.getP2Set().isEmpty()) {
Node[] srcs = pag.allocInvLookup(v);
for (Node element : srcs) {
ret = v.makeP2Set().add(element) | ret;
}
}
{
Node[] srcs = pag.simpleInvLookup(v);
for (Node element : srcs) {
VarNode src = (VarNode) element;
ret = computeP2Set(src, path) | ret;
ret = v.makeP2Set().addAll(src.getP2Set(), null) | ret;
}
}
{
Node[] srcs = pag.loadInvLookup(v);
for (Node element : srcs) {
final FieldRefNode src = (FieldRefNode) element;
ret = src.getBase().getP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocNode an = (AllocNode) n;
AllocDotField adf = pag.makeAllocDotField(an, src.getField());
returnValue = v.makeP2Set().addAll(adf.getP2Set(), null) | returnValue;
}
}) | ret;
}
}
path.remove(path.size() - 1);
return ret;
}
private PAG pag;
private OnFlyCallGraph ofcg;
private Integer currentIteration;
private final LargeNumberedMap<VarNode, Integer> varNodeToIteration;
}
| 5,319
| 30.666667
| 115
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/PropIter.java
|
package soot.jimple.spark.solver;
/*-
* #%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.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.Type;
import soot.jimple.spark.pag.AllocDotField;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.ClassConstantNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.NewInstanceNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.util.queue.QueueReader;
/**
* Propagates points-to sets along pointer assignment graph using iteration.
*
* @author Ondrej Lhotak
*/
public class PropIter extends Propagator {
private static final Logger logger = LoggerFactory.getLogger(PropIter.class);
public PropIter(PAG pag) {
this.pag = pag;
}
/** Actually does the propagation. */
public void propagate() {
final OnFlyCallGraph ofcg = pag.getOnFlyCallGraph();
new TopoSorter(pag, false).sort();
for (Object object : pag.allocSources()) {
handleAllocNode((AllocNode) object);
}
int iteration = 1;
boolean change;
do {
change = false;
TreeSet<VarNode> simpleSources = new TreeSet<VarNode>(pag.simpleSources());
if (pag.getOpts().verbose()) {
logger.debug("Iteration " + (iteration++));
}
for (VarNode object : simpleSources) {
change = handleSimples(object) | change;
}
if (ofcg != null) {
QueueReader<Node> addedEdges = pag.edgeReader();
for (VarNode src : pag.getVarNodeNumberer()) {
ofcg.updatedNode(src);
}
ofcg.build();
while (addedEdges.hasNext()) {
Node addedSrc = (Node) addedEdges.next();
Node addedTgt = (Node) addedEdges.next();
change = true;
if (addedSrc instanceof VarNode) {
PointsToSetInternal p2set = ((VarNode) addedSrc).getP2Set();
if (p2set != null) {
p2set.unFlushNew();
}
} else if (addedSrc instanceof AllocNode) {
((VarNode) addedTgt).makeP2Set().add(addedSrc);
}
}
if (change) {
new TopoSorter(pag, false).sort();
}
}
for (FieldRefNode object : pag.loadSources()) {
change = handleLoads(object) | change;
}
for (VarNode object : pag.storeSources()) {
change = handleStores(object) | change;
}
for (NewInstanceNode object : pag.assignInstanceSources()) {
change = handleNewInstances(object) | change;
}
} while (change);
}
/* End of public methods. */
/* End of package methods. */
/**
* Propagates new points-to information of node src to all its successors.
*/
protected boolean handleAllocNode(AllocNode src) {
boolean ret = false;
Node[] targets = pag.allocLookup(src);
for (Node element : targets) {
ret = element.makeP2Set().add(src) | ret;
}
return ret;
}
protected boolean handleSimples(VarNode src) {
boolean ret = false;
PointsToSetInternal srcSet = src.getP2Set();
if (srcSet.isEmpty()) {
return false;
}
Node[] simpleTargets = pag.simpleLookup(src);
for (Node element : simpleTargets) {
ret = element.makeP2Set().addAll(srcSet, null) | ret;
}
Node[] newInstances = pag.newInstanceLookup(src);
for (Node element : newInstances) {
ret = element.makeP2Set().addAll(srcSet, null) | ret;
}
return ret;
}
protected boolean handleStores(VarNode src) {
boolean ret = false;
final PointsToSetInternal srcSet = src.getP2Set();
if (srcSet.isEmpty()) {
return false;
}
Node[] storeTargets = pag.storeLookup(src);
for (Node element : storeTargets) {
final FieldRefNode fr = (FieldRefNode) element;
final SparkField f = fr.getField();
ret = fr.getBase().getP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, f);
if (nDotF.makeP2Set().addAll(srcSet, null)) {
returnValue = true;
}
}
}) | ret;
}
return ret;
}
protected boolean handleLoads(FieldRefNode src) {
boolean ret = false;
final Node[] loadTargets = pag.loadLookup(src);
final SparkField f = src.getField();
ret = src.getBase().getP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = ((AllocNode) n).dot(f);
if (nDotF == null) {
return;
}
PointsToSetInternal set = nDotF.getP2Set();
if (set.isEmpty()) {
return;
}
for (Node element : loadTargets) {
VarNode target = (VarNode) element;
if (target.makeP2Set().addAll(set, null)) {
returnValue = true;
}
}
}
}) | ret;
return ret;
}
protected boolean handleNewInstances(final NewInstanceNode src) {
boolean ret = false;
final Node[] newInstances = pag.assignInstanceLookup(src);
for (final Node instance : newInstances) {
ret = src.getP2Set().forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (n instanceof ClassConstantNode) {
ClassConstantNode ccn = (ClassConstantNode) n;
Type ccnType = ccn.getClassConstant().toSootType();
// If the referenced class has not been loaded, we do
// this now
SootClass targetClass = ((RefType) ccnType).getSootClass();
if (targetClass.resolvingLevel() == SootClass.DANGLING) {
Scene.v().forceResolve(targetClass.getName(), SootClass.SIGNATURES);
}
instance.makeP2Set().add(pag.makeAllocNode(src.getValue(), ccnType, ccn.getMethod()));
}
}
});
}
return ret;
}
protected PAG pag;
}
| 6,900
| 29.671111
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/PropMerge.java
|
package soot.jimple.spark.solver;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.jimple.spark.pag.AllocDotField;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
/**
* Propagates points-to sets along pointer assignment graph using a merging of field reference (Red) nodes to improve
* scalability.
*
* @author Ondrej Lhotak
*/
public class PropMerge extends Propagator {
private static final Logger logger = LoggerFactory.getLogger(PropMerge.class);
protected final Set<Node> varNodeWorkList = new TreeSet<Node>();
public PropMerge(PAG pag) {
this.pag = pag;
}
/** Actually does the propagation. */
public void propagate() {
new TopoSorter(pag, false).sort();
for (Object object : pag.allocSources()) {
handleAllocNode((AllocNode) object);
}
boolean verbose = pag.getOpts().verbose();
do {
if (verbose) {
logger.debug("Worklist has " + varNodeWorkList.size() + " nodes.");
}
int iter = 0;
while (!varNodeWorkList.isEmpty()) {
VarNode src = (VarNode) varNodeWorkList.iterator().next();
varNodeWorkList.remove(src);
handleVarNode(src);
if (verbose) {
iter++;
if (iter >= 1000) {
iter = 0;
logger.debug("Worklist has " + varNodeWorkList.size() + " nodes.");
}
}
}
if (verbose) {
logger.debug("Now handling field references");
}
for (Object object : pag.storeSources()) {
final VarNode src = (VarNode) object;
Node[] storeTargets = pag.storeLookup(src);
for (Node element0 : storeTargets) {
final FieldRefNode fr = (FieldRefNode) element0;
fr.makeP2Set().addAll(src.getP2Set(), null);
}
}
for (Object object : pag.loadSources()) {
final FieldRefNode src = (FieldRefNode) object;
if (src != src.getReplacement()) {
throw new RuntimeException("shouldn't happen");
}
Node[] targets = pag.loadLookup(src);
for (Node element0 : targets) {
VarNode target = (VarNode) element0;
if (target.makeP2Set().addAll(src.getP2Set(), null)) {
varNodeWorkList.add(target);
}
}
}
} while (!varNodeWorkList.isEmpty());
}
/* End of public methods. */
/* End of package methods. */
/**
* Propagates new points-to information of node src to all its successors.
*/
protected boolean handleAllocNode(AllocNode src) {
boolean ret = false;
Node[] targets = pag.allocLookup(src);
for (Node element : targets) {
if (element.makeP2Set().add(src)) {
varNodeWorkList.add(element);
ret = true;
}
}
return ret;
}
/**
* Propagates new points-to information of node src to all its successors.
*/
protected boolean handleVarNode(final VarNode src) {
boolean ret = false;
if (src.getReplacement() != src) {
return ret;
/*
* throw new RuntimeException( "Got bad node "+src+" with rep "+src.getReplacement() );
*/
}
final PointsToSetInternal newP2Set = src.getP2Set();
if (newP2Set.isEmpty()) {
return false;
}
Node[] simpleTargets = pag.simpleLookup(src);
for (Node element : simpleTargets) {
if (element.makeP2Set().addAll(newP2Set, null)) {
varNodeWorkList.add(element);
ret = true;
}
}
Node[] storeTargets = pag.storeLookup(src);
for (Node element : storeTargets) {
final FieldRefNode fr = (FieldRefNode) element;
if (fr.makeP2Set().addAll(newP2Set, null)) {
ret = true;
}
}
for (final FieldRefNode fr : src.getAllFieldRefs()) {
final SparkField field = fr.getField();
ret = newP2Set.forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, field);
Node nDotFNode = nDotF.getReplacement();
if (nDotFNode != fr) {
fr.mergeWith(nDotFNode);
returnValue = true;
}
}
}) | ret;
}
// src.getP2Set().flushNew();
return ret;
}
protected PAG pag;
}
| 5,332
| 28.793296
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/PropWorklist.java
|
package soot.jimple.spark.solver;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 - 2006 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.Type;
import soot.jimple.spark.pag.AllocDotField;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.ClassConstantNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.NewInstanceNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.util.queue.QueueReader;
/**
* Propagates points-to sets along pointer assignment graph using a worklist.
*
* @author Ondrej Lhotak
*/
public class PropWorklist extends Propagator {
private static final Logger logger = LoggerFactory.getLogger(PropWorklist.class);
protected final Set<VarNode> varNodeWorkList = new TreeSet<VarNode>();
public PropWorklist(PAG pag) {
this.pag = pag;
}
/** Actually does the propagation. */
public void propagate() {
ofcg = pag.getOnFlyCallGraph();
new TopoSorter(pag, false).sort();
for (AllocNode object : pag.allocSources()) {
handleAllocNode(object);
}
boolean verbose = pag.getOpts().verbose();
do {
if (verbose) {
logger.debug("Worklist has " + varNodeWorkList.size() + " nodes.");
}
while (!varNodeWorkList.isEmpty()) {
VarNode src = varNodeWorkList.iterator().next();
varNodeWorkList.remove(src);
handleVarNode(src);
}
if (verbose) {
logger.debug("Now handling field references");
}
for (VarNode src : pag.storeSources()) {
Node[] targets = pag.storeLookup(src);
for (Node element0 : targets) {
final FieldRefNode target = (FieldRefNode) element0;
target.getBase().makeP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, target.getField());
if (ofcg != null) {
ofcg.updatedFieldRef(nDotF, src.getP2Set());
}
nDotF.makeP2Set().addAll(src.getP2Set(), null);
}
});
}
}
HashSet<Object[]> edgesToPropagate = new HashSet<Object[]>();
for (FieldRefNode object : pag.loadSources()) {
handleFieldRefNode(object, edgesToPropagate);
}
Set<PointsToSetInternal> nodesToFlush = Collections.newSetFromMap(new IdentityHashMap<PointsToSetInternal, Boolean>());
for (Object[] pair : edgesToPropagate) {
PointsToSetInternal nDotF = (PointsToSetInternal) pair[0];
PointsToSetInternal newP2Set = nDotF.getNewSet();
VarNode loadTarget = (VarNode) pair[1];
if (loadTarget.makeP2Set().addAll(newP2Set, null)) {
varNodeWorkList.add(loadTarget);
}
nodesToFlush.add(nDotF);
}
for (PointsToSetInternal nDotF : nodesToFlush) {
nDotF.flushNew();
}
} while (!varNodeWorkList.isEmpty());
}
/* End of public methods. */
/* End of package methods. */
/**
* Propagates new points-to information of node src to all its successors.
*/
protected boolean handleAllocNode(AllocNode src) {
boolean ret = false;
Node[] targets = pag.allocLookup(src);
for (Node element : targets) {
if (element.makeP2Set().add(src)) {
varNodeWorkList.add((VarNode) element);
ret = true;
}
}
return ret;
}
/**
* Propagates new points-to information of node src to all its successors.
*/
protected boolean handleVarNode(final VarNode src) {
boolean ret = false;
boolean flush = true;
if (src.getReplacement() != src) {
throw new RuntimeException("Got bad node " + src + " with rep " + src.getReplacement());
}
final PointsToSetInternal newP2Set = src.getP2Set().getNewSet();
if (newP2Set.isEmpty()) {
return false;
}
if (ofcg != null) {
QueueReader<Node> addedEdges = pag.edgeReader();
ofcg.updatedNode(src);
ofcg.build();
while (addedEdges.hasNext()) {
Node addedSrc = (Node) addedEdges.next();
Node addedTgt = (Node) addedEdges.next();
ret = true;
if (addedSrc instanceof VarNode) {
VarNode edgeSrc = (VarNode) addedSrc.getReplacement();
if (addedTgt instanceof VarNode) {
VarNode edgeTgt = (VarNode) addedTgt.getReplacement();
if (edgeTgt.makeP2Set().addAll(edgeSrc.getP2Set(), null)) {
varNodeWorkList.add(edgeTgt);
if (edgeTgt == src) {
flush = false;
}
}
} else if (addedTgt instanceof NewInstanceNode) {
NewInstanceNode edgeTgt = (NewInstanceNode) addedTgt.getReplacement();
if (edgeTgt.makeP2Set().addAll(edgeSrc.getP2Set(), null)) {
for (Node element : pag.assignInstanceLookup(edgeTgt)) {
varNodeWorkList.add((VarNode) element);
if (element == src) {
flush = false;
}
}
}
}
} else if (addedSrc instanceof AllocNode) {
VarNode edgeTgt = (VarNode) addedTgt.getReplacement();
if (edgeTgt.makeP2Set().add(addedSrc)) {
varNodeWorkList.add(edgeTgt);
if (edgeTgt == src) {
flush = false;
}
}
} else if (addedSrc instanceof NewInstanceNode && addedTgt instanceof VarNode) {
final NewInstanceNode edgeSrc = (NewInstanceNode) addedSrc.getReplacement();
final VarNode edgeTgt = (VarNode) addedTgt.getReplacement();
addedSrc.getP2Set().forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (n instanceof ClassConstantNode) {
ClassConstantNode ccn = (ClassConstantNode) n;
Type ccnType = ccn.getClassConstant().toSootType();
// If the referenced class has not been loaded,
// we do this now
SootClass targetClass = ((RefType) ccnType).getSootClass();
if (targetClass.resolvingLevel() == SootClass.DANGLING) {
Scene.v().forceResolve(targetClass.getName(), SootClass.SIGNATURES);
}
// We can only create alloc nodes for types that
// we know
edgeTgt.makeP2Set().add(pag.makeAllocNode(edgeSrc.getValue(), ccnType, ccn.getMethod()));
varNodeWorkList.add(edgeTgt);
}
}
});
if (edgeTgt.makeP2Set().add(addedSrc)) {
if (edgeTgt == src) {
flush = false;
}
}
}
}
}
Node[] simpleTargets = pag.simpleLookup(src);
for (Node element : simpleTargets) {
if (element.makeP2Set().addAll(newP2Set, null)) {
varNodeWorkList.add((VarNode) element);
if (element == src) {
flush = false;
}
ret = true;
}
}
Node[] storeTargets = pag.storeLookup(src);
for (Node element : storeTargets) {
final FieldRefNode fr = (FieldRefNode) element;
final SparkField f = fr.getField();
ret = fr.getBase().getP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, f);
if (nDotF.makeP2Set().addAll(newP2Set, null)) {
returnValue = true;
}
}
}) | ret;
}
final HashSet<Node[]> storesToPropagate = new HashSet<Node[]>();
final HashSet<Node[]> loadsToPropagate = new HashSet<Node[]>();
for (final FieldRefNode fr : src.getAllFieldRefs()) {
final SparkField field = fr.getField();
final Node[] storeSources = pag.storeInvLookup(fr);
if (storeSources.length > 0) {
newP2Set.forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, field);
for (Node element : storeSources) {
Node[] pair = { element, nDotF.getReplacement() };
storesToPropagate.add(pair);
}
}
});
}
final Node[] loadTargets = pag.loadLookup(fr);
if (loadTargets.length > 0) {
newP2Set.forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, field);
if (nDotF != null) {
for (Node element : loadTargets) {
Node[] pair = { nDotF.getReplacement(), element };
loadsToPropagate.add(pair);
}
}
}
});
}
}
if (flush) {
src.getP2Set().flushNew();
}
for (Node[] p : storesToPropagate) {
VarNode storeSource = (VarNode) p[0];
AllocDotField nDotF = (AllocDotField) p[1];
if (nDotF.makeP2Set().addAll(storeSource.getP2Set(), null)) {
ret = true;
}
}
for (Node[] p : loadsToPropagate) {
AllocDotField nDotF = (AllocDotField) p[0];
VarNode loadTarget = (VarNode) p[1];
if (loadTarget.makeP2Set().addAll(nDotF.getP2Set(), null)) {
varNodeWorkList.add(loadTarget);
ret = true;
}
}
return ret;
}
/**
* Propagates new points-to information of node src to all its successors.
*/
protected final void handleFieldRefNode(FieldRefNode src, final HashSet<Object[]> edgesToPropagate) {
final Node[] loadTargets = pag.loadLookup(src);
if (loadTargets.length == 0) {
return;
}
final SparkField field = src.getField();
src.getBase().getP2Set().forall(new P2SetVisitor() {
public final void visit(Node n) {
AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, field);
if (nDotF != null) {
PointsToSetInternal p2Set = nDotF.getP2Set();
if (!p2Set.getNewSet().isEmpty()) {
for (Node element : loadTargets) {
Object[] pair = { p2Set, element };
edgesToPropagate.add(pair);
}
}
}
}
});
}
protected PAG pag;
protected OnFlyCallGraph ofcg;
}
| 11,368
| 32.735905
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/Propagator.java
|
package soot.jimple.spark.solver;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Abstract base class for a propagator that propagates points-to sets along pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public abstract class Propagator {
/** Actually does the propagation. */
public abstract void propagate();
}
| 1,087
| 30.085714
| 102
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/SCCCollapser.java
|
package soot.jimple.spark.solver;
/*-
* #%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.HashSet;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.jimple.spark.internal.TypeManager;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.PointsToSetInternal;
/**
* Collapses VarNodes (green) forming strongly-connected components in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public class SCCCollapser {
private static final Logger logger = LoggerFactory.getLogger(SCCCollapser.class);
/** Actually collapse the SCCs in the PAG. */
public void collapse() {
boolean verbose = pag.getOpts().verbose();
if (verbose) {
logger.debug("" + "Total VarNodes: " + pag.getVarNodeNumberer().size() + ". Collapsing SCCs...");
}
new TopoSorter(pag, ignoreTypes).sort();
TreeSet<VarNode> s = new TreeSet<VarNode>();
for (final VarNode v : pag.getVarNodeNumberer()) {
s.add(v);
}
for (VarNode v : s) {
dfsVisit(v, v);
}
if (verbose) {
logger.debug("" + "" + numCollapsed + " nodes were collapsed.");
}
visited = null;
}
public SCCCollapser(PAG pag, boolean ignoreTypes) {
this.pag = pag;
this.ignoreTypes = ignoreTypes;
this.typeManager = pag.getTypeManager();
}
/* End of public methods. */
/* End of package methods. */
protected int numCollapsed = 0;
protected PAG pag;
protected HashSet<VarNode> visited = new HashSet<VarNode>();
protected boolean ignoreTypes;
protected TypeManager typeManager;
final protected void dfsVisit(VarNode v, VarNode rootOfSCC) {
if (visited.contains(v)) {
return;
}
visited.add(v);
Node[] succs = pag.simpleInvLookup(v);
for (Node element : succs) {
if (ignoreTypes || typeManager.castNeverFails(element.getType(), v.getType())) {
dfsVisit((VarNode) element, rootOfSCC);
}
}
if (v != rootOfSCC) {
if (!ignoreTypes) {
if (typeManager.castNeverFails(v.getType(), rootOfSCC.getType())
&& typeManager.castNeverFails(rootOfSCC.getType(), v.getType())) {
rootOfSCC.mergeWith(v);
numCollapsed++;
}
} else /* ignoreTypes */ {
if (typeManager.castNeverFails(v.getType(), rootOfSCC.getType())) {
rootOfSCC.mergeWith(v);
} else if (typeManager.castNeverFails(rootOfSCC.getType(), v.getType())) {
v.mergeWith(rootOfSCC);
} else {
rootOfSCC.getReplacement().setType(null);
PointsToSetInternal set = rootOfSCC.getP2Set();
if (set != null) {
set.setType(null);
}
rootOfSCC.mergeWith(v);
}
numCollapsed++;
}
}
}
}
| 3,594
| 29.210084
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/spark/solver/TopoSorter.java
|
package soot.jimple.spark.solver;
/*-
* #%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.HashSet;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.VarNode;
/**
* Performs a pseudo-topological sort on the VarNodes in a PAG.
*
* @author Ondrej Lhotak
*/
public class TopoSorter {
/** Actually perform the topological sort on the PAG. */
public void sort() {
for (VarNode v : pag.getVarNodeNumberer()) {
dfsVisit(v);
}
visited = null;
}
public TopoSorter(PAG pag, boolean ignoreTypes) {
this.pag = pag;
this.ignoreTypes = ignoreTypes;
// this.visited = new NumberedSet( pag.getVarNodeNumberer() );
this.visited = new HashSet<VarNode>();
}
/* End of public methods. */
/* End of package methods. */
protected boolean ignoreTypes;
protected PAG pag;
protected int nextFinishNumber = 1;
protected HashSet<VarNode> visited;
protected void dfsVisit(VarNode n) {
if (visited.contains(n)) {
return;
}
visited.add(n);
Node[] succs = pag.simpleLookup(n);
for (Node element : succs) {
if (ignoreTypes || pag.getTypeManager().castNeverFails(n.getType(), element.getType())) {
dfsVisit((VarNode) element);
}
}
n.setFinishingNumber(nextFinishNumber++);
}
}
| 2,077
| 26.706667
| 95
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/AvailExprTagger.java
|
package soot.jimple.toolkits.annotation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.PhaseOptions;
import soot.Scene;
import soot.SideEffectTester;
import soot.Singletons;
import soot.jimple.NaiveSideEffectTester;
import soot.jimple.toolkits.pointer.PASideEffectTester;
import soot.jimple.toolkits.scalar.PessimisticAvailableExpressionsAnalysis;
import soot.jimple.toolkits.scalar.SlowAvailableExpressionsAnalysis;
import soot.options.AETOptions;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
/**
* A body transformer that records avail expression information in tags. - both pessimistic and optimistic options
*/
public class AvailExprTagger extends BodyTransformer {
public AvailExprTagger(Singletons.Global g) {
}
public static AvailExprTagger v() {
return G.v().soot_jimple_toolkits_annotation_AvailExprTagger();
}
protected void internalTransform(Body b, String phaseName, Map opts) {
SideEffectTester sideEffect;
if (Scene.v().hasCallGraph() && !PhaseOptions.getBoolean(opts, "naive-side-effect")) {
sideEffect = new PASideEffectTester();
} else {
sideEffect = new NaiveSideEffectTester();
}
sideEffect.newMethod(b.getMethod());
AETOptions options = new AETOptions(opts);
if (options.kind() == AETOptions.kind_optimistic) {
new SlowAvailableExpressionsAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b));
} else {
new PessimisticAvailableExpressionsAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b), b.getMethod(),
sideEffect);
}
}
}
| 2,430
| 33.239437
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/DominatorsTagger.java
|
package soot.jimple.toolkits.annotation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Singletons;
import soot.jimple.Stmt;
import soot.tagkit.LinkTag;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.MHGDominatorsFinder;
/**
* A body transformer that records avail expression information in tags. - both pessimistic and optimistic options
*/
public class DominatorsTagger extends BodyTransformer {
public DominatorsTagger(Singletons.Global g) {
}
public static DominatorsTagger v() {
return G.v().soot_jimple_toolkits_annotation_DominatorsTagger();
}
protected void internalTransform(Body b, String phaseName, Map opts) {
MHGDominatorsFinder analysis = new MHGDominatorsFinder(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b));
Iterator it = b.getUnits().iterator();
while (it.hasNext()) {
Stmt s = (Stmt) it.next();
List dominators = analysis.getDominators(s);
Iterator dIt = dominators.iterator();
while (dIt.hasNext()) {
Stmt ds = (Stmt) dIt.next();
String info = ds + " dominates " + s;
s.addTag(new LinkTag(info, ds, b.getMethod().getDeclaringClass().getName(), "Dominators"));
}
}
}
}
| 2,129
| 31.769231
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/LineNumberAdder.java
|
package soot.jimple.toolkits.annotation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import soot.G;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.IdentityStmt;
import soot.tagkit.LineNumberTag;
import soot.util.Chain;
public class LineNumberAdder extends SceneTransformer {
public LineNumberAdder(Singletons.Global g) {
}
public static LineNumberAdder v() {
return G.v().soot_jimple_toolkits_annotation_LineNumberAdder();
}
@Override
public void internalTransform(String phaseName, Map<String, String> opts) {
// using a snapshot iterator because Application classes may change if LambdaMetaFactory translates
// invokedynamic to new classes; no need to visit new classes
for (Iterator<SootClass> it = Scene.v().getApplicationClasses().snapshotIterator(); it.hasNext();) {
SootClass sc = it.next();
// make map of first line to each method
HashMap<Integer, SootMethod> lineToMeth = new HashMap<Integer, SootMethod>();
for (SootMethod meth : sc.getMethods()) {
if (!meth.isConcrete()) {
continue;
}
Chain<Unit> units = meth.retrieveActiveBody().getUnits();
Unit s = units.getFirst();
while (s instanceof IdentityStmt) {
s = units.getSuccOf(s);
}
LineNumberTag tag = (LineNumberTag) s.getTag(LineNumberTag.NAME);
if (tag != null) {
lineToMeth.put(tag.getLineNumber(), meth);
}
}
for (SootMethod meth : sc.getMethods()) {
if (!meth.isConcrete()) {
continue;
}
Chain<Unit> units = meth.retrieveActiveBody().getUnits();
Unit s = units.getFirst();
while (s instanceof IdentityStmt) {
s = units.getSuccOf(s);
}
LineNumberTag tag = (LineNumberTag) s.getTag(LineNumberTag.NAME);
if (tag != null) {
int line_num = tag.getLineNumber() - 1;
// already taken
if (lineToMeth.containsKey(line_num)) {
meth.addTag(new LineNumberTag(line_num + 1));
} else {
// still available - so use it for this meth
meth.addTag(new LineNumberTag(line_num));
}
}
}
}
}
}
| 3,144
| 32.105263
| 104
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/Array2ndDimensionSymbol.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.G;
public class Array2ndDimensionSymbol {
private Object var;
public static Array2ndDimensionSymbol v(Object which) {
Array2ndDimensionSymbol tdal = G.v().Array2ndDimensionSymbol_pool.get(which);
if (tdal == null) {
tdal = new Array2ndDimensionSymbol(which);
G.v().Array2ndDimensionSymbol_pool.put(which, tdal);
}
return tdal;
}
private Array2ndDimensionSymbol(Object which) {
this.var = which;
}
public Object getVar() {
return this.var;
}
public int hashCode() {
return var.hashCode() + 1;
}
public boolean equals(Object other) {
if (other instanceof Array2ndDimensionSymbol) {
Array2ndDimensionSymbol another = (Array2ndDimensionSymbol) other;
return (this.var == another.var);
} else {
return false;
}
}
public String toString() {
return var + "[";
}
}
| 1,725
| 25.151515
| 81
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/ArrayBoundsChecker.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Local;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.Stmt;
import soot.jimple.toolkits.annotation.tags.ArrayCheckTag;
import soot.options.ABCOptions;
import soot.options.Options;
import soot.tagkit.ColorTag;
import soot.tagkit.KeyTag;
import soot.tagkit.Tag;
import soot.util.Chain;
public class ArrayBoundsChecker extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(ArrayBoundsChecker.class);
public ArrayBoundsChecker(Singletons.Global g) {
}
public static ArrayBoundsChecker v() {
return G.v().soot_jimple_toolkits_annotation_arraycheck_ArrayBoundsChecker();
}
protected boolean takeClassField = false;
protected boolean takeFieldRef = false;
protected boolean takeArrayRef = false;
protected boolean takeCSE = false;
protected boolean takeRectArray = false;
protected boolean addColorTags = false;
protected void internalTransform(Body body, String phaseName, Map opts) {
ABCOptions options = new ABCOptions(opts);
if (options.with_all()) {
takeClassField = true;
takeFieldRef = true;
takeArrayRef = true;
takeCSE = true;
takeRectArray = true;
} else {
takeClassField = options.with_classfield();
takeFieldRef = options.with_fieldref();
takeArrayRef = options.with_arrayref();
takeCSE = options.with_cse();
takeRectArray = options.with_rectarray();
}
addColorTags = options.add_color_tags();
{
SootMethod m = body.getMethod();
Date start = new Date();
if (Options.v().verbose()) {
logger.debug("[abc] Analyzing array bounds information for " + m.getName());
logger.debug("[abc] Started on " + start);
}
ArrayBoundsCheckerAnalysis analysis = null;
if (hasArrayLocals(body)) {
analysis = new ArrayBoundsCheckerAnalysis(body, takeClassField, takeFieldRef, takeArrayRef, takeCSE, takeRectArray);
}
SootClass counterClass = null;
SootMethod increase = null;
if (options.profiling()) {
counterClass = Scene.v().loadClassAndSupport("MultiCounter");
increase = counterClass.getMethod("void increase(int)");
}
Chain units = body.getUnits();
IntContainer zero = new IntContainer(0);
Iterator unitIt = units.snapshotIterator();
while (unitIt.hasNext()) {
Stmt stmt = (Stmt) unitIt.next();
if (stmt.containsArrayRef()) {
ArrayRef aref = stmt.getArrayRef();
{
WeightedDirectedSparseGraph vgraph = (WeightedDirectedSparseGraph) analysis.getFlowBefore(stmt);
int res = interpretGraph(vgraph, aref, stmt, zero);
boolean lowercheck = true;
boolean uppercheck = true;
if (res == 0) {
lowercheck = true;
uppercheck = true;
} else if (res == 1) {
lowercheck = true;
uppercheck = false;
} else if (res == 2) {
lowercheck = false;
uppercheck = true;
} else if (res == 3) {
lowercheck = false;
uppercheck = false;
}
if (addColorTags) {
if (res == 0) {
aref.getIndexBox().addTag(new ColorTag(255, 0, 0, false, ArrayCheckTag.NAME));
} else if (res == 1) {
aref.getIndexBox().addTag(new ColorTag(255, 248, 35, false, ArrayCheckTag.NAME));
} else if (res == 2) {
aref.getIndexBox().addTag(new ColorTag(255, 163, 0, false, ArrayCheckTag.NAME));
} else if (res == 3) {
aref.getIndexBox().addTag(new ColorTag(45, 255, 84, false, ArrayCheckTag.NAME));
}
SootClass bodyClass = body.getMethod().getDeclaringClass();
Iterator keysIt = bodyClass.getTags().iterator();
boolean keysAdded = false;
while (keysIt.hasNext()) {
Object next = keysIt.next();
if (next instanceof KeyTag) {
if (((KeyTag) next).analysisType().equals(ArrayCheckTag.NAME)) {
keysAdded = true;
}
}
}
if (!keysAdded) {
bodyClass.addTag(new KeyTag(255, 0, 0, "ArrayBounds: Unsafe Lower and Unsafe Upper", ArrayCheckTag.NAME));
bodyClass.addTag(new KeyTag(255, 248, 35, "ArrayBounds: Unsafe Lower and Safe Upper", ArrayCheckTag.NAME));
bodyClass.addTag(new KeyTag(255, 163, 0, "ArrayBounds: Safe Lower and Unsafe Upper", ArrayCheckTag.NAME));
bodyClass.addTag(new KeyTag(45, 255, 84, "ArrayBounds: Safe Lower and Safe Upper", ArrayCheckTag.NAME));
}
}
/*
* boolean lowercheck = true; boolean uppercheck = true;
*
* { if (Options.v().debug()) { if (!vgraph.makeShortestPathGraph()) { logger.debug(""+stmt+" :");
* logger.debug(""+vgraph); } }
*
* Value base = aref.getBase(); Value index = aref.getIndex();
*
* if (index instanceof IntConstant) { int indexv = ((IntConstant)index).value;
*
* if (vgraph.hasEdge(base, zero)) { int alength = vgraph.edgeWeight(base, zero);
*
* if (-alength > indexv) uppercheck = false; }
*
* if (indexv >= 0) lowercheck = false; } else { if (vgraph.hasEdge(base, index)) { int upperdistance =
* vgraph.edgeWeight(base, index); if (upperdistance < 0) uppercheck = false; }
*
* if (vgraph.hasEdge(index, zero)) { int lowerdistance = vgraph.edgeWeight(index, zero);
*
* if (lowerdistance <= 0) lowercheck = false; } } }
*/
if (options.profiling()) {
int lowercounter = 0;
if (!lowercheck) {
lowercounter = 1;
}
units.insertBefore(
Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(increase.makeRef(), IntConstant.v(lowercounter))),
stmt);
int uppercounter = 2;
if (!uppercheck) {
uppercounter = 3;
}
units.insertBefore(
Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(increase.makeRef(), IntConstant.v(uppercounter))),
stmt);
/*
* if (!lowercheck && !uppercheck) { units.insertBefore(Jimple.v().newInvokeStmt(
* Jimple.v().newStaticInvokeExpr(increase, IntConstant.v(4))), stmt);
*
* NullCheckTag nullTag = (NullCheckTag)stmt.getTag(NullCheckTag.NAME);
*
* if (nullTag != null && !nullTag.needCheck()) units.insertBefore(Jimple.v().newInvokeStmt(
* Jimple.v().newStaticInvokeExpr(increase, IntConstant.v(7))), stmt); }
*/
} else {
Tag checkTag = new ArrayCheckTag(lowercheck, uppercheck);
stmt.addTag(checkTag);
}
}
}
}
if (addColorTags && takeRectArray) {
RectangularArrayFinder raf = RectangularArrayFinder.v();
for (Iterator vbIt = body.getUseAndDefBoxes().iterator(); vbIt.hasNext();) {
final ValueBox vb = (ValueBox) vbIt.next();
Value v = vb.getValue();
if (!(v instanceof Local)) {
continue;
}
Type t = v.getType();
if (!(t instanceof ArrayType)) {
continue;
}
ArrayType at = (ArrayType) t;
if (at.numDimensions <= 1) {
continue;
}
vb.addTag(new ColorTag(raf.isRectangular(new MethodLocal(m, (Local) v)) ? ColorTag.GREEN : ColorTag.RED));
}
}
Date finish = new Date();
if (Options.v().verbose()) {
long runtime = finish.getTime() - start.getTime();
logger.debug(
"[abc] ended on " + finish + ". It took " + (runtime / 60000) + " min. " + ((runtime % 60000) / 1000) + " sec.");
}
}
}
private boolean hasArrayLocals(Body body) {
Iterator localIt = body.getLocals().iterator();
while (localIt.hasNext()) {
Local local = (Local) localIt.next();
if (local.getType() instanceof ArrayType) {
return true;
}
}
return false;
}
protected int interpretGraph(WeightedDirectedSparseGraph vgraph, ArrayRef aref, Stmt stmt, IntContainer zero) {
boolean lowercheck = true;
boolean uppercheck = true;
{
if (Options.v().debug()) {
if (!vgraph.makeShortestPathGraph()) {
logger.debug("" + stmt + " :");
logger.debug("" + vgraph);
}
}
Value base = aref.getBase();
Value index = aref.getIndex();
if (index instanceof IntConstant) {
int indexv = ((IntConstant) index).value;
if (vgraph.hasEdge(base, zero)) {
int alength = vgraph.edgeWeight(base, zero);
if (-alength > indexv) {
uppercheck = false;
}
}
if (indexv >= 0) {
lowercheck = false;
}
} else {
if (vgraph.hasEdge(base, index)) {
int upperdistance = vgraph.edgeWeight(base, index);
if (upperdistance < 0) {
uppercheck = false;
}
}
if (vgraph.hasEdge(index, zero)) {
int lowerdistance = vgraph.edgeWeight(index, zero);
if (lowerdistance <= 0) {
lowercheck = false;
}
}
}
}
if (lowercheck && uppercheck) {
return 0;
} else if (lowercheck && !uppercheck) {
return 1;
} else if (!lowercheck && uppercheck) {
return 2;
} else {
return 3;
}
}
}
| 11,187
| 32.198813
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/ArrayBoundsCheckerAnalysis.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.Hierarchy;
import soot.Local;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AddExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.EqExpr;
import soot.jimple.FieldRef;
import soot.jimple.GeExpr;
import soot.jimple.GtExpr;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Stmt;
import soot.jimple.SubExpr;
import soot.options.Options;
import soot.toolkits.graph.ArrayRefBlockGraph;
import soot.toolkits.graph.Block;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.SlowPseudoTopologicalOrderer;
class ArrayBoundsCheckerAnalysis {
private static final Logger logger = LoggerFactory.getLogger(ArrayBoundsCheckerAnalysis.class);
protected Map<Block, WeightedDirectedSparseGraph> blockToBeforeFlow;
protected Map<Unit, WeightedDirectedSparseGraph> unitToBeforeFlow;
private final Map<FlowGraphEdge, WeightedDirectedSparseGraph> edgeMap;
private final Set<FlowGraphEdge> edgeSet;
private HashMap<Block, Integer> stableRoundOfUnits;
private ArrayRefBlockGraph graph;
private final IntContainer zero = new IntContainer(0);
private boolean fieldin = false;
private HashMap<Object, HashSet<Value>> localToFieldRef;
private HashMap<Object, HashSet<Value>> fieldToFieldRef;
private final int strictness = 2;
private boolean arrayin = false;
private boolean csin = false;
private HashMap<Value, HashSet<Value>> localToExpr;
private boolean classfieldin = false;
private ClassFieldAnalysis cfield;
private boolean rectarray = false;
private HashSet<Local> rectarrayset;
private HashSet<Local> multiarraylocals;
private final ArrayIndexLivenessAnalysis ailanalysis;
/* A little bit different from ForwardFlowAnalysis */
public ArrayBoundsCheckerAnalysis(Body body, boolean takeClassField, boolean takeFieldRef, boolean takeArrayRef,
boolean takeCSE, boolean takeRectArray) {
classfieldin = takeClassField;
fieldin = takeFieldRef;
arrayin = takeArrayRef;
csin = takeCSE;
rectarray = takeRectArray;
SootMethod thismethod = body.getMethod();
if (Options.v().debug()) {
logger.debug("ArrayBoundsCheckerAnalysis started on " + thismethod.getName());
}
ailanalysis = new ArrayIndexLivenessAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body), fieldin,
arrayin, csin, rectarray);
if (fieldin) {
this.localToFieldRef = ailanalysis.getLocalToFieldRef();
this.fieldToFieldRef = ailanalysis.getFieldToFieldRef();
}
if (arrayin) {
if (rectarray) {
this.multiarraylocals = ailanalysis.getMultiArrayLocals();
this.rectarrayset = new HashSet<Local>();
RectangularArrayFinder pgbuilder = RectangularArrayFinder.v();
Iterator<Local> localIt = multiarraylocals.iterator();
while (localIt.hasNext()) {
Local local = localIt.next();
MethodLocal mlocal = new MethodLocal(thismethod, local);
if (pgbuilder.isRectangular(mlocal)) {
this.rectarrayset.add(local);
}
}
}
}
if (csin) {
this.localToExpr = ailanalysis.getLocalToExpr();
}
if (classfieldin) {
this.cfield = ClassFieldAnalysis.v();
}
this.graph = new ArrayRefBlockGraph(body);
blockToBeforeFlow = new HashMap<Block, WeightedDirectedSparseGraph>(graph.size() * 2 + 1, 0.7f);
edgeMap = new HashMap<FlowGraphEdge, WeightedDirectedSparseGraph>(graph.size() * 2 + 1, 0.7f);
edgeSet = buildEdgeSet(graph);
doAnalysis();
convertToUnitEntry();
if (Options.v().debug()) {
logger.debug("ArrayBoundsCheckerAnalysis finished.");
}
}
private void convertToUnitEntry() {
unitToBeforeFlow = new HashMap<Unit, WeightedDirectedSparseGraph>();
Iterator<Block> blockIt = blockToBeforeFlow.keySet().iterator();
while (blockIt.hasNext()) {
Block block = blockIt.next();
Unit first = block.getHead();
unitToBeforeFlow.put(first, blockToBeforeFlow.get(block));
}
}
/**
* buildEdgeSet creates a set of edges from directed graph.
*/
public Set<FlowGraphEdge> buildEdgeSet(DirectedGraph<Block> dg) {
HashSet<FlowGraphEdge> edges = new HashSet<FlowGraphEdge>();
Iterator<Block> blockIt = dg.iterator();
while (blockIt.hasNext()) {
Block s = blockIt.next();
List<Block> preds = graph.getPredsOf(s);
List<Block> succs = graph.getSuccsOf(s);
/* Head units has in edge from itself to itself. */
if (preds.size() == 0) {
edges.add(new FlowGraphEdge(s, s));
}
/* End units has out edge from itself to itself. */
if (succs.size() == 0) {
edges.add(new FlowGraphEdge(s, s));
} else {
Iterator succIt = succs.iterator();
while (succIt.hasNext()) {
edges.add(new FlowGraphEdge(s, succIt.next()));
}
}
}
return edges;
}
public Object getFlowBefore(Object s) {
return unitToBeforeFlow.get(s);
}
/* merge all preds' out set */
private void mergebunch(Object ins[], Object s, Object prevOut, Object out) {
WeightedDirectedSparseGraph prevgraph = (WeightedDirectedSparseGraph) prevOut,
outgraph = (WeightedDirectedSparseGraph) out;
WeightedDirectedSparseGraph[] ingraphs = new WeightedDirectedSparseGraph[ins.length];
for (int i = 0; i < ins.length; i++) {
ingraphs[i] = (WeightedDirectedSparseGraph) ins[i];
}
{
outgraph.addBoundedAll(ingraphs[0]);
for (int i = 1; i < ingraphs.length; i++) {
outgraph.unionSelf(ingraphs[i]);
outgraph.makeShortestPathGraph();
}
// if (flowStable)
/*
* Integer round = (Integer)stableRoundOfUnits.get(s);
*
* if (round.intValue() < 2) { stableRoundOfUnits.put(s, new Integer(round.intValue()+1)); } else { // To make output
* stable. compare with previous output value. outgraph.wideEdges((WeightedDirectedSparseGraph)prevOut);
* outgraph.makeShortestPathGraph(); }
*/
outgraph.widenEdges(prevgraph);
// outgraph.makeShortestPathGraph();
/*
* for (int i=0; i<ins.length; i++) { logger.debug("in " + i); logger.debug(""+ins[i]); }
*
* logger.debug("out "); logger.debug(""+out);
*/
}
}
/*
* override ForwardFlowAnalysis
*/
private void doAnalysis() {
Date start = new Date();
if (Options.v().debug()) {
logger.debug("Building PseudoTopological order list on " + start);
}
LinkedList allUnits = (LinkedList) SlowPseudoTopologicalOrderer.v().newList(this.graph, false);
BoundedPriorityList changedUnits = new BoundedPriorityList(allUnits);
// LinkedList changedUnits = new LinkedList(allUnits);
Date finish = new Date();
if (Options.v().debug()) {
long runtime = finish.getTime() - start.getTime();
long mins = runtime / 60000;
long secs = (runtime % 60000) / 1000;
logger.debug("Building PseudoTopological order finished. " + "It took " + mins + " mins and " + secs + " secs.");
}
start = new Date();
HashSet changedUnitsSet = new HashSet(allUnits);
List<Object> changedSuccs;
/* An temporary object. */
FlowGraphEdge tmpEdge = new FlowGraphEdge();
/*
* If any output flow set has unknow value, it will be put in this set
*/
HashSet<Block> unvisitedNodes = new HashSet<Block>(graph.size() * 2 + 1, 0.7f);
/* adjust livelocals set */
{
Iterator blockIt = graph.iterator();
while (blockIt.hasNext()) {
Block block = (Block) blockIt.next();
HashSet<IntContainer> livelocals = (HashSet<IntContainer>) ailanalysis.getFlowBefore(block.getHead());
livelocals.add(zero);
}
}
/* Set initial values and nodes to visit. */
{
stableRoundOfUnits = new HashMap<Block, Integer>();
Iterator it = graph.iterator();
while (it.hasNext()) {
Block block = (Block) it.next();
unvisitedNodes.add(block);
stableRoundOfUnits.put(block, new Integer(0));
/* only take out the necessary node set. */
HashSet livelocals = (HashSet) ailanalysis.getFlowBefore(block.getHead());
blockToBeforeFlow.put(block, new WeightedDirectedSparseGraph(livelocals, false));
}
Iterator<FlowGraphEdge> edgeIt = edgeSet.iterator();
while (edgeIt.hasNext()) {
FlowGraphEdge edge = edgeIt.next();
Block target = (Block) edge.to;
HashSet livelocals = (HashSet) ailanalysis.getFlowBefore(target.getHead());
edgeMap.put(edge, new WeightedDirectedSparseGraph(livelocals, false));
}
}
/* perform customized initialization. */
{
List headlist = graph.getHeads();
Iterator headIt = headlist.iterator();
while (headIt.hasNext()) {
Object head = headIt.next();
FlowGraphEdge edge = new FlowGraphEdge(head, head);
WeightedDirectedSparseGraph initgraph = edgeMap.get(edge);
initgraph.setTop();
}
}
/*
* Perform fixed point flow analysis.
*/
{
WeightedDirectedSparseGraph beforeFlow = new WeightedDirectedSparseGraph(null, false);
// DebugMsg.counter1 += allUnits.size();
while (!changedUnits.isEmpty()) {
Block s = (Block) changedUnits.removeFirst();
changedUnitsSet.remove(s);
// DebugMsg.counter2++;
/* previousAfterFlow, old-out, it is null initially */
WeightedDirectedSparseGraph previousBeforeFlow = blockToBeforeFlow.get(s);
beforeFlow.setVertexes(previousBeforeFlow.getVertexes());
// Compute and store beforeFlow
{
List preds = graph.getPredsOf(s);
/* the init node */
if (preds.size() == 0) {
tmpEdge.changeEndUnits(s, s);
copy(edgeMap.get(tmpEdge), beforeFlow);
} else if (preds.size() == 1) {
tmpEdge.changeEndUnits(preds.get(0), s);
copy(edgeMap.get(tmpEdge), beforeFlow);
// widenGraphs(beforeFlow, previousBeforeFlow);
} else {
/* has 2 or more preds, Updated by Feng. */
Object predFlows[] = new Object[preds.size()];
boolean allUnvisited = true;
Iterator predIt = preds.iterator();
int index = 0;
int lastVisited = 0;
while (predIt.hasNext()) {
Object pred = predIt.next();
tmpEdge.changeEndUnits(pred, s);
if (!unvisitedNodes.contains(pred)) {
allUnvisited = false;
lastVisited = index;
}
predFlows[index++] = edgeMap.get(tmpEdge);
}
// put the visited node as the first one
if (allUnvisited) {
logger.debug("Warning : see all unvisited node");
} else {
Object tmp = predFlows[0];
predFlows[0] = predFlows[lastVisited];
predFlows[lastVisited] = tmp;
}
mergebunch(predFlows, s, previousBeforeFlow, beforeFlow);
}
copy(beforeFlow, previousBeforeFlow);
}
/*
* Compute afterFlow and store it. Now we do not have afterFlow, we only have the out edges. Different out edges may
* have different flow set. It returns back a list of succ units that edge has been changed.
*/
{
changedSuccs = flowThrough(beforeFlow, s);
}
{
for (int i = 0; i < changedSuccs.size(); i++) {
Object succ = changedSuccs.get(i);
if (!changedUnitsSet.contains(succ)) {
changedUnits.add(succ);
changedUnitsSet.add(succ);
}
}
}
/* Decide to remove or add unit from/to unvisitedNodes set */
{
unvisitedNodes.remove(s);
}
}
}
finish = new Date();
if (Options.v().debug()) {
long runtime = finish.getTime() - start.getTime();
long mins = runtime / 60000;
long secs = (runtime / 60000) / 1000;
logger.debug("Doing analysis finished." + " It took " + mins + " mins and " + secs + "secs.");
}
}
/*
* Flow go through a node, the output will be put into edgeMap, and also the changed succ will be in a list to return back.
*/
private List<Object> flowThrough(Object inValue, Object unit) {
ArrayList<Object> changedSuccs = new ArrayList<Object>();
WeightedDirectedSparseGraph ingraph = (WeightedDirectedSparseGraph) inValue;
Block block = (Block) unit;
List succs = block.getSuccs();
// leave out the last element.
Unit s = block.getHead();
Unit nexts = block.getSuccOf(s);
while (nexts != null) {
/* deal with array references */
assertArrayRef(ingraph, s);
/* deal with normal expressions. */
assertNormalExpr(ingraph, s);
s = nexts;
nexts = block.getSuccOf(nexts);
}
// at the end of block, it should update the out edges.
if (s instanceof IfStmt) {
if (!assertBranchStmt(ingraph, s, block, succs, changedSuccs)) {
updateOutEdges(ingraph, block, succs, changedSuccs);
}
} else {
assertArrayRef(ingraph, s);
assertNormalExpr(ingraph, s);
updateOutEdges(ingraph, block, succs, changedSuccs);
}
return changedSuccs;
}
private void assertArrayRef(Object in, Unit unit) {
if (!(unit instanceof AssignStmt)) {
return;
}
Stmt s = (Stmt) unit;
WeightedDirectedSparseGraph ingraph = (WeightedDirectedSparseGraph) in;
/*
* ArrayRef op = null;
*
* Value leftOp = ((AssignStmt)s).getLeftOp(); Value rightOp = ((AssignStmt)s).getRightOp();
*
* if (leftOp instanceof ArrayRef) op = (ArrayRef)leftOp;
*
* if (rightOp instanceof ArrayRef) op = (ArrayRef)rightOp;
*
* if (op == null) return;
*/
if (!s.containsArrayRef()) {
return;
}
ArrayRef op = s.getArrayRef();
Value base = (op).getBase();
Value index = (op).getIndex();
HashSet livelocals = (HashSet) ailanalysis.getFlowAfter(s);
if (!livelocals.contains(base) && !livelocals.contains(index)) {
return;
}
if (index instanceof IntConstant) {
int weight = ((IntConstant) index).value;
weight = -1 - weight;
ingraph.addEdge(base, zero, weight);
} else {
// add two edges.
// index <= a.length -1;
ingraph.addEdge(base, index, -1);
// index >= 0
ingraph.addEdge(index, zero, 0);
}
}
private void assertNormalExpr(Object in, Unit s) {
WeightedDirectedSparseGraph ingraph = (WeightedDirectedSparseGraph) in;
/* If it is a contains invoke expr, the parameter should be analyzed. */
if (fieldin) {
Stmt stmt = (Stmt) s;
if (stmt.containsInvokeExpr()) {
HashSet tokills = new HashSet();
Value expr = stmt.getInvokeExpr();
List parameters = ((InvokeExpr) expr).getArgs();
/* kill only the locals in hierarchy. */
if (strictness == 0) {
Hierarchy hierarchy = Scene.v().getActiveHierarchy();
for (int i = 0; i < parameters.size(); i++) {
Value para = (Value) parameters.get(i);
Type type = para.getType();
if (type instanceof RefType) {
SootClass pclass = ((RefType) type).getSootClass();
/* then we are looking for the possible types. */
Iterator<Object> keyIt = localToFieldRef.keySet().iterator();
while (keyIt.hasNext()) {
Value local = (Value) keyIt.next();
Type ltype = local.getType();
SootClass lclass = ((RefType) ltype).getSootClass();
if (hierarchy.isClassSuperclassOfIncluding(pclass, lclass)
|| hierarchy.isClassSuperclassOfIncluding(lclass, pclass)) {
HashSet toadd = localToFieldRef.get(local);
tokills.addAll(toadd);
}
}
}
}
if (expr instanceof InstanceInvokeExpr) {
Value base = ((InstanceInvokeExpr) expr).getBase();
Type type = base.getType();
if (type instanceof RefType) {
SootClass pclass = ((RefType) type).getSootClass();
/* then we are looking for the possible types. */
Iterator<Object> keyIt = localToFieldRef.keySet().iterator();
while (keyIt.hasNext()) {
Value local = (Value) keyIt.next();
Type ltype = local.getType();
SootClass lclass = ((RefType) ltype).getSootClass();
if (hierarchy.isClassSuperclassOfIncluding(pclass, lclass)
|| hierarchy.isClassSuperclassOfIncluding(lclass, pclass)) {
HashSet toadd = localToFieldRef.get(local);
tokills.addAll(toadd);
}
}
}
}
} else if (strictness == 1) {
/* kill all instance field reference. */
boolean killall = false;
if (expr instanceof InstanceInvokeExpr) {
killall = true;
} else {
for (int i = 0; i < parameters.size(); i++) {
Value para = (Value) parameters.get(i);
if (para.getType() instanceof RefType) {
killall = true;
break;
}
}
}
if (killall) {
Iterator<Object> keyIt = localToFieldRef.keySet().iterator();
while (keyIt.hasNext()) {
HashSet toadd = localToFieldRef.get(keyIt.next());
tokills.addAll(toadd);
}
}
} else if (strictness == 2) {
// tokills.addAll(allFieldRefs);
HashSet vertexes = ingraph.getVertexes();
Iterator nodeIt = vertexes.iterator();
while (nodeIt.hasNext()) {
Object node = nodeIt.next();
if (node instanceof FieldRef) {
ingraph.killNode(node);
}
}
}
/*
* Iterator killIt = tokills.iterator(); while (killIt.hasNext()) ingraph.killNode(killIt.next());
*/
}
}
if (arrayin) {
Stmt stmt = (Stmt) s;
if (stmt.containsInvokeExpr()) {
if (strictness == 2) {
/*
* Iterator killIt = allArrayRefs.iterator(); while (killIt.hasNext()) { ingraph.killNode(killIt.next()); }
*/
HashSet vertexes = ingraph.getVertexes();
Iterator nodeIt = vertexes.iterator();
while (nodeIt.hasNext()) {
Object node = nodeIt.next();
if (node instanceof ArrayRef) {
ingraph.killNode(node);
}
/*
* if (rectarray) if (node instanceof Array2ndDimensionSymbol) ingraph.killNode(node);
*/
}
}
}
}
if (!(s instanceof AssignStmt)) {
return;
}
Value leftOp = ((AssignStmt) s).getLeftOp();
Value rightOp = ((AssignStmt) s).getRightOp();
HashSet livelocals = (HashSet) ailanalysis.getFlowAfter(s);
if (fieldin) {
if (leftOp instanceof Local) {
HashSet fieldrefs = localToFieldRef.get(leftOp);
if (fieldrefs != null) {
Iterator refsIt = fieldrefs.iterator();
while (refsIt.hasNext()) {
Object ref = refsIt.next();
if (livelocals.contains(ref)) {
ingraph.killNode(ref);
}
}
}
} else if (leftOp instanceof InstanceFieldRef) {
SootField field = ((InstanceFieldRef) leftOp).getField();
HashSet fieldrefs = fieldToFieldRef.get(field);
if (fieldrefs != null) {
Iterator refsIt = fieldrefs.iterator();
while (refsIt.hasNext()) {
Object ref = refsIt.next();
if (livelocals.contains(ref)) {
ingraph.killNode(ref);
}
}
}
}
}
if (arrayin) {
/*
* a = ..; kill all references of a; i = ..; kill all references with index i;
*/
if (leftOp instanceof Local) {
/*
* HashSet arrayrefs = (HashSet)localToArrayRef.get(leftOp);
*
* if (arrayrefs != null) { Iterator refsIt = arrayrefs.iterator(); while (refsIt.hasNext()) { Object ref =
* refsIt.next(); ingraph.killNode(ref); } }
*/
HashSet vertexes = ingraph.getVertexes();
Iterator nodeIt = vertexes.iterator();
while (nodeIt.hasNext()) {
Object node = nodeIt.next();
if (node instanceof ArrayRef) {
Value base = ((ArrayRef) node).getBase();
Value index = ((ArrayRef) node).getIndex();
if (base.equals(leftOp) || index.equals(leftOp)) {
ingraph.killNode(node);
}
}
if (rectarray) {
if (node instanceof Array2ndDimensionSymbol) {
Object base = ((Array2ndDimensionSymbol) node).getVar();
if (base.equals(leftOp)) {
ingraph.killNode(node);
}
}
}
}
} else if (leftOp instanceof ArrayRef) {
/* kill all array references */
/*
* Iterator allrefsIt = allArrayRefs.iterator(); while (allrefsIt.hasNext()) { Object ref = allrefsIt.next();
* ingraph.killNode(ref); }
*/
HashSet vertexes = ingraph.getVertexes();
{
Iterator nodeIt = vertexes.iterator();
while (nodeIt.hasNext()) {
Object node = nodeIt.next();
if (node instanceof ArrayRef) {
ingraph.killNode(node);
}
}
}
/* only when multiarray was given a new value to its sub dimension, we kill all second dimensions of arrays */
/*
* if (rectarray) { Value base = ((ArrayRef)leftOp).getBase();
*
* if (multiarraylocals.contains(base)) { Iterator nodeIt = vertexes.iterator(); while (nodeIt.hasNext()) { Object
* node = nodeIt.next(); if (node instanceof Array2ndDimensionSymbol) ingraph.killNode(node); } } }
*/
}
}
if (!livelocals.contains(leftOp) && !livelocals.contains(rightOp)) {
return;
}
// i = i;
if (rightOp.equals(leftOp)) {
return;
}
if (csin) {
HashSet exprs = localToExpr.get(leftOp);
if (exprs != null) {
Iterator exprIt = exprs.iterator();
while (exprIt.hasNext()) {
ingraph.killNode(exprIt.next());
}
}
}
// i = i + c; is special
if (rightOp instanceof AddExpr) {
Value op1 = ((AddExpr) rightOp).getOp1();
Value op2 = ((AddExpr) rightOp).getOp2();
if (op1 == leftOp && op2 instanceof IntConstant) {
int inc_w = ((IntConstant) op2).value;
ingraph.updateWeight(leftOp, inc_w);
return;
} else if (op2 == leftOp && op1 instanceof IntConstant) {
int inc_w = ((IntConstant) op1).value;
ingraph.updateWeight(leftOp, inc_w);
return;
}
}
// i = i - c; is also special
if (rightOp instanceof SubExpr) {
Value op1 = ((SubExpr) rightOp).getOp1();
Value op2 = ((SubExpr) rightOp).getOp2();
if ((op1 == leftOp) && (op2 instanceof IntConstant)) {
int inc_w = -((IntConstant) op2).value;
ingraph.updateWeight(leftOp, inc_w);
return;
}
}
// i = j; i = j + c; i = c + j; need two operations, kill node and add new relationship.
// kill left hand side,
ingraph.killNode(leftOp);
// add new relationship.
// i = c;
if (rightOp instanceof IntConstant) {
int inc_w = ((IntConstant) rightOp).value;
ingraph.addMutualEdges(zero, leftOp, inc_w);
return;
}
// i = j;
if (rightOp instanceof Local) {
ingraph.addMutualEdges(rightOp, leftOp, 0);
return;
}
if (rightOp instanceof FieldRef) {
if (fieldin) {
ingraph.addMutualEdges(rightOp, leftOp, 0);
}
if (classfieldin) {
SootField field = ((FieldRef) rightOp).getField();
IntValueContainer flength = (IntValueContainer) cfield.getFieldInfo(field);
if (flength != null) {
if (flength.isInteger()) {
ingraph.addMutualEdges(zero, leftOp, flength.getValue());
}
}
}
return;
}
/*
* if (rectarray) { Type leftType = leftOp.getType();
*
* if ((leftType instanceof ArrayType) && (rightOp instanceof ArrayRef)) { Local base =
* (Local)((ArrayRef)rightOp).getBase();
*
* SymbolArrayLength sv = (SymbolArrayLength)lra_analysis.getSymbolLengthAt(base, s); if (sv != null) {
* ingraph.addMutualEdges(leftOp, sv.next(), 0); } } }
*/
if (arrayin) {
if (rightOp instanceof ArrayRef) {
ingraph.addMutualEdges(rightOp, leftOp, 0);
if (rectarray) {
Value base = ((ArrayRef) rightOp).getBase();
if (rectarrayset.contains(base)) {
ingraph.addMutualEdges(leftOp, Array2ndDimensionSymbol.v(base), 0);
}
}
return;
}
}
if (csin) {
Value rhs = rightOp;
if (rhs instanceof BinopExpr) {
Value op1 = ((BinopExpr) rhs).getOp1();
Value op2 = ((BinopExpr) rhs).getOp2();
if (rhs instanceof AddExpr) {
if ((op1 instanceof Local) && (op2 instanceof Local)) {
ingraph.addMutualEdges(rhs, leftOp, 0);
return;
}
} else if (rhs instanceof MulExpr) {
if ((op1 instanceof Local) || (op2 instanceof Local)) {
ingraph.addMutualEdges(rhs, leftOp, 0);
return;
}
} else if (rhs instanceof SubExpr) {
if (op2 instanceof Local) {
ingraph.addMutualEdges(rhs, leftOp, 0);
return;
}
}
}
}
// i = j + c; or i = c + j;
if (rightOp instanceof AddExpr) {
Value op1 = ((AddExpr) rightOp).getOp1();
Value op2 = ((AddExpr) rightOp).getOp2();
if ((op1 instanceof Local) && (op2 instanceof IntConstant)) {
int inc_w = ((IntConstant) op2).value;
ingraph.addMutualEdges(op1, leftOp, inc_w);
return;
}
if ((op2 instanceof Local) && (op1 instanceof IntConstant)) {
int inc_w = ((IntConstant) op1).value;
ingraph.addMutualEdges(op2, leftOp, inc_w);
return;
}
}
// only i = j - c was considered.
if (rightOp instanceof SubExpr) {
Value op1 = ((SubExpr) rightOp).getOp1();
Value op2 = ((SubExpr) rightOp).getOp2();
if ((op1 instanceof Local) && (op2 instanceof IntConstant)) {
int inc_w = -((IntConstant) op2).value;
ingraph.addMutualEdges(op1, leftOp, inc_w);
return;
}
}
// new experessions can also generate relationship
// a = new A[i]; a = new A[c];
if (rightOp instanceof NewArrayExpr) {
Value size = ((NewArrayExpr) rightOp).getSize();
if (size instanceof Local) {
ingraph.addMutualEdges(size, leftOp, 0);
return;
}
if (size instanceof IntConstant) {
int inc_w = ((IntConstant) size).value;
ingraph.addMutualEdges(zero, leftOp, inc_w);
return;
}
}
// a = new A[i][].. ; a = new A[c]...;
if (rightOp instanceof NewMultiArrayExpr) {
Value size = ((NewMultiArrayExpr) rightOp).getSize(0);
if (size instanceof Local) {
ingraph.addMutualEdges(size, leftOp, 0);
} else if (size instanceof IntConstant) {
int inc_w = ((IntConstant) size).value;
ingraph.addMutualEdges(zero, leftOp, inc_w);
}
if (arrayin && rectarray) {
if (((NewMultiArrayExpr) rightOp).getSizeCount() > 1) {
size = ((NewMultiArrayExpr) rightOp).getSize(1);
if (size instanceof Local) {
ingraph.addMutualEdges(size, Array2ndDimensionSymbol.v(leftOp), 0);
} else if (size instanceof IntConstant) {
int inc_w = ((IntConstant) size).value;
ingraph.addMutualEdges(zero, Array2ndDimensionSymbol.v(leftOp), inc_w);
}
}
}
return;
}
// i = a.length
if (rightOp instanceof LengthExpr) {
Value base = ((LengthExpr) rightOp).getOp();
ingraph.addMutualEdges(base, leftOp, 0);
return;
}
}
/*
* assert the branch statement return true, if the out condition changed, false, otherwise
*/
private boolean assertBranchStmt(Object in, Unit s, Block current, List succs, List<Object> changedSuccs) {
IfStmt ifstmt = (IfStmt) s;
// take out the condition.
Value cmpcond = ifstmt.getCondition();
if (!(cmpcond instanceof ConditionExpr)) {
return false;
}
// how may succs?
if (succs.size() != 2) {
return false;
}
Stmt targetUnit = ifstmt.getTarget();
Block targetBlock = (Block) succs.get(0);
Block nextBlock = (Block) succs.get(1);
if (!targetUnit.equals(targetBlock.getHead())) {
Block swap = targetBlock;
targetBlock = nextBlock;
nextBlock = swap;
}
Value op1 = ((ConditionExpr) cmpcond).getOp1();
Value op2 = ((ConditionExpr) cmpcond).getOp2();
HashSet livelocals = (HashSet) ailanalysis.getFlowAfter(s);
if (!livelocals.contains(op1) && !livelocals.contains(op2)) {
return false;
}
WeightedDirectedSparseGraph ingraph = (WeightedDirectedSparseGraph) in;
WeightedDirectedSparseGraph targetgraph = ingraph.dup();
// EqExpr, GeExpr, GtExpr, LeExpr, LtExpr, NeExpr
if ((cmpcond instanceof EqExpr) || (cmpcond instanceof NeExpr)) {
Object node1 = op1, node2 = op2;
int weight = 0;
if (node1 instanceof IntConstant) {
weight = ((IntConstant) node1).value;
node1 = zero;
}
if (node2 instanceof IntConstant) {
weight = ((IntConstant) node2).value;
node2 = zero;
}
if (node1 == node2) {
return false;
}
if (cmpcond instanceof EqExpr) {
targetgraph.addMutualEdges(node1, node2, weight);
} else {
ingraph.addMutualEdges(node1, node2, weight);
}
} else if ((cmpcond instanceof GtExpr) ||
// i >= j
(cmpcond instanceof GeExpr)) {
Object node1 = op1, node2 = op2;
int weight = 0;
if (node1 instanceof IntConstant) {
weight += ((IntConstant) node1).value;
node1 = zero;
}
if (node2 instanceof IntConstant) {
weight -= ((IntConstant) node2).value;
node2 = zero;
}
if (node1 == node2) {
return false;
}
if (cmpcond instanceof GtExpr) {
targetgraph.addEdge(node1, node2, weight - 1);
ingraph.addEdge(node2, node1, -weight);
} else {
targetgraph.addEdge(node1, node2, weight);
ingraph.addEdge(node2, node1, -weight - 1);
}
} else if ((cmpcond instanceof LtExpr) || (cmpcond instanceof LeExpr)) {
// i < j
Object node1 = op1, node2 = op2;
int weight = 0;
if (node1 instanceof IntConstant) {
weight -= ((IntConstant) node1).value;
node1 = zero;
}
if (node2 instanceof IntConstant) {
weight += ((IntConstant) node2).value;
node2 = zero;
}
if (node1 == node2) {
return false;
}
if (cmpcond instanceof LtExpr) {
targetgraph.addEdge(node2, node1, weight - 1);
ingraph.addEdge(node1, node2, -weight);
} else {
targetgraph.addEdge(node2, node1, weight);
ingraph.addEdge(node1, node2, -weight - 1);
}
} else {
return false;
}
// update out edges and changed succs.
// targetgraph -> targetBlock
FlowGraphEdge targetEdge = new FlowGraphEdge(current, targetBlock);
WeightedDirectedSparseGraph prevtarget = edgeMap.get(targetEdge);
boolean changed = false;
targetgraph.makeShortestPathGraph();
WeightedDirectedSparseGraph tmpgraph = new WeightedDirectedSparseGraph(prevtarget.getVertexes(), true);
copy(targetgraph, tmpgraph);
if (!tmpgraph.equals(prevtarget)) {
prevtarget.replaceAllEdges(tmpgraph);
changed = true;
}
if (changed) {
changedSuccs.add(targetBlock);
}
// ingraph -> nextBlock
FlowGraphEdge nextEdge = new FlowGraphEdge(current, nextBlock);
WeightedDirectedSparseGraph prevnext = edgeMap.get(nextEdge);
changed = false;
ingraph.makeShortestPathGraph();
tmpgraph = new WeightedDirectedSparseGraph(prevnext.getVertexes(), true);
copy(ingraph, tmpgraph);
if (!tmpgraph.equals(prevnext)) {
prevnext.replaceAllEdges(tmpgraph);
changed = true;
}
if (changed) {
changedSuccs.add(nextBlock);
}
return true;
}
private void updateOutEdges(Object in, Block current, List succs, List<Object> changedSuccs) {
WeightedDirectedSparseGraph ingraph = (WeightedDirectedSparseGraph) in;
ingraph.makeShortestPathGraph();
for (int i = 0; i < succs.size(); i++) {
Object next = succs.get(i);
FlowGraphEdge nextEdge = new FlowGraphEdge(current, next);
WeightedDirectedSparseGraph prevs = edgeMap.get(nextEdge);
boolean changed = false;
/* equals should be used to take out sub graph first */
WeightedDirectedSparseGraph tmpgraph = new WeightedDirectedSparseGraph(prevs.getVertexes(), true);
copy(ingraph, tmpgraph);
if (!tmpgraph.equals(prevs)) {
prevs.replaceAllEdges(tmpgraph);
changed = true;
}
if (changed) {
changedSuccs.add(next);
}
}
}
protected void copy(Object from, Object to) {
WeightedDirectedSparseGraph fromgraph = (WeightedDirectedSparseGraph) from;
WeightedDirectedSparseGraph tograph = (WeightedDirectedSparseGraph) to;
tograph.clear();
tograph.addBoundedAll(fromgraph);
}
protected void widenGraphs(Object current, Object before) {
WeightedDirectedSparseGraph curgraphs = (WeightedDirectedSparseGraph) current;
WeightedDirectedSparseGraph pregraphs = (WeightedDirectedSparseGraph) before;
curgraphs.widenEdges(pregraphs);
curgraphs.makeShortestPathGraph();
}
}
| 36,189
| 29.033195
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/ArrayIndexLivenessAnalysis.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.Body;
import soot.IntType;
import soot.Local;
import soot.SootField;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AddExpr;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.IntConstant;
import soot.jimple.LengthExpr;
import soot.jimple.MulExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.SubExpr;
import soot.jimple.internal.JAddExpr;
import soot.jimple.internal.JSubExpr;
import soot.options.Options;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.scalar.BackwardFlowAnalysis;
class ArrayIndexLivenessAnalysis extends BackwardFlowAnalysis {
private static final Logger logger = LoggerFactory.getLogger(ArrayIndexLivenessAnalysis.class);
HashSet<Local> fullSet = new HashSet<Local>();
ExceptionalUnitGraph eug;
/*
* for each unit, kill set has variables to be killed. gen set was considered with conditionOfGenSet, for example, gen set
* of unit s are valid only when the condition object. was in the living input set.
*/
HashMap<Stmt, HashSet<Object>> genOfUnit;
HashMap<Stmt, HashSet<Value>> absGenOfUnit;
HashMap<Stmt, HashSet<Value>> killOfUnit;
HashMap<Stmt, HashSet<Value>> conditionOfGen;
// s --> a kill all a[?].
HashMap<DefinitionStmt, Value> killArrayRelated;
// s --> true
HashMap<DefinitionStmt, Boolean> killAllArrayRef;
IntContainer zero = new IntContainer(0);
private final boolean fieldin;
HashMap<Object, HashSet<Value>> localToFieldRef, fieldToFieldRef;
HashSet<Value> allFieldRefs;
private final boolean arrayin;
HashMap localToArrayRef;
HashSet allArrayRefs;
private final boolean csin;
HashMap<Value, HashSet<Value>> localToExpr;
private final boolean rectarray;
HashSet<Local> multiarraylocals;
public ArrayIndexLivenessAnalysis(DirectedGraph dg, boolean takeFieldRef, boolean takeArrayRef, boolean takeCSE,
boolean takeRectArray) {
super(dg);
fieldin = takeFieldRef;
arrayin = takeArrayRef;
csin = takeCSE;
rectarray = takeRectArray;
if (Options.v().debug()) {
logger.debug("Enter ArrayIndexLivenessAnalysis");
}
eug = (ExceptionalUnitGraph) dg;
retrieveAllArrayLocals(eug.getBody(), fullSet);
/* compute gen set, kill set, and condition set */
genOfUnit = new HashMap<Stmt, HashSet<Object>>(eug.size() * 2 + 1);
absGenOfUnit = new HashMap<Stmt, HashSet<Value>>(eug.size() * 2 + 1);
killOfUnit = new HashMap<Stmt, HashSet<Value>>(eug.size() * 2 + 1);
conditionOfGen = new HashMap<Stmt, HashSet<Value>>(eug.size() * 2 + 1);
if (fieldin) {
localToFieldRef = new HashMap<Object, HashSet<Value>>();
fieldToFieldRef = new HashMap<Object, HashSet<Value>>();
allFieldRefs = new HashSet<Value>();
}
if (arrayin) {
localToArrayRef = new HashMap();
allArrayRefs = new HashSet();
killArrayRelated = new HashMap<DefinitionStmt, Value>();
killAllArrayRef = new HashMap<DefinitionStmt, Boolean>();
if (rectarray) {
multiarraylocals = new HashSet<Local>();
retrieveMultiArrayLocals(eug.getBody(), multiarraylocals);
}
}
if (csin) {
localToExpr = new HashMap<Value, HashSet<Value>>();
}
getAllRelatedMaps(eug.getBody());
getGenAndKillSet(eug.getBody(), absGenOfUnit, genOfUnit, killOfUnit, conditionOfGen);
doAnalysis();
if (Options.v().debug()) {
logger.debug("Leave ArrayIndexLivenessAnalysis");
}
}
public HashMap<Object, HashSet<Value>> getLocalToFieldRef() {
return localToFieldRef;
}
public HashMap<Object, HashSet<Value>> getFieldToFieldRef() {
return fieldToFieldRef;
}
public HashSet<Value> getAllFieldRefs() {
return this.allFieldRefs;
}
public HashMap getLocalToArrayRef() {
return localToArrayRef;
}
public HashSet getAllArrayRefs() {
return allArrayRefs;
}
public HashMap<Value, HashSet<Value>> getLocalToExpr() {
return localToExpr;
}
public HashSet<Local> getMultiArrayLocals() {
return multiarraylocals;
}
private void getAllRelatedMaps(Body body) {
Iterator unitIt = body.getUnits().iterator();
while (unitIt.hasNext()) {
Stmt stmt = (Stmt) unitIt.next();
if (csin) {
if (stmt instanceof DefinitionStmt) {
Value rhs = ((DefinitionStmt) stmt).getRightOp();
if (rhs instanceof BinopExpr) {
Value op1 = ((BinopExpr) rhs).getOp1();
Value op2 = ((BinopExpr) rhs).getOp2();
if (rhs instanceof AddExpr) {
// op1 + op2 --> a + b
if ((op1 instanceof Local) && (op2 instanceof Local)) {
HashSet<Value> refs = localToExpr.get(op1);
if (refs == null) {
refs = new HashSet<Value>();
localToExpr.put(op1, refs);
}
refs.add(rhs);
refs = localToExpr.get(op2);
if (refs == null) {
refs = new HashSet<Value>();
localToExpr.put(op2, refs);
}
refs.add(rhs);
}
}
// a * b, a * c, c * a
else if (rhs instanceof MulExpr) {
HashSet<Value> refs = localToExpr.get(op1);
if (refs == null) {
refs = new HashSet<Value>();
localToExpr.put(op1, refs);
}
refs.add(rhs);
refs = localToExpr.get(op2);
if (refs == null) {
refs = new HashSet<Value>();
localToExpr.put(op2, refs);
}
refs.add(rhs);
} else if (rhs instanceof SubExpr) {
if (op2 instanceof Local) {
HashSet<Value> refs = localToExpr.get(op2);
if (refs == null) {
refs = new HashSet<Value>();
localToExpr.put(op2, refs);
}
refs.add(rhs);
if (op1 instanceof Local) {
refs = localToExpr.get(op1);
if (refs == null) {
refs = new HashSet<Value>();
localToExpr.put(op1, refs);
}
refs.add(rhs);
}
}
}
}
}
}
for (ValueBox vbox : stmt.getUseAndDefBoxes()) {
Value v = vbox.getValue();
if (fieldin) {
if (v instanceof InstanceFieldRef) {
Value base = ((InstanceFieldRef) v).getBase();
SootField field = ((InstanceFieldRef) v).getField();
HashSet<Value> baseset = localToFieldRef.get(base);
if (baseset == null) {
baseset = new HashSet<Value>();
localToFieldRef.put(base, baseset);
}
baseset.add(v);
HashSet<Value> fieldset = fieldToFieldRef.get(field);
if (fieldset == null) {
fieldset = new HashSet<Value>();
fieldToFieldRef.put(field, fieldset);
}
fieldset.add(v);
}
if (v instanceof FieldRef) {
allFieldRefs.add(v);
}
}
if (arrayin) {
// a = ... --> kill all a[x] nodes.
// a[i] = .. --> kill all array references.
// m(a) --> kill all array references
// i = ... --> kill all array reference with index as i
/*
* if (v instanceof ArrayRef) { Value base = ((ArrayRef)v).getBase(); Value index = ((ArrayRef)v).getIndex();
*
* HashSet refset = (HashSet)localToArrayRef.get(base); if (refset == null) { refset = new HashSet();
* localToArrayRef.put(base, refset); } refset.add(v);
*
* if (index instanceof Local) { refset = (HashSet)localToArrayRef.get(index); if (refset == null) { refset = new
* HashSet(); localToArrayRef.put(index, refset); }
*
* refset.add(v); } allArrayRefs.add(v); }
*/
}
}
}
}
private void retrieveAllArrayLocals(Body body, Set<Local> container) {
for (Local local : body.getLocals()) {
Type type = local.getType();
if (type instanceof IntType || type instanceof ArrayType) {
container.add(local);
}
}
}
private void retrieveMultiArrayLocals(Body body, Set<Local> container) {
for (Local local : body.getLocals()) {
Type type = local.getType();
if (type instanceof ArrayType) {
if (((ArrayType) type).numDimensions > 1) {
this.multiarraylocals.add(local);
}
}
}
}
private void getGenAndKillSetForDefnStmt(DefinitionStmt asstmt, HashMap<Stmt, HashSet<Value>> absgen,
HashSet<Object> genset, HashSet<Value> absgenset, HashSet<Value> killset, HashSet<Value> condset) {
/* kill left hand side */
Value lhs = asstmt.getLeftOp();
Value rhs = asstmt.getRightOp();
boolean killarrayrelated = false;
boolean killallarrayref = false;
if (fieldin) {
if (lhs instanceof Local) {
HashSet<Value> related = localToFieldRef.get(lhs);
if (related != null) {
killset.addAll(related);
}
} else if (lhs instanceof StaticFieldRef) {
killset.add(lhs);
condset.add(lhs);
} else if (lhs instanceof InstanceFieldRef) {
SootField field = ((InstanceFieldRef) lhs).getField();
HashSet<Value> related = fieldToFieldRef.get(field);
if (related != null) {
killset.addAll(related);
}
condset.add(lhs);
}
if (asstmt.containsInvokeExpr()) {
/*
* Value expr = asstmt.getInvokeExpr(); List parameters = ((InvokeExpr)expr).getArgs();
*
* // add the method invocation boolean killall = false; if (expr instanceof InstanceInvokeExpr) killall = true; else
* { for (int i=0; i<parameters.size(); i++) { Value para = (Value)parameters.get(i); if (para.getType() instanceof
* RefType) { killall = true; break; } } }
*
* if (killall) { killset.addAll(allInstFieldRefs); }
*/
killset.addAll(allFieldRefs);
}
}
if (arrayin) {
// a = ... or i = ...
if (lhs instanceof Local) {
killarrayrelated = true;
} else if (lhs instanceof ArrayRef) {
// a[i] = ...
killallarrayref = true;
condset.add(lhs);
}
// invokeexpr kills all array references.
if (asstmt.containsInvokeExpr()) {
killallarrayref = true;
}
}
if (csin) {
HashSet<Value> exprs = localToExpr.get(lhs);
if (exprs != null) {
killset.addAll(exprs);
}
if (rhs instanceof BinopExpr) {
Value op1 = ((BinopExpr) rhs).getOp1();
Value op2 = ((BinopExpr) rhs).getOp2();
if (rhs instanceof AddExpr) {
if ((op1 instanceof Local) && (op2 instanceof Local)) {
genset.add(rhs);
}
} else if (rhs instanceof MulExpr) {
if ((op1 instanceof Local) || (op2 instanceof Local)) {
genset.add(rhs);
}
} else if (rhs instanceof SubExpr) {
if (op2 instanceof Local) {
genset.add(rhs);
}
}
}
}
if ((lhs instanceof Local) && (fullSet.contains(lhs))) {
killset.add(lhs);
/* speculatively add lhs as live condition. */
condset.add(lhs);
} else if (lhs instanceof ArrayRef) {
/* a[i] generate a and i. */
Value base = ((ArrayRef) lhs).getBase();
Value index = ((ArrayRef) lhs).getIndex();
absgenset.add(base);
if (index instanceof Local) {
absgenset.add(index);
}
}
if (rhs instanceof Local) {
/* only lhs=rhs is valid. */
/*
* if (lhs instanceof Local && fullSet.contains(rhs)) genset.add(rhs);
*/
if (fullSet.contains(rhs)) {
genset.add(rhs);
}
/*
* if (fieldin && (lhs instanceof FieldRef)) genset.add(rhs);
*/
} else if (rhs instanceof FieldRef) {
if (fieldin) {
genset.add(rhs);
}
} else if (rhs instanceof ArrayRef) {
/* lhs=a[i]. */
Value base = ((ArrayRef) rhs).getBase();
Value index = ((ArrayRef) rhs).getIndex();
absgenset.add(base);
if (index instanceof Local) {
absgenset.add(index);
}
if (arrayin) {
genset.add(rhs);
if (rectarray) {
genset.add(Array2ndDimensionSymbol.v(base));
}
}
} else if (rhs instanceof NewArrayExpr) {
/* a = new A[i]; */
Value size = ((NewArrayExpr) rhs).getSize();
if (size instanceof Local) {
genset.add(size);
}
} else if (rhs instanceof NewMultiArrayExpr) {
/* a = new A[i][]...; */
/* More precisely, we should track other dimensions. */
List sizes = ((NewMultiArrayExpr) rhs).getSizes();
Iterator sizeIt = sizes.iterator();
while (sizeIt.hasNext()) {
Value size = (Value) sizeIt.next();
if (size instanceof Local) {
genset.add(size);
}
}
} else if (rhs instanceof LengthExpr) {
/* lhs = lengthof rhs */
Value op = ((LengthExpr) rhs).getOp();
genset.add(op);
} else if (rhs instanceof JAddExpr) {
/* lhs = rhs+c, lhs=c+rhs */
Value op1 = ((JAddExpr) rhs).getOp1();
Value op2 = ((JAddExpr) rhs).getOp2();
if ((op1 instanceof IntConstant) && (op2 instanceof Local)) {
genset.add(op2);
} else if ((op2 instanceof IntConstant) && (op1 instanceof Local)) {
genset.add(op1);
}
} else if (rhs instanceof JSubExpr) {
Value op1 = ((JSubExpr) rhs).getOp1();
Value op2 = ((JSubExpr) rhs).getOp2();
if ((op1 instanceof Local) && (op2 instanceof IntConstant)) {
genset.add(op1);
}
}
if (arrayin) {
if (killarrayrelated) {
killArrayRelated.put(asstmt, lhs);
}
if (killallarrayref) {
killAllArrayRef.put(asstmt, new Boolean(true));
}
}
}
private void getGenAndKillSet(Body body, HashMap<Stmt, HashSet<Value>> absgen, HashMap<Stmt, HashSet<Object>> gen,
HashMap<Stmt, HashSet<Value>> kill, HashMap<Stmt, HashSet<Value>> condition) {
for (Unit u : body.getUnits()) {
Stmt stmt = (Stmt) u;
HashSet<Object> genset = new HashSet<Object>();
HashSet<Value> absgenset = new HashSet<Value>();
HashSet<Value> killset = new HashSet<Value>();
HashSet<Value> condset = new HashSet<Value>();
if (stmt instanceof DefinitionStmt) {
getGenAndKillSetForDefnStmt((DefinitionStmt) stmt, absgen, genset, absgenset, killset, condset);
} else if (stmt instanceof IfStmt) {
/* if one of condition is living, than other one is live. */
Value cmpcond = ((IfStmt) stmt).getCondition();
if (cmpcond instanceof ConditionExpr) {
Value op1 = ((ConditionExpr) cmpcond).getOp1();
Value op2 = ((ConditionExpr) cmpcond).getOp2();
if (fullSet.contains(op1) && fullSet.contains(op2)) {
condset.add(op1);
condset.add(op2);
genset.add(op1);
genset.add(op2);
}
}
}
if (genset.size() != 0) {
gen.put(stmt, genset);
}
if (absgenset.size() != 0) {
absgen.put(stmt, absgenset);
}
if (killset.size() != 0) {
kill.put(stmt, killset);
}
if (condset.size() != 0) {
condition.put(stmt, condset);
}
}
}
/* It is unsafe for normal units. */
/*
* Since the initial value is safe, empty set. we do not need to do it again.
*/
protected Object newInitialFlow() {
return new HashSet();
}
/* It is safe for end units. */
protected Object entryInitialFlow() {
return new HashSet();
}
protected void flowThrough(Object inValue, Object unit, Object outValue) {
HashSet inset = (HashSet) inValue;
HashSet outset = (HashSet) outValue;
Stmt stmt = (Stmt) unit;
/* copy in set to out set. */
outset.clear();
outset.addAll(inset);
HashSet<Object> genset = genOfUnit.get(unit);
HashSet<Value> absgenset = absGenOfUnit.get(unit);
HashSet<Value> killset = killOfUnit.get(unit);
HashSet<Value> condset = conditionOfGen.get(unit);
if (killset != null) {
outset.removeAll(killset);
}
if (arrayin) {
Boolean killall = killAllArrayRef.get(stmt);
if ((killall != null) && killall.booleanValue()) {
List keylist = new ArrayList(outset);
Iterator keyIt = keylist.iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
if (key instanceof ArrayRef) {
outset.remove(key);
}
}
} else {
Object local = killArrayRelated.get(stmt);
if (local != null) {
List keylist = new ArrayList(outset);
Iterator keyIt = keylist.iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
if (key instanceof ArrayRef) {
Value base = ((ArrayRef) key).getBase();
Value index = ((ArrayRef) key).getIndex();
if (base.equals(local) || index.equals(local)) {
outset.remove(key);
}
}
if (rectarray) {
if (key instanceof Array2ndDimensionSymbol) {
Object base = ((Array2ndDimensionSymbol) key).getVar();
if (base.equals(local)) {
outset.remove(key);
}
}
}
}
}
}
}
if (genset != null) {
if (condset == null || (condset.size() == 0)) {
outset.addAll(genset);
} else {
Iterator condIt = condset.iterator();
while (condIt.hasNext()) {
if (inset.contains(condIt.next())) {
outset.addAll(genset);
break;
}
}
}
}
if (absgenset != null) {
outset.addAll(absgenset);
}
}
protected void merge(Object in1, Object in2, Object out) {
HashSet inset1 = (HashSet) in1;
HashSet inset2 = (HashSet) in2;
HashSet outset = (HashSet) out;
HashSet src = inset1;
if (outset == inset1) {
src = inset2;
} else if (outset == inset2) {
src = inset1;
} else {
outset.clear();
outset.addAll(inset2);
}
outset.addAll(src);
}
protected void copy(Object source, Object dest) {
if (source == dest) {
return;
}
HashSet sourceSet = (HashSet) source;
HashSet destSet = (HashSet) dest;
destSet.clear();
destSet.addAll(sourceSet);
}
}
| 20,248
| 28.603801
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/ArrayReferenceNode.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Local;
import soot.SootMethod;
class ArrayReferenceNode {
private final SootMethod m;
private final Local l;
public ArrayReferenceNode(SootMethod method, Local local) {
m = method;
l = local;
}
public SootMethod getMethod() {
return m;
}
public Local getLocal() {
return l;
}
public int hashCode() {
return m.hashCode() + l.hashCode() + 1;
}
public boolean equals(Object other) {
if (other instanceof ArrayReferenceNode) {
ArrayReferenceNode another = (ArrayReferenceNode) other;
return m.equals(another.getMethod()) && l.equals(another.getLocal());
}
return false;
}
public String toString() {
return "[" + m.getSignature() + " : " + l.toString() + "[ ]";
}
}
| 1,604
| 24.887097
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/BoolValue.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 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%
*/
class BoolValue {
private boolean isRectangular;
private static final BoolValue trueValue = new BoolValue(true);
private static final BoolValue falseValue = new BoolValue(false);
public BoolValue(boolean v) {
isRectangular = v;
}
public static BoolValue v(boolean v) {
if (v) {
return trueValue;
} else {
return falseValue;
}
}
public boolean getValue() {
return isRectangular;
}
public boolean or(BoolValue other) {
if (other.getValue()) {
isRectangular = true;
}
return isRectangular;
}
public boolean or(boolean other) {
if (other) {
isRectangular = true;
}
return isRectangular;
}
public boolean and(BoolValue other) {
if (!other.getValue()) {
isRectangular = false;
}
return isRectangular;
}
public boolean and(boolean other) {
if (!other) {
isRectangular = false;
}
return isRectangular;
}
public int hashCode() {
if (isRectangular) {
return 1;
} else {
return 0;
}
}
public boolean equals(Object other) {
if (other instanceof BoolValue) {
return isRectangular == ((BoolValue) other).getValue();
}
return false;
}
public String toString() {
return "[" + isRectangular + "]";
}
}
| 2,143
| 20.877551
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/BoundedPriorityList.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* BoundedPriorityList keeps a list in a priority queue. The order is decided by the initial list.
*
* @author Eric Bodden (adapted from Feng Qian's code)
*/
public class BoundedPriorityList implements Collection {
protected final List fulllist;
protected ArrayList worklist;
public BoundedPriorityList(List list) {
this.fulllist = list;
this.worklist = new ArrayList(list);
}
public boolean isEmpty() {
return worklist.isEmpty();
}
public Object removeFirst() {
return worklist.remove(0);
}
public boolean add(Object toadd) {
if (contains(toadd)) {
return false;
}
/* it is not added to the end, but keep it in the order */
int index = fulllist.indexOf(toadd);
for (ListIterator worklistIter = worklist.listIterator(); worklistIter.hasNext();) {
Object tocomp = worklistIter.next();
int tmpidx = fulllist.indexOf(tocomp);
if (index < tmpidx) {
worklistIter.add(toadd);
return true;
}
}
return false;
}
// rest is only necessary to implement the Collection interface
/**
* {@inheritDoc}
*/
public boolean addAll(Collection c) {
boolean addedSomething = false;
for (Iterator iter = c.iterator(); iter.hasNext();) {
Object o = iter.next();
addedSomething |= add(o);
}
return addedSomething;
}
/**
* {@inheritDoc}
*/
public boolean addAll(int index, Collection c) {
throw new RuntimeException("Not supported. You should use addAll(Collection) to keep priorities.");
}
/**
* {@inheritDoc}
*/
public void clear() {
worklist.clear();
}
/**
* {@inheritDoc}
*/
public boolean contains(Object o) {
return worklist.contains(o);
}
/**
* {@inheritDoc}
*/
public boolean containsAll(Collection c) {
return worklist.containsAll(c);
}
/**
* {@inheritDoc}
*/
public Iterator iterator() {
return worklist.iterator();
}
/**
* {@inheritDoc}
*/
public boolean remove(Object o) {
return worklist.remove(o);
}
/**
* {@inheritDoc}
*/
public boolean removeAll(Collection c) {
return worklist.removeAll(c);
}
/**
* {@inheritDoc}
*/
public boolean retainAll(Collection c) {
return worklist.retainAll(c);
}
/**
* {@inheritDoc}
*/
public int size() {
return worklist.size();
}
/**
* {@inheritDoc}
*/
public Object[] toArray() {
return worklist.toArray();
}
/**
* {@inheritDoc}
*/
public Object[] toArray(Object[] a) {
return worklist.toArray(a);
}
/**
* {@inheritDoc}
*/
public String toString() {
return worklist.toString();
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj) {
return worklist.equals(obj);
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return worklist.hashCode();
}
}
| 3,862
| 19.881081
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/ClassFieldAnalysis.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.Body;
import soot.G;
import soot.Local;
import soot.Modifier;
import soot.Singletons;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.IntConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.toolkits.scalar.LocalDefs;
public class ClassFieldAnalysis {
private static final Logger logger = LoggerFactory.getLogger(ClassFieldAnalysis.class);
public ClassFieldAnalysis(Singletons.Global g) {
}
public static ClassFieldAnalysis v() {
return G.v().soot_jimple_toolkits_annotation_arraycheck_ClassFieldAnalysis();
}
private final boolean final_in = true;
private final boolean private_in = true;
/*
* A map hold class object to other information
*
* SootClass --> FieldInfoTable
*/
private final Map<SootClass, Hashtable<SootField, IntValueContainer>> classToFieldInfoMap
= new HashMap<SootClass, Hashtable<SootField, IntValueContainer>>();
protected void internalTransform(SootClass c) {
if (classToFieldInfoMap.containsKey(c)) {
return;
}
/* Summerize class information here. */
Date start = new Date();
if (Options.v().verbose()) {
logger.debug("[] ClassFieldAnalysis started on : " + start + " for " + c.getPackageName() + c.getName());
}
Hashtable<SootField, IntValueContainer> fieldInfoTable = new Hashtable<SootField, IntValueContainer>();
classToFieldInfoMap.put(c, fieldInfoTable);
/*
* Who is the candidate for analysis? Int, Array, field. Also it should be PRIVATE now.
*/
HashSet<SootField> candidSet = new HashSet<SootField>();
int arrayTypeFieldNum = 0;
Iterator<SootField> fieldIt = c.getFields().iterator();
while (fieldIt.hasNext()) {
SootField field = fieldIt.next();
int modifiers = field.getModifiers();
Type type = field.getType();
if (type instanceof ArrayType) {
if ((final_in && ((modifiers & Modifier.FINAL) != 0)) || (private_in && ((modifiers & Modifier.PRIVATE) != 0))) {
candidSet.add(field);
arrayTypeFieldNum++;
}
}
}
if (arrayTypeFieldNum == 0) {
if (Options.v().verbose()) {
logger.debug("[] ClassFieldAnalysis finished with nothing");
}
return;
}
/* For FINAL field, it only needs to scan the <clinit> and <init> methods. */
/*
* For PRIVATE field, <clinit> is scanned to make sure that it is always assigned a value before other uses. And no other
* assignment in other methods.
*/
/*
* The fastest way to determine the value of one field may get. Scan all method to get all definitions, and summerize the
* final value. For PRIVATE STATIC field, if it is not always assigned value, it may count null pointer exception before
* array exception
*/
Iterator<SootMethod> methodIt = c.methodIterator();
while (methodIt.hasNext()) {
ScanMethod(methodIt.next(), candidSet, fieldInfoTable);
}
Date finish = new Date();
if (Options.v().verbose()) {
long runtime = finish.getTime() - start.getTime();
long mins = runtime / 60000;
long secs = (runtime % 60000) / 1000;
logger.debug("[] ClassFieldAnalysis finished normally. " + "It took " + mins + " mins and " + secs + " secs.");
}
}
public Object getFieldInfo(SootField field) {
SootClass c = field.getDeclaringClass();
Map<SootField, IntValueContainer> fieldInfoTable = classToFieldInfoMap.get(c);
if (fieldInfoTable == null) {
internalTransform(c);
fieldInfoTable = classToFieldInfoMap.get(c);
}
return fieldInfoTable.get(field);
}
/*
* method, to be scanned candidates, the candidate set of fields, fields with value TOP are moved out of the set.
* fieldinfo, keep the field -> value.
*/
public void ScanMethod(SootMethod method, Set<SootField> candidates, Hashtable<SootField, IntValueContainer> fieldinfo) {
if (!method.isConcrete()) {
return;
}
Body body = method.retrieveActiveBody();
if (body == null) {
return;
}
/* no array locals, then definitely it has no array type field references. */
{
boolean hasArrayLocal = false;
Collection<Local> locals = body.getLocals();
Iterator<Local> localIt = locals.iterator();
while (localIt.hasNext()) {
Local local = localIt.next();
Type type = local.getType();
if (type instanceof ArrayType) {
hasArrayLocal = true;
break;
}
}
if (!hasArrayLocal) {
return;
}
}
/* only take care of the first dimension of array size */
/* check the assignment of fields. */
/* Linearly scan the method body, if it has field references in candidate set. */
/*
* Only a.f = ... needs consideration. this.f, or other.f are treated as same because we summerize the field as a class's
* field.
*/
HashMap<Stmt, SootField> stmtfield = new HashMap<Stmt, SootField>();
{
Iterator<Unit> unitIt = body.getUnits().iterator();
while (unitIt.hasNext()) {
Stmt stmt = (Stmt) unitIt.next();
if (stmt.containsFieldRef()) {
Value leftOp = ((AssignStmt) stmt).getLeftOp();
if (leftOp instanceof FieldRef) {
FieldRef fref = (FieldRef) leftOp;
SootField field = fref.getField();
if (candidates.contains(field)) {
stmtfield.put(stmt, field);
}
}
}
}
if (stmtfield.size() == 0) {
return;
}
}
if (Options.v().verbose()) {
logger.debug("[] ScanMethod for field started.");
}
/* build D/U web, find the value of each candidate */
{
LocalDefs localDefs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(body);
Set<Map.Entry<Stmt, SootField>> entries = stmtfield.entrySet();
Iterator<Map.Entry<Stmt, SootField>> entryIt = entries.iterator();
while (entryIt.hasNext()) {
Map.Entry<Stmt, SootField> entry = entryIt.next();
Stmt where = entry.getKey();
SootField which = entry.getValue();
IntValueContainer length = new IntValueContainer();
// take out the right side of assign stmt
Value rightOp = ((AssignStmt) where).getRightOp();
if (rightOp instanceof Local) {
// tracing down the defs of right side local.
Local local = (Local) rightOp;
DefinitionStmt usestmt = (DefinitionStmt) where;
while (length.isBottom()) {
List<Unit> defs = localDefs.getDefsOfAt(local, usestmt);
if (defs.size() == 1) {
usestmt = (DefinitionStmt) defs.get(0);
if (Options.v().debug()) {
logger.debug(" " + usestmt);
}
Value tmp_rhs = usestmt.getRightOp();
if ((tmp_rhs instanceof NewArrayExpr) || (tmp_rhs instanceof NewMultiArrayExpr)) {
Value size;
if (tmp_rhs instanceof NewArrayExpr) {
size = ((NewArrayExpr) tmp_rhs).getSize();
} else {
size = ((NewMultiArrayExpr) tmp_rhs).getSize(0);
}
if (size instanceof IntConstant) {
length.setValue(((IntConstant) size).value);
} else if (size instanceof Local) {
local = (Local) size;
// defs = localDefs.getDefsOfAt((Local)size, (Unit)usestmt);
continue;
} else {
length.setTop();
}
} else if (tmp_rhs instanceof IntConstant) {
length.setValue(((IntConstant) tmp_rhs).value);
} else if (tmp_rhs instanceof Local) {
// defs = localDefs.getDefsOfAt((Local)tmp_rhs, usestmt);
local = (Local) tmp_rhs;
continue;
} else {
length.setTop();
}
} else {
length.setTop();
}
}
} else {
/* it could be null */
continue;
}
IntValueContainer oldv = fieldinfo.get(which);
/* the length is top, set the field to top */
if (length.isTop()) {
if (oldv == null) {
fieldinfo.put(which, length.dup());
} else {
oldv.setTop();
}
/* remove from the candidate set. */
candidates.remove(which);
} else if (length.isInteger()) {
if (oldv == null) {
fieldinfo.put(which, length.dup());
} else {
if (oldv.isInteger() && oldv.getValue() != length.getValue()) {
oldv.setTop();
candidates.remove(which);
}
}
}
}
}
if (Options.v().verbose()) {
logger.debug("[] ScanMethod finished.");
}
}
}
| 10,361
| 29.476471
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/ExtendedHashMutableDirectedGraph.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import soot.toolkits.graph.HashMutableDirectedGraph;
/**
* add skipNode method to direct all predecessor edges to successors.
*
* override 'addEdge' to add node if the node was not in the graph
*
* @param <N>
*/
public class ExtendedHashMutableDirectedGraph<N> extends HashMutableDirectedGraph<N> {
public ExtendedHashMutableDirectedGraph() {
}
/**
* If nodes are not in the graph, add them into graph first.
*/
@Override
public void addEdge(N from, N to) {
if (!super.containsNode(from)) {
super.addNode(from);
}
if (!super.containsNode(to)) {
super.addNode(to);
}
super.addEdge(from, to);
}
/**
* Add mutual edge to the graph. It should be optimized in the future.
*/
public void addMutualEdge(N from, N to) {
if (!super.containsNode(from)) {
super.addNode(from);
}
if (!super.containsNode(to)) {
super.addNode(to);
}
super.addEdge(from, to);
super.addEdge(to, from);
}
/**
* Bypass the in edge to out edge. Not delete the node
*/
public void skipNode(N node) {
if (!super.containsNode(node)) {
return;
}
ArrayList<N> origPreds = new ArrayList<N>(getPredsOf(node));
ArrayList<N> origSuccs = new ArrayList<N>(getSuccsOf(node));
for (N p : origPreds) {
for (N s : origSuccs) {
if (p != s) {
super.addEdge(p, s);
}
}
}
for (N element : origPreds) {
super.removeEdge(element, node);
}
for (N element : origSuccs) {
super.removeEdge(node, element);
}
super.removeNode(node);
}
public <T extends N> void mergeWith(ExtendedHashMutableDirectedGraph<T> other) {
for (T node : other.getNodes()) {
for (T succ : other.getSuccsOf(node)) {
this.addEdge(node, succ);
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Graph:\n");
for (N node : super.getNodes()) {
for (N succ : super.getSuccsOf(node)) {
sb.append(node).append("\t --- \t").append(succ).append('\n');
}
}
return sb.toString();
}
}
| 3,015
| 23.721311
| 86
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/FlowGraphEdge.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 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%
*/
class FlowGraphEdge {
Object from;
Object to;
public FlowGraphEdge() {
this.from = null;
this.to = null;
}
public FlowGraphEdge(Object from, Object to) {
this.from = from;
this.to = to;
}
public int hashCode() {
return this.from.hashCode() ^ this.to.hashCode();
}
public Object getStartUnit() {
return this.from;
}
public Object getTargetUnit() {
return this.to;
}
public void changeEndUnits(Object from, Object to) {
this.from = from;
this.to = to;
}
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other instanceof FlowGraphEdge) {
Object otherstart = ((FlowGraphEdge) other).getStartUnit();
Object othertarget = ((FlowGraphEdge) other).getTargetUnit();
return (this.from.equals(otherstart) && this.to.equals(othertarget));
} else {
return false;
}
}
}
| 1,760
| 23.802817
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/IntContainer.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 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%
*/
class IntContainer {
static IntContainer[] pool = new IntContainer[100];
static {
for (int i = 0; i < 100; i++) {
pool[i] = new IntContainer(i - 50);
}
}
int value;
public IntContainer(int v) {
this.value = v;
}
public static IntContainer v(int v) {
if ((v >= -50) && (v <= 49)) {
return pool[v + 50];
} else {
return new IntContainer(v);
}
}
public IntContainer dup() {
return new IntContainer(value);
}
public int hashCode() {
return value;
}
public boolean equals(Object other) {
if (other instanceof IntContainer) {
return ((IntContainer) other).value == this.value;
}
return false;
}
public String toString() {
return "" + value;
}
}
| 1,599
| 22.529412
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/IntValueContainer.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 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%
*/
class IntValueContainer {
private static final int BOT = 0;
private static final int TOP = 1;
private static final int INT = 2;
private int type;
private int value;
public IntValueContainer() {
this.type = BOT;
}
public IntValueContainer(int v) {
this.type = INT;
this.value = v;
}
public boolean isBottom() {
return (this.type == BOT);
}
public boolean isTop() {
return (this.type == TOP);
}
public boolean isInteger() {
return this.type == INT;
}
public int getValue() {
if (this.type != INT) {
throw new RuntimeException("IntValueContainer: not integer type");
}
return this.value;
}
public void setTop() {
this.type = TOP;
}
public void setValue(int v) {
this.type = INT;
this.value = v;
}
public void setBottom() {
this.type = BOT;
}
public String toString() {
if (type == BOT) {
return "[B]";
} else if (type == TOP) {
return "[T]";
} else {
return "[" + value + "]";
}
}
public boolean equals(Object other) {
if (!(other instanceof IntValueContainer)) {
return false;
}
IntValueContainer otherv = (IntValueContainer) other;
if ((this.type == INT) && (otherv.type == INT)) {
return (this.value == otherv.value);
} else {
return (this.type == otherv.type);
}
}
public IntValueContainer dup() {
IntValueContainer other = new IntValueContainer();
other.type = this.type;
other.value = this.value;
return other;
}
}
| 2,390
| 21.345794
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/MethodLocal.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Local;
import soot.SootMethod;
class MethodLocal {
private final SootMethod m;
private final Local l;
public MethodLocal(SootMethod method, Local local) {
m = method;
l = local;
}
public SootMethod getMethod() {
return m;
}
public Local getLocal() {
return l;
}
public int hashCode() {
return m.hashCode() + l.hashCode();
}
public boolean equals(Object other) {
if (other instanceof MethodLocal) {
MethodLocal another = (MethodLocal) other;
return m.equals(another.getMethod()) && l.equals(another.getLocal());
}
return false;
}
public String toString() {
return "[" + m.getSignature() + " : " + l.toString() + "]";
}
}
| 1,563
| 24.225806
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/MethodParameter.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.Type;
class MethodParameter {
private SootMethod m;
private int param;
public MethodParameter(SootMethod m, int i) {
this.m = m;
this.param = i;
}
public Type getType() {
return m.getParameterType(param);
}
public int hashCode() {
return m.hashCode() + param;
}
public SootMethod getMethod() {
return m;
}
public int getIndex() {
return param;
}
public boolean equals(Object other) {
if (other instanceof MethodParameter) {
MethodParameter another = (MethodParameter) other;
return (m.equals(another.getMethod()) && param == another.getIndex());
}
return false;
}
public String toString() {
return "[" + m.getSignature() + " : P" + param + "]";
}
}
| 1,626
| 23.283582
| 76
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/MethodReturn.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.Type;
class MethodReturn {
private SootMethod m;
public MethodReturn(SootMethod m) {
this.m = m;
}
public SootMethod getMethod() {
return m;
}
public Type getType() {
return m.getReturnType();
}
public int hashCode() {
return m.hashCode() + m.getParameterCount();
}
public boolean equals(Object other) {
if (other instanceof MethodReturn) {
return m.equals(((MethodReturn) other).getMethod());
}
return false;
}
public String toString() {
return "[" + m.getSignature() + " : R]";
}
}
| 1,439
| 23.40678
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/RectangularArrayFinder.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.Body;
import soot.G;
import soot.Local;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.ParameterRef;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.internal.JArrayRef;
import soot.jimple.internal.JNewMultiArrayExpr;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Targets;
import soot.options.Options;
import soot.util.Chain;
/**
* Interprocedural analysis to identify rectangular multi-dimension array locals. It is based on the call graph.
*/
public class RectangularArrayFinder extends SceneTransformer {
private static final Logger logger = LoggerFactory.getLogger(RectangularArrayFinder.class);
public RectangularArrayFinder(Singletons.Global g) {
}
public static RectangularArrayFinder v() {
return G.v().soot_jimple_toolkits_annotation_arraycheck_RectangularArrayFinder();
}
private final ExtendedHashMutableDirectedGraph<Object> agraph = new ExtendedHashMutableDirectedGraph<Object>();
private final Set<Object> falseSet = new HashSet<Object>();
private final Set<Object> trueSet = new HashSet<Object>();
private CallGraph cg;
@Override
protected void internalTransform(String phaseName, Map<String, String> opts) {
Scene sc = Scene.v();
cg = sc.getCallGraph();
Date start = new Date();
if (Options.v().verbose()) {
logger.debug("[ra] Finding rectangular arrays, start on " + start);
}
for (SootClass c : sc.getApplicationClasses()) {
for (Iterator<SootMethod> methodIt = c.methodIterator(); methodIt.hasNext();) {
SootMethod method = methodIt.next();
if (!method.isConcrete()) {
continue;
}
if (!sc.getReachableMethods().contains(method)) {
continue;
}
recoverRectArray(method);
addInfoFromMethod(method);// initializes the graph
}
}
/*
* MutableDirectedGraph methodGraph = ig.newMethodGraph(); HashSet visitedMethods = new HashSet(); LinkedList
* tovisitMethods = new LinkedList();
*
* List heads = methodGraph.getHeads(); Iterator headIt = heads.iterator(); while (headIt.hasNext()) { SootMethod entry =
* (SootMethod)headIt.next(); String sig = entry.getSubSignature();
*
* if (sig.equals(mainSignature)) tovisitMethods.add(entry); }
*
* while (!tovisitMethods.isEmpty()) { SootMethod visiting = (SootMethod)tovisitMethods.removeFirst();
* visitedMethods.add(visiting);
*
* recoverRectArray(visiting); addInfoFromMethod(visiting);
*
* List succs = methodGraph.getSuccsOf(visiting); Iterator succIt = succs.iterator(); while (succIt.hasNext()) { Object
* succ = succIt.next(); if (!visitedMethods.contains(succ)) tovisitMethods.add(succ); } }
*/
/* propagate the graph info from FALSE node. */
if (agraph.containsNode(BoolValue.v(false))) {
List<Object> startNodes = agraph.getSuccsOf(BoolValue.v(false));
falseSet.addAll(startNodes);
List<Object> changedNodeList = new ArrayList<Object>(startNodes);
while (!changedNodeList.isEmpty()) {
Object node = changedNodeList.remove(0);
for (Object succ : agraph.getSuccsOf(node)) {
if (!falseSet.contains(succ)) {
falseSet.add(succ);
changedNodeList.add(succ);
}
}
}
}
/* propagate graph info from TRUE node then. */
if (agraph.containsNode(BoolValue.v(true))) {
List<Object> changedNodeList = new ArrayList<Object>();
for (Object node : agraph.getSuccsOf(BoolValue.v(true))) {
if (!falseSet.contains(node)) {
changedNodeList.add(node);
trueSet.add(node);
}
}
while (!changedNodeList.isEmpty()) {
Object node = changedNodeList.remove(0);
for (Object succ : agraph.getSuccsOf(node)) {
if (falseSet.contains(succ)) {
continue;
}
if (trueSet.contains(succ)) {
continue;
}
trueSet.add(succ);
changedNodeList.add(succ);
}
}
}
/* For verification, print out true set and false set. */
if (Options.v().debug()) {
logger.debug("Rectangular Array :");
for (Object node : trueSet) {
logger.debug("" + node);
}
logger.debug("\nNon-rectangular Array :");
for (Object node : falseSet) {
logger.debug("" + node);
}
}
if (Options.v().verbose()) {
Date finish = new Date();
long runtime = finish.getTime() - start.getTime();
long mins = runtime / 60000;
long secs = (runtime % 60000) / 1000;
logger.debug("[ra] Rectangular array finder finishes. It took " + mins + " mins and " + secs + " secs.");
}
}
private void addInfoFromMethod(SootMethod method) {
if (Options.v().verbose()) {
logger.debug("[ra] Operating " + method.getSignature());
}
boolean needTransfer = true;
boolean trackReturn = false;
/* check the return type of method, if it is multi-array. */
Type rtnType = method.getReturnType();
if (rtnType instanceof ArrayType) {
if (((ArrayType) rtnType).numDimensions > 1) {
trackReturn = true;
needTransfer = true;
}
}
final Body body = method.getActiveBody();
Set<Object> tmpNode = new HashSet<Object>();
Set<Value> arrayLocal = new HashSet<Value>();
/* Collect the multi-array locals */
for (Local local : body.getLocals()) {
Type type = local.getType();
if (type instanceof ArrayType) {
if (((ArrayType) type).numDimensions > 1) {
arrayLocal.add(local);
} else {
tmpNode.add(new MethodLocal(method, local));
}
}
}
/* The method has a local graph. It will be merged to the whole graph after simplification. */
ExtendedHashMutableDirectedGraph<Object> ehmdg = new ExtendedHashMutableDirectedGraph<Object>();
for (Iterator<Unit> unitIt = body.getUnits().snapshotIterator(); unitIt.hasNext();) {
Stmt s = (Stmt) unitIt.next();
/* for each invoke site, add edges from local parameter to the target methods' parameter node. */
if (s.containsInvokeExpr()) {
InvokeExpr iexpr = s.getInvokeExpr();
int argnum = iexpr.getArgCount();
for (int i = 0; i < argnum; i++) {
Value arg = iexpr.getArg(i);
if (arrayLocal.contains(arg)) {
needTransfer = true;
/* from node, it is a local */
MethodLocal ml = new MethodLocal(method, (Local) arg);
for (Targets targetIt = new Targets(cg.edgesOutOf(s)); targetIt.hasNext();) {
SootMethod target = (SootMethod) targetIt.next();
MethodParameter mp = new MethodParameter(target, i);
/* add edge to the graph. */
ehmdg.addMutualEdge(ml, mp);
}
}
}
}
/* if the return type is multiarray, add an mutual edge from local to return node. */
if (trackReturn && (s instanceof ReturnStmt)) {
Value op = ((ReturnStmt) s).getOp();
if (op instanceof Local) {
ehmdg.addMutualEdge(new MethodLocal(method, (Local) op), new MethodReturn(method));
}
}
/* examine each assign statement. build edge relationship between them. */
if (s instanceof DefinitionStmt) {
Value leftOp = ((DefinitionStmt) s).getLeftOp();
Value rightOp = ((DefinitionStmt) s).getRightOp();
if (!(leftOp.getType() instanceof ArrayType) && !(rightOp.getType() instanceof ArrayType)) {
continue;
}
/* kick out the possible cast. */
if ((leftOp instanceof Local) && (rightOp instanceof Local)) {
if (arrayLocal.contains(leftOp) && arrayLocal.contains(rightOp)) {
int leftDims = ((ArrayType) ((Local) leftOp).getType()).numDimensions;
int rightDims = ((ArrayType) ((Local) rightOp).getType()).numDimensions;
Object to = new MethodLocal(method, (Local) leftOp);
Object from = new MethodLocal(method, (Local) rightOp);
ehmdg.addMutualEdge(from, to);
if (leftDims != rightDims) {
ehmdg.addEdge(BoolValue.v(false), from);
}
} else if (!arrayLocal.contains(leftOp)) {
/* implicitly cast from right side to left side, and the left side declare type is Object ... */
ehmdg.addEdge(BoolValue.v(false), new MethodLocal(method, (Local) rightOp));
}
} else if ((leftOp instanceof Local) && (rightOp instanceof ParameterRef)) {
if (arrayLocal.contains(leftOp)) {
Object to = new MethodLocal(method, (Local) leftOp);
int index = ((ParameterRef) rightOp).getIndex();
Object from = new MethodParameter(method, index);
ehmdg.addMutualEdge(from, to);
needTransfer = true;
}
} else if ((leftOp instanceof Local) && (rightOp instanceof ArrayRef)) {
Local base = (Local) ((ArrayRef) rightOp).getBase();
/* it may include one-dimension array into the graph, */
if (arrayLocal.contains(base)) {
/* add 'a' to 'a[' first */
Object to = new ArrayReferenceNode(method, base);
Object from = new MethodLocal(method, base);
ehmdg.addMutualEdge(from, to);
/* put 'a[' into temporary object pool. */
tmpNode.add(to);
/* add 'a[' to 'p' then */
from = to;
to = new MethodLocal(method, (Local) leftOp);
ehmdg.addMutualEdge(from, to);
}
} else if ((leftOp instanceof ArrayRef) && (rightOp instanceof Local)) {
Local base = (Local) ((ArrayRef) leftOp).getBase();
if (arrayLocal.contains(base)) {
/* to recover the SWAP of array dimensions. */
Object suspect = new MethodLocal(method, (Local) rightOp);
boolean addEdge = true;
if (ehmdg.containsNode(suspect)) {
Set<Object> neighbor = new HashSet<Object>();
neighbor.addAll(ehmdg.getSuccsOf(suspect));
neighbor.addAll(ehmdg.getSuccsOf(suspect));
if (neighbor.size() == 1) {
Object arrRef = new ArrayReferenceNode(method, base);
if (arrRef.equals(neighbor.iterator().next())) {
addEdge = false;
}
}
}
if (addEdge) {
ehmdg.addEdge(BoolValue.v(false), new MethodLocal(method, base));
}
}
} else if ((leftOp instanceof Local) && (rightOp instanceof InvokeExpr)) {
if (arrayLocal.contains(leftOp)) {
Object to = new MethodLocal(method, (Local) leftOp);
for (Targets targetIt = new Targets(cg.edgesOutOf(s)); targetIt.hasNext();) {
SootMethod target = (SootMethod) targetIt.next();
ehmdg.addMutualEdge(new MethodReturn(target), to);
}
}
} else if ((leftOp instanceof FieldRef) && (rightOp instanceof Local)) {
/* For field reference, we can make conservative assumption that all instance fieldRef use the same node. */
if (arrayLocal.contains(rightOp)) {
Object to = ((FieldRef) leftOp).getField();
Object from = new MethodLocal(method, (Local) rightOp);
ehmdg.addMutualEdge(from, to);
Type ftype = ((FieldRef) leftOp).getType();
Type ltype = ((Local) rightOp).getType();
if (!ftype.equals(ltype)) {
ehmdg.addEdge(BoolValue.v(false), to);
}
needTransfer = true;
}
} else if ((leftOp instanceof Local) && (rightOp instanceof FieldRef)) {
if (arrayLocal.contains(leftOp)) {
Object to = new MethodLocal(method, (Local) leftOp);
Object from = ((FieldRef) rightOp).getField();
ehmdg.addMutualEdge(from, to);
Type ftype = ((FieldRef) rightOp).getType();
Type ltype = ((Local) leftOp).getType();
if (!ftype.equals(ltype)) {
ehmdg.addEdge(BoolValue.v(false), to);
}
needTransfer = true;
}
} else if ((leftOp instanceof Local)
&& ((rightOp instanceof NewArrayExpr) || (rightOp instanceof NewMultiArrayExpr))) {
if (arrayLocal.contains(leftOp)) {
ehmdg.addEdge(BoolValue.v(true), new MethodLocal(method, (Local) leftOp));
}
} else if ((leftOp instanceof Local) && (rightOp instanceof CastExpr)) {
/* Cast express, we will use conservative solution. */
Local rOp = (Local) ((CastExpr) rightOp).getOp();
Object to = new MethodLocal(method, (Local) leftOp);
Object from = new MethodLocal(method, rOp);
if (arrayLocal.contains(leftOp) && arrayLocal.contains(rOp)) {
ArrayType lat = (ArrayType) leftOp.getType();
ArrayType rat = (ArrayType) rOp.getType();
if (lat.numDimensions == rat.numDimensions) {
ehmdg.addMutualEdge(from, to);
} else {
ehmdg.addEdge(BoolValue.v(false), from);
ehmdg.addEdge(BoolValue.v(false), to);
}
} else if (arrayLocal.contains(leftOp)) {
ehmdg.addEdge(BoolValue.v(false), to);
} else if (arrayLocal.contains(rOp)) {
ehmdg.addEdge(BoolValue.v(false), from);
}
}
}
}
/* Compute the graph locally, it will skip all locals */
if (needTransfer) {
for (Object next : tmpNode) {
ehmdg.skipNode(next);
}
/* Add local graph to whole graph */
agraph.mergeWith(ehmdg);
}
}
private void recoverRectArray(final SootMethod method) {
final Body body = method.getActiveBody();
HashSet<Value> malocal = new HashSet<Value>();
for (Local local : body.getLocals()) {
Type type = local.getType();
if (type instanceof ArrayType) {
if (((ArrayType) type).numDimensions == 2) {
malocal.add(local);
}
}
}
if (malocal.isEmpty()) {
return;
}
Chain<Unit> units = body.getUnits();
for (Stmt stmt = (Stmt) units.getFirst(); true;) {
if (stmt == null) {
break;
}
/* only deal with the first block */
if (!stmt.fallsThrough()) {
break;
}
searchblock: {
/* possible candidates */
if (!(stmt instanceof AssignStmt)) {
break searchblock;
}
Value leftOp = ((AssignStmt) stmt).getLeftOp();
Value rightOp = ((AssignStmt) stmt).getRightOp();
if (!malocal.contains(leftOp) || !(rightOp instanceof NewArrayExpr)) {
break searchblock;
}
Local local = (Local) leftOp;
NewArrayExpr naexpr = (NewArrayExpr) rightOp;
Value size = naexpr.getSize();
if (!(size instanceof IntConstant)) {
break searchblock;
}
int firstdim = ((IntConstant) size).value;
if (firstdim > 100) {
break searchblock;
}
ArrayType localtype = (ArrayType) local.getType();
Type basetype = localtype.baseType;
Local[] tmplocals = new Local[firstdim];
int seconddim = lookforPattern(units, stmt, firstdim, local, basetype, tmplocals);
if (seconddim >= 0) {
transferPattern(units, stmt, firstdim, seconddim, local, basetype, tmplocals);
}
}
stmt = (Stmt) units.getSuccOf(stmt);
}
}
/*
* if the local is assigned a rect array, return back the second dimension length, else return -1
*/
private int lookforPattern(Chain<Unit> units, Stmt startpoint, int firstdim, Local local, Type baseTy, Local[] tmplocals) {
/* It is a state machine to match the pattern */
/*
* state input goto start r1 = new(A[])[c] 1 1 r2 = newA[d] 2 2 r2[?] = ... 2 r1[e] = r2 (e = c-1) 3 r1[e] = r2 (e =
* e'+1) 2 3 end
*/
int seconddim = -1;
int curdim = 0;
Value curtmp = local; // Local, I have to initialize it. It should not be this value.
Stmt curstmt = startpoint;
int fault = 99;
int state = 1;
while (true) {
curstmt = (Stmt) units.getSuccOf(curstmt);
if (curstmt == null) {
return -1;
}
if (!(curstmt instanceof AssignStmt)) {
return -1;
}
Value leftOp = ((AssignStmt) curstmt).getLeftOp();
Value rightOp = ((AssignStmt) curstmt).getRightOp();
switch (state) {
case 0:
/* we already did state 0 outside */
break;
case 1: {
/* make sure it is a new array expr */
state = fault;
if (!(rightOp instanceof NewArrayExpr)) {
break;
}
NewArrayExpr naexpr = (NewArrayExpr) rightOp;
Type type = naexpr.getBaseType();
Value size = naexpr.getSize();
if (!type.equals(baseTy)) {
break;
}
if (!(size instanceof IntConstant)) {
break;
}
if (curdim == 0) {
seconddim = ((IntConstant) size).value;
} else if (((IntConstant) size).value != seconddim) {
break;
}
curtmp = leftOp;
state = 2;
break;
}
case 2: {
state = fault;
if (!(leftOp instanceof ArrayRef)) {
break;
}
Value base = ((ArrayRef) leftOp).getBase();
Value idx = ((ArrayRef) leftOp).getIndex();
/* curtmp[?] = ? */
if (base.equals(curtmp)) {
state = 2;
} else if (base.equals(local)) {
/* local[?] = curtmp? */
if (!(idx instanceof IntConstant)) {
break;
}
if (curdim != ((IntConstant) idx).value) {
break;
}
if (!rightOp.equals(curtmp)) {
break;
}
tmplocals[curdim] = (Local) curtmp;
curdim++;
if (curdim >= firstdim) {
state = 3;
} else {
state = 1;
}
}
break;
}
case 3:
return seconddim;
default:
return -1;
}
}
}
private void transferPattern(Chain<Unit> units, Stmt startpoint, int firstdim, int seconddim, Local local, Type baseTy,
Local[] tmplocals) {
/* sequentially search and replace the sub dimension assignment */
{
/* change the first one, reset the right op */
List<Value> sizes = new ArrayList<Value>(2);
sizes.add(IntConstant.v(firstdim));
sizes.add(IntConstant.v(seconddim));
Value nmexpr = new JNewMultiArrayExpr((ArrayType) local.getType(), sizes);
((AssignStmt) startpoint).setRightOp(nmexpr);
}
int curdim = 0;
Local tmpcur = local;
Stmt curstmt = (Stmt) units.getSuccOf(startpoint);
while (curdim < firstdim) {
Value leftOp = ((AssignStmt) curstmt).getLeftOp();
Value rightOp = ((AssignStmt) curstmt).getRightOp();
if (tmplocals[curdim].equals(leftOp) && (rightOp instanceof NewArrayExpr)) {
ArrayRef arexpr = new JArrayRef(local, IntConstant.v(curdim));
((AssignStmt) curstmt).setRightOp(arexpr);
tmpcur = (Local) leftOp;
} else if ((leftOp instanceof ArrayRef) && (rightOp.equals(tmpcur))) {
/* delete current stmt */
Stmt tmpstmt = curstmt;
curstmt = (Stmt) units.getSuccOf(curstmt);
units.remove(tmpstmt);
curdim++;
} else {
curstmt = (Stmt) units.getSuccOf(curstmt);
}
}
}
public boolean isRectangular(Object obj) {
return trueSet.contains(obj);
}
}
| 21,455
| 32.577465
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/WeightedDirectedEdge.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 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%
*/
class WeightedDirectedEdge {
Object from, to;
int weight;
public WeightedDirectedEdge(Object from, Object to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
public int hashCode() {
return from.hashCode() + to.hashCode() + weight;
}
public boolean equals(Object other) {
if (other instanceof WeightedDirectedEdge) {
WeightedDirectedEdge another = (WeightedDirectedEdge) other;
return ((this.from == another.from) && (this.to == another.to) && (this.weight == another.weight));
}
return false;
}
public String toString() {
return from + "->" + to + "=" + weight;
}
}
| 1,503
| 28.490196
| 105
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/arraycheck/WeightedDirectedSparseGraph.java
|
package soot.jimple.toolkits.annotation.arraycheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
class WeightedDirectedSparseGraph {
private boolean isUnknown;
/* The graph is in linked list structure. */
private Hashtable<Object, Hashtable<Object, IntContainer>> sources
= new Hashtable<Object, Hashtable<Object, IntContainer>>();
/* vertex set, may contain superious nodes. */
private HashSet vertexes = new HashSet();
public WeightedDirectedSparseGraph(HashSet vertexset) {
this(vertexset, false);
}
public WeightedDirectedSparseGraph(HashSet vertexset, boolean isTop) {
this.vertexes = vertexset;
this.isUnknown = !isTop;
}
public void setTop() {
this.isUnknown = false;
this.sources.clear();
}
public HashSet getVertexes() {
return this.vertexes;
}
public void setVertexes(HashSet newset) {
this.vertexes = newset;
this.sources.clear();
}
/**
* Add an edge with weight to the graph
*/
public void addEdge(Object from, Object to, int w) {
if (this.isUnknown) {
throw new RuntimeException("Unknown graph can not have edges");
}
Hashtable<Object, IntContainer> targets = sources.get(from);
if (targets == null) {
/* a new node was added to the graph */
targets = new Hashtable<Object, IntContainer>();
sources.put(from, targets);
}
IntContainer weight = targets.get(to);
if (weight == null) {
weight = new IntContainer(w);
targets.put(to, weight);
} else {
if (weight.value > w) {
weight.value = w;
}
}
}
/**
* addMutualEdge adds bi-direct edges between two nodes. for example, i = j + 1; generates two directed edges. one from j
* to i with weight 1, another from i to j with weight -1
*/
public void addMutualEdges(Object from, Object to, int weight) {
addEdge(from, to, weight);
addEdge(to, from, -weight);
}
/*
* removeEdge removes all edges from source to target.
*/
public void removeEdge(Object from, Object to) {
Hashtable targets = sources.get(from);
if (targets == null) {
return;
}
targets.remove(to);
if (targets.size() == 0) {
sources.remove(from);
}
}
public boolean hasEdge(Object from, Object to) {
Hashtable targets = sources.get(from);
if (targets == null) {
return false;
}
return targets.containsKey(to);
}
/* return back the weight of the edge from source to target */
public int edgeWeight(Object from, Object to) {
Hashtable targets = sources.get(from);
if (targets == null) {
throw new RuntimeException("No such edge (" + from + " ," + to + ") exists.");
}
IntContainer weight = (IntContainer) targets.get(to);
if (weight == null) {
throw new RuntimeException("No such edge (" + from + ", " + to + ") exists.");
}
return weight.value;
}
/*
* If other graph is unknown, keep current one. If current graph is unknown, copy the other. And if both are not unknown,
* union each edge.
*/
public void unionSelf(WeightedDirectedSparseGraph other) {
if (other == null) {
return;
}
WeightedDirectedSparseGraph othergraph = other;
if (othergraph.isUnknown) {
return;
}
if (this.isUnknown) {
addAll(othergraph);
}
List<Object> sourceList = new ArrayList<Object>(this.sources.keySet());
Iterator<Object> firstSrcIt = sourceList.iterator();
while (firstSrcIt.hasNext()) {
Object srcKey = firstSrcIt.next();
Hashtable src1 = this.sources.get(srcKey);
Hashtable src2 = othergraph.sources.get(srcKey);
/* other is unbounded */
if (src2 == null) {
this.sources.remove(srcKey);
continue;
}
List targetList = new ArrayList(src1.keySet());
Iterator targetIt = targetList.iterator();
while (targetIt.hasNext()) {
Object target = targetIt.next();
IntContainer w1 = (IntContainer) src1.get(target);
IntContainer w2 = (IntContainer) src2.get(target);
/* other is unbounded */
if (w2 == null) {
src1.remove(target);
continue;
}
if (w2.value > w1.value) {
w1.value = w2.value;
}
}
if (src1.size() == 0) {
this.sources.remove(srcKey);
}
}
}
/*
* it was used to compare with former graph, if the edge weight is increasing, the edge is removed (unlimited distance).
*/
public void widenEdges(WeightedDirectedSparseGraph othergraph) {
WeightedDirectedSparseGraph other = othergraph;
if (other.isUnknown) {
return;
}
Hashtable<Object, Hashtable<Object, IntContainer>> othersources = other.sources;
List<Object> sourceList = new ArrayList<Object>(this.sources.keySet());
Iterator<Object> srcIt = sourceList.iterator();
while (srcIt.hasNext()) {
Object src = srcIt.next();
Hashtable thistargets = this.sources.get(src);
Hashtable othertargets = othersources.get(src);
/* the former is unbounded */
if (othertargets == null) {
this.sources.remove(src);
continue;
}
List targetList = new ArrayList(thistargets.keySet());
Iterator targetIt = targetList.iterator();
while (targetIt.hasNext()) {
Object target = targetIt.next();
IntContainer thisweight = (IntContainer) thistargets.get(target);
IntContainer otherweight = (IntContainer) othertargets.get(target);
/* the former edge is unbounded. */
if (otherweight == null) {
thistargets.remove(target);
continue;
}
if (thisweight.value > otherweight.value) {
thistargets.remove(target);
}
}
if (thistargets.size() == 0) {
this.sources.remove(src);
}
}
}
/* It is necessary to prune the graph to the shortest path. */
/* it could be replaced by a ShortestPathGraph */
/* kill a node. */
public void killNode(Object tokill) {
if (!this.vertexes.contains(tokill)) {
return;
}
this.makeShortestPathGraph();
List<Object> sourceList = new ArrayList<Object>(sources.keySet());
Iterator<Object> srcIt = sourceList.iterator();
while (srcIt.hasNext()) {
Object src = srcIt.next();
Hashtable targets = sources.get(src);
/* delete the in edge */
targets.remove(tokill);
if (targets.size() == 0) {
sources.remove(src);
}
}
sources.remove(tokill);
this.makeShortestPathGraph();
}
/* when met i=i+c, it is necessary to update the weight of in and out edges */
public void updateWeight(Object which, int c) {
/* for the in edge, the weight + c. for the out edge, the weight - c */
Iterator<Object> srcIt = sources.keySet().iterator();
while (srcIt.hasNext()) {
Object from = srcIt.next();
Hashtable targets = sources.get(from);
IntContainer weight = (IntContainer) targets.get(which);
if (weight != null) {
weight.value += c;
}
}
/* update out edges */
Hashtable toset = sources.get(which);
if (toset == null) {
return;
}
Iterator toIt = toset.keySet().iterator();
while (toIt.hasNext()) {
Object to = toIt.next();
IntContainer weight = (IntContainer) toset.get(to);
weight.value -= c;
}
}
public void clear() {
sources.clear();
}
public void replaceAllEdges(WeightedDirectedSparseGraph other) {
this.isUnknown = other.isUnknown;
this.vertexes = other.vertexes;
this.sources = other.sources;
}
/* add edges that belong to this vertex set */
public void addBoundedAll(WeightedDirectedSparseGraph another) {
this.isUnknown = another.isUnknown;
Hashtable<Object, Hashtable<Object, IntContainer>> othersources = another.sources;
Iterator thisnodeIt = this.vertexes.iterator();
while (thisnodeIt.hasNext()) {
Object src = thisnodeIt.next();
Hashtable othertargets = othersources.get(src);
if (othertargets == null) {
continue;
}
Hashtable<Object, IntContainer> thistargets = new Hashtable<Object, IntContainer>();
Iterator othertargetIt = othertargets.keySet().iterator();
while (othertargetIt.hasNext()) {
Object key = othertargetIt.next();
if (this.vertexes.contains(key)) {
IntContainer weight = (IntContainer) othertargets.get(key);
thistargets.put(key, weight.dup());
}
}
if (thistargets.size() > 0) {
this.sources.put(src, thistargets);
}
}
}
/*
* add another graph's edge and weight to this graph, it simply replace the edge weight. When used with clear, it can copy
* a graph to a new graph
*/
public void addAll(WeightedDirectedSparseGraph othergraph) {
WeightedDirectedSparseGraph another = othergraph;
this.isUnknown = another.isUnknown;
this.clear();
Hashtable<Object, Hashtable<Object, IntContainer>> othersources = another.sources;
Iterator<Object> othersrcIt = othersources.keySet().iterator();
while (othersrcIt.hasNext()) {
Object src = othersrcIt.next();
Hashtable othertargets = othersources.get(src);
Hashtable<Object, IntContainer> thistargets = new Hashtable<Object, IntContainer>(othersources.size());
this.sources.put(src, thistargets);
Iterator targetIt = othertargets.keySet().iterator();
while (targetIt.hasNext()) {
Object target = targetIt.next();
IntContainer otherweight = (IntContainer) othertargets.get(target);
thistargets.put(target, otherweight.dup());
}
}
}
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (!(other instanceof WeightedDirectedSparseGraph)) {
return false;
}
WeightedDirectedSparseGraph othergraph = (WeightedDirectedSparseGraph) other;
if (this.isUnknown != othergraph.isUnknown) {
return false;
}
if (this.isUnknown) {
return true;
}
// compare each edges. It is not always true, only when shortest path graph can be guaranteed.
Hashtable<Object, Hashtable<Object, IntContainer>> othersources = othergraph.sources;
if (this.sources.size() != othersources.size()) {
return false;
}
Iterator<Object> sourceIt = this.sources.keySet().iterator();
while (sourceIt.hasNext()) {
Object src = sourceIt.next();
Hashtable thistarget = sources.get(src);
Hashtable othertarget = othersources.get(src);
if (othertarget == null) {
return false;
}
if (thistarget.size() != othertarget.size()) {
return false;
}
Iterator targetIt = thistarget.keySet().iterator();
while (targetIt.hasNext()) {
Object target = targetIt.next();
IntContainer thisweight = (IntContainer) thistarget.get(target);
IntContainer otherweight = (IntContainer) othertarget.get(target);
if (otherweight == null) {
return false;
}
if (thisweight.value != otherweight.value) {
return false;
}
}
}
return true;
}
public String toString() {
String graphstring = "WeightedDirectedSparseGraph:\n";
graphstring = graphstring + this.vertexes + "\n";
Iterator<Object> srcIt = sources.keySet().iterator();
while (srcIt.hasNext()) {
Object src = srcIt.next();
graphstring = graphstring + src + " : ";
Hashtable targets = sources.get(src);
Iterator targetIt = targets.keySet().iterator();
while (targetIt.hasNext()) {
Object target = targetIt.next();
IntContainer weight = (IntContainer) targets.get(target);
graphstring = graphstring + target + "(" + weight.value + ") ";
}
graphstring += "\n";
}
return graphstring;
}
public WeightedDirectedSparseGraph dup() {
WeightedDirectedSparseGraph newone = new WeightedDirectedSparseGraph(this.vertexes);
newone.addAll(this);
return newone;
}
public boolean makeShortestPathGraph() {
boolean nonegcycle = true;
List<Object> srcList = new ArrayList<Object>(sources.keySet());
Iterator<Object> srcIt = srcList.iterator();
while (srcIt.hasNext()) {
Object src = srcIt.next();
if (!SSSPFinder(src)) {
nonegcycle = false;
}
}
return nonegcycle;
}
private final HashSet<Object> reachableNodes = new HashSet<Object>();
private final HashSet<WeightedDirectedEdge> reachableEdges = new HashSet<WeightedDirectedEdge>();
private final Hashtable<Object, IntContainer> distance = new Hashtable<Object, IntContainer>();
private final Hashtable<Object, Object> pei = new Hashtable<Object, Object>();
private boolean SSSPFinder(Object src) {
Hashtable<Object, IntContainer> outedges = sources.get(src);
if (outedges == null) {
return true;
}
if (outedges.size() == 0) {
return true;
}
InitializeSingleSource(src);
getReachableNodesAndEdges(src);
// relaxation
int vSize = reachableNodes.size();
for (int i = 0; i < vSize; i++) {
Iterator<WeightedDirectedEdge> edgeIt = reachableEdges.iterator();
while (edgeIt.hasNext()) {
WeightedDirectedEdge edge = edgeIt.next();
Relax(edge.from, edge.to, edge.weight);
}
}
distance.remove(src);
// check negative cycle
{
Iterator<WeightedDirectedEdge> edgeIt = reachableEdges.iterator();
while (edgeIt.hasNext()) {
WeightedDirectedEdge edge = edgeIt.next();
IntContainer dfrom = distance.get(edge.from);
if (dfrom == null) {
continue;
}
IntContainer dto = distance.get(edge.to);
if (dto == null) {
continue;
}
if (dto.value > (dfrom.value + edge.weight)) {
return false;
}
}
}
// update the graph
outedges.clear();
Iterator<Object> targetIt = distance.keySet().iterator();
while (targetIt.hasNext()) {
Object to = targetIt.next();
IntContainer dist = distance.get(to);
outedges.put(to, dist.dup());
}
return true;
}
private void InitializeSingleSource(Object src) {
reachableNodes.clear();
reachableEdges.clear();
pei.clear();
distance.clear();
distance.put(src, new IntContainer(0));
}
private void getReachableNodesAndEdges(Object src) {
LinkedList<Object> worklist = new LinkedList<Object>();
reachableNodes.add(src);
worklist.add(src);
while (!worklist.isEmpty()) {
Object from = worklist.removeFirst();
Hashtable targets = sources.get(from);
if (targets == null) {
continue;
}
Iterator targetIt = targets.keySet().iterator();
while (targetIt.hasNext()) {
Object target = targetIt.next();
if (!reachableNodes.contains(target)) {
worklist.add(target);
reachableNodes.add(target);
}
IntContainer weight = (IntContainer) targets.get(target);
reachableEdges.add(new WeightedDirectedEdge(from, target, weight.value));
}
}
}
private void Relax(Object from, Object to, int weight) {
IntContainer dfrom = distance.get(from);
IntContainer dto = distance.get(to);
if (dfrom != null) {
int vfrom = dfrom.value;
int vnew = vfrom + weight;
if (dto == null) {
distance.put(to, new IntContainer(vnew));
pei.put(to, from);
} else {
int vto = dto.value;
if (vto > vnew) {
distance.put(to, new IntContainer(vnew));
pei.put(to, from);
}
}
}
}
}
| 16,675
| 25.220126
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/callgraph/CallData.java
|
package soot.jimple.toolkits.annotation.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
public class CallData {
private final HashMap<Object, CallData> map = new HashMap<Object, CallData>();
private final ArrayList<CallData> children = new ArrayList<CallData>();
private final ArrayList<CallData> outputs = new ArrayList<CallData>();
private String data;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Data: ");
sb.append(data);
// sb.append(" Children: ");
// sb.append(children);
// sb.append(" Outputs: ");
// sb.append(outputs);
return sb.toString();
}
public void addChild(CallData cd) {
children.add(cd);
}
public void addOutput(CallData cd) {
if (!outputs.contains(cd)) {
outputs.add(cd);
}
}
public void setData(String d) {
data = d;
}
public String getData() {
return data;
}
public ArrayList<CallData> getChildren() {
return children;
}
public ArrayList<CallData> getOutputs() {
return outputs;
}
public void addToMap(Object key, CallData val) {
map.put(key, val);
}
public HashMap<Object, CallData> getMap() {
return map;
}
}
| 2,014
| 23.876543
| 80
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/callgraph/CallGraphGrapher.java
|
package soot.jimple.toolkits.annotation.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.MethodOrMethodContext;
import soot.MethodToContexts;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.jimple.Stmt;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.options.CGGOptions;
import soot.options.Options;
import soot.toolkits.graph.interaction.InteractionHandler;
/** A scene transformer that creates a graphical callgraph. */
public class CallGraphGrapher extends SceneTransformer {
private static final Logger logger = LoggerFactory.getLogger(CallGraphGrapher.class);
public CallGraphGrapher(Singletons.Global g) {
}
public static CallGraphGrapher v() {
return G.v().soot_jimple_toolkits_annotation_callgraph_CallGraphGrapher();
}
private MethodToContexts methodToContexts;
private CallGraph cg;
private boolean showLibMeths;
private ArrayList<MethInfo> getTgtMethods(SootMethod method, boolean recurse) {
// logger.debug("meth for tgts: "+method);
if (!method.hasActiveBody()) {
return new ArrayList<MethInfo>();
}
Body b = method.getActiveBody();
ArrayList<MethInfo> list = new ArrayList<MethInfo>();
Iterator sIt = b.getUnits().iterator();
while (sIt.hasNext()) {
Stmt s = (Stmt) sIt.next();
Iterator edges = cg.edgesOutOf(s);
while (edges.hasNext()) {
Edge e = (Edge) edges.next();
SootMethod sm = e.tgt();
// logger.debug("found target method: "+sm);
if (sm.getDeclaringClass().isLibraryClass()) {
if (isShowLibMeths()) {
if (recurse) {
list.add(new MethInfo(sm, hasTgtMethods(sm) | hasSrcMethods(sm), e.kind()));
} else {
list.add(new MethInfo(sm, true, e.kind()));
}
}
} else {
if (recurse) {
list.add(new MethInfo(sm, hasTgtMethods(sm) | hasSrcMethods(sm), e.kind()));
} else {
list.add(new MethInfo(sm, true, e.kind()));
}
}
}
}
return list;
}
private boolean hasTgtMethods(SootMethod meth) {
ArrayList<MethInfo> list = getTgtMethods(meth, false);
if (!list.isEmpty()) {
return true;
} else {
return false;
}
}
private boolean hasSrcMethods(SootMethod meth) {
ArrayList<MethInfo> list = getSrcMethods(meth, false);
if (list.size() > 1) {
return true;
} else {
return false;
}
}
private ArrayList<MethInfo> getSrcMethods(SootMethod method, boolean recurse) {
// logger.debug("meth for srcs: "+method);
ArrayList<MethInfo> list = new ArrayList<MethInfo>();
for (Iterator momcIt = methodToContexts.get(method).iterator(); momcIt.hasNext();) {
final MethodOrMethodContext momc = (MethodOrMethodContext) momcIt.next();
Iterator callerEdges = cg.edgesInto(momc);
while (callerEdges.hasNext()) {
Edge callEdge = (Edge) callerEdges.next();
SootMethod methodCaller = callEdge.src();
if (methodCaller.getDeclaringClass().isLibraryClass()) {
if (isShowLibMeths()) {
if (recurse) {
list.add(
new MethInfo(methodCaller, hasTgtMethods(methodCaller) | hasSrcMethods(methodCaller), callEdge.kind()));
} else {
list.add(new MethInfo(methodCaller, true, callEdge.kind()));
}
}
} else {
if (recurse) {
list.add(new MethInfo(methodCaller, hasTgtMethods(methodCaller) | hasSrcMethods(methodCaller), callEdge.kind()));
} else {
list.add(new MethInfo(methodCaller, true, callEdge.kind()));
}
}
}
}
return list;
}
protected void internalTransform(String phaseName, Map options) {
CGGOptions opts = new CGGOptions(options);
if (opts.show_lib_meths()) {
setShowLibMeths(true);
}
cg = Scene.v().getCallGraph();
if (Options.v().interactive_mode()) {
reset();
}
}
public void reset() {
if (methodToContexts == null) {
methodToContexts = new MethodToContexts(Scene.v().getReachableMethods().listener());
}
if (Scene.v().hasCallGraph()) {
SootClass sc = Scene.v().getMainClass();
SootMethod sm = getFirstMethod(sc);
// logger.debug("got first method");
ArrayList<MethInfo> tgts = getTgtMethods(sm, true);
// logger.debug("got tgt methods");
ArrayList<MethInfo> srcs = getSrcMethods(sm, true);
// logger.debug("got src methods");
CallGraphInfo info = new CallGraphInfo(sm, tgts, srcs);
// logger.debug("will handle new call graph");
InteractionHandler.v().handleCallGraphStart(info, this);
}
}
private SootMethod getFirstMethod(SootClass sc) {
ArrayList paramTypes = new ArrayList();
paramTypes.add(soot.ArrayType.v(soot.RefType.v("java.lang.String"), 1));
SootMethod sm = sc.getMethodUnsafe("main", paramTypes, soot.VoidType.v());
if (sm != null) {
return sm;
} else {
return (SootMethod) sc.getMethods().get(0);
}
}
public void handleNextMethod() {
if (!getNextMethod().hasActiveBody()) {
return;
}
ArrayList<MethInfo> tgts = getTgtMethods(getNextMethod(), true);
// System.out.println("for: "+getNextMethod().getName()+" tgts: "+tgts);
ArrayList<MethInfo> srcs = getSrcMethods(getNextMethod(), true);
// System.out.println("for: "+getNextMethod().getName()+" srcs: "+srcs);
CallGraphInfo info = new CallGraphInfo(getNextMethod(), tgts, srcs);
// System.out.println("sending next method");
InteractionHandler.v().handleCallGraphPart(info);
// handleNextMethod();
}
private SootMethod nextMethod;
public void setNextMethod(SootMethod m) {
nextMethod = m;
}
public SootMethod getNextMethod() {
return nextMethod;
}
public void setShowLibMeths(boolean b) {
showLibMeths = b;
}
public boolean isShowLibMeths() {
return showLibMeths;
}
}
| 7,050
| 30.618834
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/callgraph/CallGraphInfo.java
|
package soot.jimple.toolkits.annotation.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import soot.SootMethod;
public class CallGraphInfo {
private ArrayList<MethInfo> inputs = new ArrayList<MethInfo>();
private ArrayList<MethInfo> outputs = new ArrayList<MethInfo>();
private SootMethod center;
public CallGraphInfo(SootMethod sm, ArrayList<MethInfo> outputs, ArrayList<MethInfo> inputs) {
setCenter(sm);
setOutputs(outputs);
setInputs(inputs);
}
public void setCenter(SootMethod sm) {
center = sm;
}
public SootMethod getCenter() {
return center;
}
public ArrayList<MethInfo> getInputs() {
return inputs;
}
public void setInputs(ArrayList<MethInfo> list) {
inputs = list;
}
public ArrayList<MethInfo> getOutputs() {
return outputs;
}
public void setOutputs(ArrayList<MethInfo> list) {
outputs = list;
}
}
| 1,681
| 24.484848
| 96
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.