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/toolkits/thread/synchronization/CriticalSectionGroup.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import soot.Value;
import soot.jimple.toolkits.pointer.CodeBlockRWSet;
import soot.jimple.toolkits.pointer.RWSet;
class CriticalSectionGroup implements Iterable<CriticalSection> {
int groupNum;
// Information about the group members
List<CriticalSection> criticalSections;
// Group read/write set
RWSet rwSet;
// Information about the selected lock(s)
public boolean isDynamicLock; // is lockObject actually dynamic? or is it a static ref?
public boolean useDynamicLock; // use one dynamic lock per tn
public Value lockObject;
public boolean useLocksets;
public CriticalSectionGroup(int groupNum) {
this.groupNum = groupNum;
this.criticalSections = new ArrayList<CriticalSection>();
this.rwSet = new CodeBlockRWSet();
this.isDynamicLock = false;
this.useDynamicLock = false;
this.lockObject = null;
this.useLocksets = false;
}
public int num() {
return groupNum;
}
public int size() {
return criticalSections.size();
}
public void add(CriticalSection tn) {
tn.setNumber = groupNum;
tn.group = this;
if (!criticalSections.contains(tn)) {
criticalSections.add(tn);
}
}
public boolean contains(CriticalSection tn) {
return criticalSections.contains(tn);
}
public Iterator<CriticalSection> iterator() {
return criticalSections.iterator();
}
public void mergeGroups(CriticalSectionGroup other) {
if (other == this) {
return;
}
Iterator<CriticalSection> tnIt = other.criticalSections.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = tnIt.next();
add(tn);
}
other.criticalSections.clear();
}
}
| 2,616
| 26.260417
| 89
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/CriticalSectionInterferenceGraph.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import soot.Hierarchy;
import soot.Local;
import soot.PointsToAnalysis;
import soot.RefLikeType;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.jimple.toolkits.pointer.CodeBlockRWSet;
import soot.jimple.toolkits.thread.mhp.MhpTester;
public class CriticalSectionInterferenceGraph {
int nextGroup;
List<CriticalSectionGroup> groups;
List<CriticalSection> criticalSections;
MhpTester mhp;
PointsToAnalysis pta;
boolean optionOneGlobalLock = false;
boolean optionLeaveOriginalLocks = false;
boolean optionIncludeEmptyPossibleEdges = false;
public CriticalSectionInterferenceGraph(List<CriticalSection> criticalSections, MhpTester mhp, boolean optionOneGlobalLock,
boolean optionLeaveOriginalLocks, boolean optionIncludeEmptyPossibleEdges) {
this.criticalSections = criticalSections;
this.mhp = mhp;
this.pta = Scene.v().getPointsToAnalysis();
this.optionOneGlobalLock = optionOneGlobalLock;
this.optionLeaveOriginalLocks = optionLeaveOriginalLocks;
this.optionIncludeEmptyPossibleEdges = optionIncludeEmptyPossibleEdges;
calculateGroups();
}
public int groupCount() {
return nextGroup;
}
public List<CriticalSectionGroup> groups() {
return groups;
}
public void calculateGroups() {
nextGroup = 1;
groups = new ArrayList<CriticalSectionGroup>();
groups.add(new CriticalSectionGroup(0)); // dummy group
if (optionOneGlobalLock) // use one group for all transactions
{
CriticalSectionGroup onlyGroup = new CriticalSectionGroup(nextGroup);
Iterator<CriticalSection> tnIt1 = criticalSections.iterator();
while (tnIt1.hasNext()) {
CriticalSection tn1 = tnIt1.next();
onlyGroup.add(tn1);
}
nextGroup++;
groups.add(onlyGroup);
} else // calculate separate groups for transactions
{
Iterator<CriticalSection> tnIt1 = criticalSections.iterator();
while (tnIt1.hasNext()) {
CriticalSection tn1 = tnIt1.next();
// if this transaction has somehow already been marked for deletion
if (tn1.setNumber == -1) {
continue;
}
// if this transaction is empty
if (tn1.read.size() == 0 && tn1.write.size() == 0 && !optionLeaveOriginalLocks) {
// this transaction has no effect except on locals... we don't need it!
tn1.setNumber = -1; // AKA delete the transactional region (but don't really so long as we are using
// the synchronized keyword in our language... because java guarantees memory
// barriers at certain points in synchronized blocks)
} else {
Iterator<CriticalSection> tnIt2 = criticalSections.iterator();
while (tnIt2.hasNext()) {
CriticalSection tn2 = tnIt2.next();
// check if this transactional region is going to be deleted
if (tn2.setNumber == -1) {
continue;
}
// check if they're already marked as having an interference
// NOTE: this results in a sound grouping, but a badly
// incomplete dependency graph. If the dependency
// graph is to be analyzed, we cannot do this
// if(tn1.setNumber > 0 && tn1.setNumber == tn2.setNumber)
// continue;
// check if these two transactions can't ever be in parallel
if (!mayHappenInParallel(tn1, tn2)) {
continue;
}
// check for RW or WW data dependencies.
// or, for optionLeaveOriginalLocks, check type compatibility
SootClass classOne = null;
SootClass classTwo = null;
boolean typeCompatible = false;
boolean emptyEdge = false;
if (tn1.origLock != null && tn2.origLock != null) {
// Check if edge is empty
if (tn1.origLock == null || tn2.origLock == null) {
emptyEdge = true;
} else if (!(tn1.origLock instanceof Local) || !(tn2.origLock instanceof Local)) {
emptyEdge = !tn1.origLock.equals(tn2.origLock);
} else {
emptyEdge = !pta.reachingObjects((Local) tn1.origLock)
.hasNonEmptyIntersection(pta.reachingObjects((Local) tn2.origLock));
}
// Check if types are compatible
RefLikeType typeOne = (RefLikeType) tn1.origLock.getType();
RefLikeType typeTwo = (RefLikeType) tn2.origLock.getType();
classOne = (typeOne instanceof RefType) ? ((RefType) typeOne).getSootClass() : null;
classTwo = (typeTwo instanceof RefType) ? ((RefType) typeTwo).getSootClass() : null;
if (classOne != null && classTwo != null) {
Hierarchy h = Scene.v().getActiveHierarchy();
if (classOne.isInterface()) {
if (classTwo.isInterface()) {
typeCompatible = h.getSubinterfacesOfIncluding(classOne).contains(classTwo)
|| h.getSubinterfacesOfIncluding(classTwo).contains(classOne);
} else {
typeCompatible = h.getImplementersOf(classOne).contains(classTwo);
}
} else {
if (classTwo.isInterface()) {
typeCompatible = h.getImplementersOf(classTwo).contains(classOne);
} else {
typeCompatible = (classOne != null
&& Scene.v().getActiveHierarchy().getSubclassesOfIncluding(classOne).contains(classTwo)
|| classTwo != null
&& Scene.v().getActiveHierarchy().getSubclassesOfIncluding(classTwo).contains(classOne));
}
}
}
}
if ((!optionLeaveOriginalLocks && (tn1.write.hasNonEmptyIntersection(tn2.write)
|| tn1.write.hasNonEmptyIntersection(tn2.read) || tn1.read.hasNonEmptyIntersection(tn2.write)))
|| (optionLeaveOriginalLocks && typeCompatible && (optionIncludeEmptyPossibleEdges || !emptyEdge))) {
// Determine the size of the intersection for GraphViz output
CodeBlockRWSet rw = null;
int size;
if (optionLeaveOriginalLocks) {
rw = new CodeBlockRWSet();
size = emptyEdge ? 0 : 1;
} else {
rw = tn1.write.intersection(tn2.write);
rw.union(tn1.write.intersection(tn2.read));
rw.union(tn1.read.intersection(tn2.write));
size = rw.size();
}
// Record this
tn1.edges.add(new CriticalSectionDataDependency(tn2, size, rw));
// Don't add opposite... all n^2 pairs will be visited separately
if (size > 0) {
// if tn1 already is in a group
if (tn1.setNumber > 0) {
// if tn2 is NOT already in a group
if (tn2.setNumber == 0) {
tn1.group.add(tn2);
}
// if tn2 is already in a group
else if (tn2.setNumber > 0) {
if (tn1.setNumber != tn2.setNumber) // if they are equal, then they are already in the same group!
{
tn1.group.mergeGroups(tn2.group);
}
}
}
// if tn1 is NOT already in a group
else if (tn1.setNumber == 0) {
// if tn2 is NOT already in a group
if (tn2.setNumber == 0) {
CriticalSectionGroup newGroup = new CriticalSectionGroup(nextGroup);
newGroup.add(tn1);
newGroup.add(tn2);
groups.add(newGroup);
nextGroup++;
}
// if tn2 is already in a group
else if (tn2.setNumber > 0) {
tn2.group.add(tn1);
}
}
}
}
}
// If, after comparing to all other transactions, we have no group:
if (tn1.setNumber == 0) {
tn1.setNumber = -1; // delete transactional region
}
}
}
}
}
public boolean mayHappenInParallel(CriticalSection tn1, CriticalSection tn2) {
if (mhp == null) {
if (optionLeaveOriginalLocks) {
return true;
}
ReachableMethods rm = Scene.v().getReachableMethods();
if (!rm.contains(tn1.method) || !rm.contains(tn2.method)) {
return false;
}
return true;
}
return mhp.mayHappenInParallel(tn1.method, tn2.method);
}
}
| 9,814
| 39.061224
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/CriticalSectionVisibleEdgesPred.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%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.Collection;
import java.util.Iterator;
import soot.jimple.toolkits.callgraph.Edge;
import soot.jimple.toolkits.callgraph.EdgePredicate;
/**
* A predicate that accepts edges that are not part of the class library and do not have a source statement that falls inside
* a transaction.
*
* @author Richard L. Halpert
*/
public class CriticalSectionVisibleEdgesPred implements EdgePredicate {
Collection<CriticalSection> tns;
CriticalSection exemptTn;
public CriticalSectionVisibleEdgesPred(Collection<CriticalSection> tns) {
this.tns = tns;
}
public void setExemptTransaction(CriticalSection exemptTn) {
this.exemptTn = exemptTn;
}
/** Returns true iff the edge e is wanted. */
public boolean want(Edge e) {
String tgtMethod = e.tgt().toString();
String tgtClass = e.tgt().getDeclaringClass().toString();
String srcMethod = e.src().toString();
String srcClass = e.src().getDeclaringClass().toString();
// Remove Deep Library Calls
if (tgtClass.startsWith("sun.")) {
return false;
}
if (tgtClass.startsWith("com.sun.")) {
return false;
}
// Remove static initializers
if (tgtMethod.endsWith("void <clinit>()>")) {
return false;
}
// Remove calls to equals in the library
if ((tgtClass.startsWith("java.") || tgtClass.startsWith("javax."))
&& e.tgt().toString().endsWith("boolean equals(java.lang.Object)>")) {
return false;
}
// Remove anything in java.util
// these calls will be treated as a non-transitive RW to the receiving object
if (tgtClass.startsWith("java.util") || srcClass.startsWith("java.util")) {
return false;
}
// Remove anything in java.lang
// these calls will be treated as a non-transitive RW to the receiving object
if (tgtClass.startsWith("java.lang") || srcClass.startsWith("java.lang")) {
return false;
}
if (tgtClass.startsWith("java")) {
return false; // filter out the rest!
}
if (e.tgt().isSynchronized()) {
return false;
}
// I THINK THIS CHUNK IS JUST NOT NEEDED... TODO: REMOVE IT
// Remove Calls from within a transaction
// one transaction is exempt - so that we may analyze calls within it
if (tns != null) {
Iterator<CriticalSection> tnIt = tns.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = tnIt.next();
if (tn != exemptTn && tn.units.contains(e.srcStmt())) // if this method call originates inside a transaction...
{
return false; // ignore it
}
}
}
return true;
}
}
| 3,473
| 30.017857
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/DeadlockAvoidanceEdge.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%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.SootClass;
public class DeadlockAvoidanceEdge extends NewStaticLock {
public DeadlockAvoidanceEdge(SootClass sc) {
super(sc);
}
/** Clones the object. */
public Object clone() {
return new DeadlockAvoidanceEdge(sc);
}
public boolean equals(Object c) {
if (c instanceof DeadlockAvoidanceEdge) {
return ((DeadlockAvoidanceEdge) c).idnum == idnum;
}
return false;
}
public String toString() {
return "dae<" + sc.toString() + ">";
}
}
| 1,368
| 26.938776
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/DeadlockDetector.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.EquivalentValue;
import soot.MethodOrMethodContext;
import soot.Scene;
import soot.Unit;
import soot.Value;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.sets.HashPointsToSet;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.Filter;
import soot.jimple.toolkits.callgraph.TransitiveTargets;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.HashMutableDirectedGraph;
import soot.toolkits.graph.HashMutableEdgeLabelledDirectedGraph;
import soot.toolkits.graph.MutableDirectedGraph;
import soot.toolkits.graph.MutableEdgeLabelledDirectedGraph;
public class DeadlockDetector {
private static final Logger logger = LoggerFactory.getLogger(DeadlockDetector.class);
boolean optionPrintDebug;
boolean optionRepairDeadlock;
boolean optionAllowSelfEdges;
List<CriticalSection> criticalSections;
TransitiveTargets tt;
public DeadlockDetector(boolean optionPrintDebug, boolean optionRepairDeadlock, boolean optionAllowSelfEdges,
List<CriticalSection> criticalSections) {
this.optionPrintDebug = optionPrintDebug;
this.optionRepairDeadlock = optionRepairDeadlock;
this.optionAllowSelfEdges = optionAllowSelfEdges && !optionRepairDeadlock; // can only do this if not repairing
this.criticalSections = criticalSections;
this.tt = new TransitiveTargets(Scene.v().getCallGraph(), new Filter(new CriticalSectionVisibleEdgesPred(null)));
}
public MutableDirectedGraph<CriticalSectionGroup> detectComponentBasedDeadlock() {
MutableDirectedGraph<CriticalSectionGroup> lockOrder;
boolean foundDeadlock;
int iteration = 0;
do {
iteration++;
logger.debug("[DeadlockDetector] Deadlock Iteration #" + iteration);
foundDeadlock = false;
lockOrder = new HashMutableDirectedGraph<CriticalSectionGroup>(); // start each iteration with a fresh graph
// Assemble the partial ordering of locks
Iterator<CriticalSection> deadlockIt1 = criticalSections.iterator();
while (deadlockIt1.hasNext() && !foundDeadlock) {
CriticalSection tn1 = deadlockIt1.next();
// skip if unlocked
if (tn1.setNumber <= 0) {
continue;
}
// add a node for this set
if (!lockOrder.containsNode(tn1.group)) {
lockOrder.addNode(tn1.group);
}
// Get list of tn1's target methods
if (tn1.transitiveTargets == null) {
tn1.transitiveTargets = new HashSet<MethodOrMethodContext>();
for (Unit tn1Invoke : tn1.invokes) {
Iterator<MethodOrMethodContext> targetIt = tt.iterator(tn1Invoke);
while (targetIt.hasNext()) {
tn1.transitiveTargets.add(targetIt.next());
}
}
}
// compare to each other tn
Iterator<CriticalSection> deadlockIt2 = criticalSections.iterator();
while (deadlockIt2.hasNext() && (!optionRepairDeadlock || !foundDeadlock)) {
CriticalSection tn2 = deadlockIt2.next();
// skip if unlocked or in same set as tn1
if (tn2.setNumber <= 0 || (tn2.setNumber == tn1.setNumber && !optionAllowSelfEdges)) // this is wrong... dynamic
// locks in same group can be
// diff locks
{
continue;
}
// add a node for this set
if (!lockOrder.containsNode(tn2.group)) {
lockOrder.addNode(tn2.group);
}
if (tn1.transitiveTargets.contains(tn2.method)) {
// This implies the partial ordering tn1lock before tn2lock
if (optionPrintDebug) {
logger.debug("group" + (tn1.setNumber) + " before group" + (tn2.setNumber) + ": " + "outer: " + tn1.name
+ " inner: " + tn2.name);
}
// Check if tn2lock before tn1lock is in our lock order
List<CriticalSectionGroup> afterTn2 = new ArrayList<CriticalSectionGroup>();
afterTn2.addAll(lockOrder.getSuccsOf(tn2.group));
for (int i = 0; i < afterTn2.size(); i++) {
for (CriticalSectionGroup o : lockOrder.getSuccsOf(afterTn2.get(i))) {
if (!afterTn2.contains(o)) {
afterTn2.add(o);
}
}
}
if (afterTn2.contains(tn1.group)) {
if (!optionRepairDeadlock) {
logger.debug("[DeadlockDetector] DEADLOCK HAS BEEN DETECTED: not correcting");
foundDeadlock = true;
} else {
logger.debug("[DeadlockDetector] DEADLOCK HAS BEEN DETECTED: merging group" + (tn1.setNumber) + " and group"
+ (tn2.setNumber) + " and restarting deadlock detection");
if (optionPrintDebug) {
logger.debug("tn1.setNumber was " + tn1.setNumber + " and tn2.setNumber was " + tn2.setNumber);
logger.debug("tn1.group.size was " + tn1.group.criticalSections.size() + " and tn2.group.size was "
+ tn2.group.criticalSections.size());
logger.debug("tn1.group.num was " + tn1.group.num() + " and tn2.group.num was " + tn2.group.num());
}
tn1.group.mergeGroups(tn2.group);
if (optionPrintDebug) {
logger.debug("tn1.setNumber is " + tn1.setNumber + " and tn2.setNumber is " + tn2.setNumber);
logger.debug("tn1.group.size is " + tn1.group.criticalSections.size() + " and tn2.group.size is "
+ tn2.group.criticalSections.size());
}
foundDeadlock = true;
}
}
lockOrder.addEdge(tn1.group, tn2.group);
}
}
}
} while (foundDeadlock && optionRepairDeadlock);
return lockOrder;
}
public MutableEdgeLabelledDirectedGraph<Integer, CriticalSection> detectLocksetDeadlock(Map<Value, Integer> lockToLockNum,
List<PointsToSetInternal> lockPTSets) {
HashMutableEdgeLabelledDirectedGraph<Integer, CriticalSection> permanentOrder
= new HashMutableEdgeLabelledDirectedGraph<Integer, CriticalSection>();
MutableEdgeLabelledDirectedGraph<Integer, CriticalSection> lockOrder;
boolean foundDeadlock;
int iteration = 0;
do {
iteration++;
logger.debug("[DeadlockDetector] Deadlock Iteration #" + iteration);
foundDeadlock = false;
lockOrder = permanentOrder.clone(); // start each iteration with a fresh copy of the permanent orders
// Assemble the partial ordering of locks
Iterator<CriticalSection> deadlockIt1 = criticalSections.iterator();
while (deadlockIt1.hasNext() && !foundDeadlock) {
CriticalSection tn1 = deadlockIt1.next();
// skip if unlocked
if (tn1.group == null) {
continue;
}
// add a node for each lock in this lockset
for (EquivalentValue lockEqVal : tn1.lockset) {
Value lock = lockEqVal.getValue();
if (!lockOrder.containsNode(lockToLockNum.get(lock))) {
lockOrder.addNode(lockToLockNum.get(lock));
}
}
// Get list of tn1's target methods
if (tn1.transitiveTargets == null) {
tn1.transitiveTargets = new HashSet<MethodOrMethodContext>();
for (Unit tn1Invoke : tn1.invokes) {
Iterator<MethodOrMethodContext> targetIt = tt.iterator(tn1Invoke);
while (targetIt.hasNext()) {
tn1.transitiveTargets.add(targetIt.next());
}
}
}
// compare to each other tn
Iterator<CriticalSection> deadlockIt2 = criticalSections.iterator();
while (deadlockIt2.hasNext() && !foundDeadlock) {
CriticalSection tn2 = deadlockIt2.next();
// skip if unlocked
if (tn2.group == null) {
continue;
}
// add a node for each lock in this lockset
for (EquivalentValue lockEqVal : tn2.lockset) {
Value lock = lockEqVal.getValue();
if (!lockOrder.containsNode(lockToLockNum.get(lock))) {
lockOrder.addNode(lockToLockNum.get(lock));
}
}
if (tn1.transitiveTargets.contains(tn2.method) && !foundDeadlock) {
// This implies the partial ordering (locks in tn1) before (locks in tn2)
if (true) // optionPrintDebug)
{
logger.debug("[DeadlockDetector] locks in " + (tn1.name) + " before locks in " + (tn2.name) + ": " + "outer: "
+ tn1.name + " inner: " + tn2.name);
}
// Check if tn2locks before tn1locks is in our lock order
for (EquivalentValue lock2EqVal : tn2.lockset) {
Value lock2 = lock2EqVal.getValue();
Integer lock2Num = lockToLockNum.get(lock2);
List<Integer> afterTn2 = new ArrayList<Integer>();
afterTn2.addAll(lockOrder.getSuccsOf(lock2Num)); // filter here!
ListIterator<Integer> lit = afterTn2.listIterator();
while (lit.hasNext()) {
Integer to = lit.next(); // node the edges go to
List<CriticalSection> labels = lockOrder.getLabelsForEdges(lock2Num, to);
boolean keep = false;
if (labels != null) // this shouldn't really happen... is something wrong with the edge-labelled graph?
{
for (CriticalSection labelTn : labels) {
// Check if labelTn and tn1 share a static lock
boolean tnsShareAStaticLock = false;
for (EquivalentValue tn1LockEqVal : tn1.lockset) {
Integer tn1LockNum = lockToLockNum.get(tn1LockEqVal.getValue());
if (tn1LockNum < 0) {
// this is a static lock... see if some lock in labelTn has the same #
for (EquivalentValue labelTnLockEqVal : labelTn.lockset) {
if (Objects.equals(lockToLockNum.get(labelTnLockEqVal.getValue()), tn1LockNum)) {
tnsShareAStaticLock = true;
}
}
}
}
if (!tnsShareAStaticLock) // !hasStaticLockInCommon(tn1, labelTn))
{
keep = true;
break;
}
}
}
if (!keep) {
lit.remove();
}
}
/*
* for (int i = 0; i < afterTn2.size(); i++) { List<Integer> succs = lockOrder.getSuccsOf(afterTn2.get(i)); //
* but not here for (Integer o : succs) { if (!afterTn2.contains(o)) { afterTn2.add(o); } } }
*/
for (EquivalentValue lock1EqVal : tn1.lockset) {
Value lock1 = lock1EqVal.getValue();
Integer lock1Num = lockToLockNum.get(lock1);
if ((!Objects.equals(lock1Num, lock2Num) || lock1Num > 0) && afterTn2.contains(lock1Num)) {
if (!optionRepairDeadlock) {
logger.debug("[DeadlockDetector] DEADLOCK HAS BEEN DETECTED: not correcting");
foundDeadlock = true;
} else {
logger.debug("[DeadlockDetector] DEADLOCK HAS BEEN DETECTED while inspecting " + lock1Num + " (" + lock1
+ ") and " + lock2Num + " (" + lock2 + ") ");
// Create a deadlock avoidance edge
DeadlockAvoidanceEdge dae = new DeadlockAvoidanceEdge(tn1.method.getDeclaringClass());
EquivalentValue daeEqVal = new EquivalentValue(dae);
// Register it as a static lock
Integer daeNum = -lockPTSets.size(); // negative indicates a static lock
permanentOrder.addNode(daeNum);
lockToLockNum.put(dae, daeNum);
PointsToSetInternal dummyLockPT
= new HashPointsToSet(lock1.getType(), (PAG) Scene.v().getPointsToAnalysis());
lockPTSets.add(dummyLockPT);
// Add it to the locksets of tn1 and whoever says l2 before l1
for (EquivalentValue lockEqVal : tn1.lockset) {
Integer lockNum = lockToLockNum.get(lockEqVal.getValue());
if (!permanentOrder.containsNode(lockNum)) {
permanentOrder.addNode(lockNum);
}
permanentOrder.addEdge(daeNum, lockNum, tn1);
}
tn1.lockset.add(daeEqVal);
List<CriticalSection> forwardLabels = lockOrder.getLabelsForEdges(lock1Num, lock2Num);
if (forwardLabels != null) {
for (CriticalSection tn : forwardLabels) {
if (!tn.lockset.contains(daeEqVal)) {
for (EquivalentValue lockEqVal : tn.lockset) {
Integer lockNum = lockToLockNum.get(lockEqVal.getValue());
if (!permanentOrder.containsNode(lockNum)) {
permanentOrder.addNode(lockNum);
}
permanentOrder.addEdge(daeNum, lockNum, tn);
}
tn.lockset.add(daeEqVal);
}
}
}
List<CriticalSection> backwardLabels = lockOrder.getLabelsForEdges(lock2Num, lock1Num);
if (backwardLabels != null) {
for (CriticalSection tn : backwardLabels) {
if (!tn.lockset.contains(daeEqVal)) {
for (EquivalentValue lockEqVal : tn.lockset) {
Integer lockNum = lockToLockNum.get(lockEqVal.getValue());
if (!permanentOrder.containsNode(lockNum)) {
permanentOrder.addNode(lockNum);
}
permanentOrder.addEdge(daeNum, lockNum, tn);
}
tn.lockset.add(daeEqVal);
logger.debug("[DeadlockDetector] Adding deadlock avoidance edge between " + (tn1.name) + " and "
+ (tn.name));
}
}
logger.debug("[DeadlockDetector] Restarting deadlock detection");
}
foundDeadlock = true;
break;
}
}
if (!Objects.equals(lock1Num, lock2Num)) {
lockOrder.addEdge(lock1Num, lock2Num, tn1);
}
}
if (foundDeadlock) {
break;
}
}
}
}
}
} while (foundDeadlock && optionRepairDeadlock);
return lockOrder;
}
public void reorderLocksets(Map<Value, Integer> lockToLockNum,
MutableEdgeLabelledDirectedGraph<Integer, CriticalSection> lockOrder) {
for (CriticalSection tn : criticalSections) {
// Get the portion of the lock order that is visible to tn
HashMutableDirectedGraph<Integer> visibleOrder = new HashMutableDirectedGraph<Integer>();
if (tn.group != null) {
for (CriticalSection otherTn : criticalSections) {
// Check if otherTn and tn share a static lock
boolean tnsShareAStaticLock = false;
for (EquivalentValue tnLockEqVal : tn.lockset) {
Integer tnLockNum = lockToLockNum.get(tnLockEqVal.getValue());
if (tnLockNum < 0) {
// this is a static lock... see if some lock in labelTn has the same #
if (otherTn.group != null) {
for (EquivalentValue otherTnLockEqVal : otherTn.lockset) {
if (Objects.equals(lockToLockNum.get(otherTnLockEqVal.getValue()), tnLockNum)) {
tnsShareAStaticLock = true;
}
}
} else {
tnsShareAStaticLock = true; // not really... but we want to skip this one
}
}
}
if (!tnsShareAStaticLock || tn == otherTn) // if tns don't share any static lock, or if tns are the same one
{
// add these orderings to tn's visible order
DirectedGraph<Integer> orderings = lockOrder.getEdgesForLabel(otherTn);
for (Integer node1 : orderings) {
if (!visibleOrder.containsNode(node1)) {
visibleOrder.addNode(node1);
}
for (Integer node2 : orderings.getSuccsOf(node1)) {
if (!visibleOrder.containsNode(node2)) {
visibleOrder.addNode(node2);
}
visibleOrder.addEdge(node1, node2);
}
}
}
}
logger.debug("VISIBLE ORDER FOR " + tn.name);
visibleOrder.printGraph();
// Order locks in tn's lockset according to the visible order (insertion sort)
List<EquivalentValue> newLockset = new ArrayList<EquivalentValue>();
for (EquivalentValue lockEqVal : tn.lockset) {
Value lockToInsert = lockEqVal.getValue();
Integer lockNumToInsert = lockToLockNum.get(lockToInsert);
int i = 0;
while (i < newLockset.size()) {
EquivalentValue existingLockEqVal = newLockset.get(i);
Value existingLock = existingLockEqVal.getValue();
Integer existingLockNum = lockToLockNum.get(existingLock);
if (visibleOrder.containsEdge(lockNumToInsert, existingLockNum) || lockNumToInsert < existingLockNum)
// !visibleOrder.containsEdge(existingLockNum,
// lockNumToInsert)
// ) //
// if(!
// existing
// before
// toinsert
// )
{
break;
}
i++;
}
newLockset.add(i, lockEqVal);
}
logger.debug("reordered from " + LockAllocator.locksetToLockNumString(tn.lockset, lockToLockNum) + " to "
+ LockAllocator.locksetToLockNumString(newLockset, lockToLockNum));
tn.lockset = newLockset;
}
}
}
}
| 19,860
| 42.364629
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/LockAllocationBodyTransformer.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.EquivalentValue;
import soot.Local;
import soot.Modifier;
import soot.PatchingChain;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Trap;
import soot.Unit;
import soot.Value;
import soot.VoidType;
import soot.jimple.ArrayRef;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.Ref;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.toolkits.infoflow.FakeJimpleLocal;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.Pair;
import soot.util.Chain;
public class LockAllocationBodyTransformer extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(LockAllocationBodyTransformer.class);
private static final LockAllocationBodyTransformer instance = new LockAllocationBodyTransformer();
private LockAllocationBodyTransformer() {
}
public static LockAllocationBodyTransformer v() {
return instance;
}
private static boolean addedGlobalLockDefs = false;
private static int throwableNum = 0; // doesn't matter if not reinitialized
// to 0
protected void internalTransform(Body b, String phase, Map opts) {
throw new RuntimeException("Not Supported");
}
protected void internalTransform(Body b, FlowSet fs, List<CriticalSectionGroup> groups, boolean[] insertedGlobalLock) {
//
JimpleBody j = (JimpleBody) b;
SootMethod thisMethod = b.getMethod();
PatchingChain<Unit> units = b.getUnits();
Iterator<Unit> unitIt = units.iterator();
Unit firstUnit = j.getFirstNonIdentityStmt();
Unit lastUnit = units.getLast();
// Objects of synchronization, plus book keeping
Local[] lockObj = new Local[groups.size()];
boolean[] addedLocalLockObj = new boolean[groups.size()];
SootField[] globalLockObj = new SootField[groups.size()];
for (int i = 1; i < groups.size(); i++) {
lockObj[i] = Jimple.v().newLocal("lockObj" + i, RefType.v("java.lang.Object"));
addedLocalLockObj[i] = false;
globalLockObj[i] = null;
}
// Add all global lock objects to the main class if not yet added.
// Get references to them if they do already exist.
for (int i = 1; i < groups.size(); i++) {
CriticalSectionGroup tnGroup = groups.get(i);
if (!tnGroup.useDynamicLock && !tnGroup.useLocksets) {
if (!insertedGlobalLock[i]) {
// Add globalLockObj field if possible...
// Avoid name collision... if it's already there, then just
// use it!
try {
globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i);
// field already exists
} catch (RuntimeException re) {
// field does not yet exist (or, as a pre-existing
// error, there is more than one field by this name)
globalLockObj[i] = Scene.v().makeSootField("globalLockObj" + i, RefType.v("java.lang.Object"),
Modifier.STATIC | Modifier.PUBLIC);
Scene.v().getMainClass().addField(globalLockObj[i]);
}
insertedGlobalLock[i] = true;
} else {
globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i);
}
}
}
// If the current method is the clinit method of the main class, for
// each global lock object,
// add a local lock object and assign it a new object. Copy the new
// local lock object into the global lock object for use by other fns.
if (!addedGlobalLockDefs)// thisMethod.getSubSignature().equals("void
// <clinit>()") &&
// thisMethod.getDeclaringClass() ==
// Scene.v().getMainClass())
{
// Either get or add the <clinit> method to the main class
SootClass mainClass = Scene.v().getMainClass();
SootMethod clinitMethod = null;
JimpleBody clinitBody = null;
Stmt firstStmt = null;
boolean addingNewClinit = !mainClass.declaresMethod("void <clinit>()");
if (addingNewClinit) {
clinitMethod
= Scene.v().makeSootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC);
clinitBody = Jimple.v().newBody(clinitMethod);
clinitMethod.setActiveBody(clinitBody);
mainClass.addMethod(clinitMethod);
} else {
clinitMethod = mainClass.getMethod("void <clinit>()");
clinitBody = (JimpleBody) clinitMethod.getActiveBody();
firstStmt = clinitBody.getFirstNonIdentityStmt();
}
PatchingChain<Unit> clinitUnits = clinitBody.getUnits();
for (int i = 1; i < groups.size(); i++) {
CriticalSectionGroup tnGroup = groups.get(i);
// if( useGlobalLock[i - 1] )
if (!tnGroup.useDynamicLock && !tnGroup.useLocksets) {
// add local lock obj
// addedLocalLockObj[i] = true;
clinitBody.getLocals().add(lockObj[i]); // TODO: add name
// conflict
// avoidance code
// assign new object to lock obj
Stmt newStmt = Jimple.v().newAssignStmt(lockObj[i], Jimple.v().newNewExpr(RefType.v("java.lang.Object")));
if (addingNewClinit) {
clinitUnits.add(newStmt);
} else {
clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt);
}
// initialize new object
SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object");
RefType type = RefType.v(objectClass);
SootMethod initMethod = objectClass.getMethod("void <init>()");
Stmt initStmt = Jimple.v()
.newInvokeStmt(Jimple.v().newSpecialInvokeExpr(lockObj[i], initMethod.makeRef(), Collections.EMPTY_LIST));
if (addingNewClinit) {
clinitUnits.add(initStmt);
} else {
clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt);
}
// copy new object to global static lock object (for use by
// other fns)
Stmt assignStmt = Jimple.v().newAssignStmt(Jimple.v().newStaticFieldRef(globalLockObj[i].makeRef()), lockObj[i]);
if (addingNewClinit) {
clinitUnits.add(assignStmt);
} else {
clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt);
}
}
}
if (addingNewClinit) {
clinitUnits.add(Jimple.v().newReturnVoidStmt());
}
addedGlobalLockDefs = true;
}
int tempNum = 1;
// Iterate through all of the transactions in the current method
Iterator fsIt = fs.iterator();
Stmt newPrep = null;
while (fsIt.hasNext()) {
CriticalSection tn = ((SynchronizedRegionFlowPair) fsIt.next()).tn;
if (tn.setNumber == -1) {
continue; // this tn should be deleted... for now just skip it!
}
if (tn.wholeMethod) {
thisMethod.setModifiers(thisMethod.getModifiers() & ~(Modifier.SYNCHRONIZED)); // remove
// synchronized
// modifier
// for
// this
// method
}
Local clo = null; // depends on type of locking
SynchronizedRegion csr = null; // current synchronized region
int lockNum = 0;
boolean moreLocks = true;
while (moreLocks) {
// If this method does not yet have a reference to the lock
// object
// needed for this transaction, then create one.
if (tn.group.useDynamicLock) {
Value lock = getLockFor((EquivalentValue) tn.lockObject); // adds
// local
// vars
// and
// global
// objects
// if
// needed
if (lock instanceof Ref) {
if (lock instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) lock;
if (ifr.getBase() instanceof FakeJimpleLocal) {
lock = reconstruct(b, units, ifr, (tn.entermonitor != null ? tn.entermonitor : tn.beginning),
(tn.entermonitor != null));
}
}
if (!b.getLocals().contains(lockObj[tn.setNumber])) {
b.getLocals().add(lockObj[tn.setNumber]);
}
newPrep = Jimple.v().newAssignStmt(lockObj[tn.setNumber], lock);
if (tn.wholeMethod) {
units.insertBeforeNoRedirect(newPrep, firstUnit);
} else {
units.insertBefore(newPrep, tn.entermonitor);
}
clo = lockObj[tn.setNumber];
} else if (lock instanceof Local) {
clo = (Local) lock;
} else {
throw new RuntimeException("Unknown type of lock (" + lock + "): expected Ref or Local");
}
csr = tn;
moreLocks = false;
} else if (tn.group.useLocksets) {
Value lock = getLockFor((EquivalentValue) tn.lockset.get(lockNum)); // adds
// local
// vars
// and
// global
// objects
// if
// needed
if (lock instanceof FieldRef) {
if (lock instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) lock;
if (ifr.getBase() instanceof FakeJimpleLocal) {
lock = reconstruct(b, units, ifr, (tn.entermonitor != null ? tn.entermonitor : tn.beginning),
(tn.entermonitor != null));
}
}
// add a local variable for this lock
Local lockLocal = Jimple.v().newLocal("locksetObj" + tempNum, RefType.v("java.lang.Object"));
tempNum++;
b.getLocals().add(lockLocal);
// make it refer to the right lock object
newPrep = Jimple.v().newAssignStmt(lockLocal, lock);
if (tn.entermonitor != null) {
units.insertBefore(newPrep, tn.entermonitor);
} else {
units.insertBeforeNoRedirect(newPrep, tn.beginning);
}
// use it as the lock
clo = lockLocal;
} else if (lock instanceof Local) {
clo = (Local) lock;
} else {
throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local");
}
if (lockNum + 1 >= tn.lockset.size()) {
moreLocks = false;
} else {
moreLocks = true;
}
if (lockNum > 0) {
SynchronizedRegion nsr = new SynchronizedRegion();
nsr.beginning = csr.beginning;
for (Pair earlyEnd : csr.earlyEnds) {
Stmt earlyExitmonitor = (Stmt) earlyEnd.getO2();
nsr.earlyEnds.add(new Pair(earlyExitmonitor, null)); // <early
// exitmonitor,
// null>
}
nsr.last = csr.last; // last stmt before exception
// handling
if (csr.end != null) {
Stmt endExitmonitor = csr.end.getO2();
nsr.after = endExitmonitor;
}
csr = nsr;
} else {
csr = tn;
}
} else // global lock
{
if (!addedLocalLockObj[tn.setNumber]) {
b.getLocals().add(lockObj[tn.setNumber]);
}
addedLocalLockObj[tn.setNumber] = true;
newPrep = Jimple.v().newAssignStmt(lockObj[tn.setNumber],
Jimple.v().newStaticFieldRef(globalLockObj[tn.setNumber].makeRef()));
if (tn.wholeMethod) {
units.insertBeforeNoRedirect(newPrep, firstUnit);
} else {
units.insertBefore(newPrep, tn.entermonitor);
}
clo = lockObj[tn.setNumber];
csr = tn;
moreLocks = false;
}
// Add synchronization code
// For transactions from synchronized methods, use
// synchronizeSingleEntrySingleExitBlock()
// to add all necessary code (including ugly exception handling)
// For transactions from synchronized blocks, simply replace the
// monitorenter/monitorexit statements with new ones
if (true) {
// Remove old prep stmt
if (csr.prepStmt != null) {
// units.remove(clr.prepStmt); // seems to trigger bugs
// in code generation?
}
// Reuse old entermonitor or insert new one, and insert prep
Stmt newEntermonitor = Jimple.v().newEnterMonitorStmt(clo);
if (csr.entermonitor != null) {
units.insertBefore(newEntermonitor, csr.entermonitor);
// redirectTraps(b, clr.entermonitor, newEntermonitor);
// // EXPERIMENTAL
units.remove(csr.entermonitor);
csr.entermonitor = newEntermonitor;
// units.insertBefore(newEntermonitor, newPrep); //
// already inserted
// clr.prepStmt = newPrep;
} else {
units.insertBeforeNoRedirect(newEntermonitor, csr.beginning);
csr.entermonitor = newEntermonitor;
// units.insertBefore(newEntermonitor, newPrep); //
// already inserted
// clr.prepStmt = newPrep;
}
// For each early end, reuse or insert exitmonitor stmt
List<Pair<Stmt, Stmt>> newEarlyEnds = new ArrayList<Pair<Stmt, Stmt>>();
for (Pair<Stmt, Stmt> end : csr.earlyEnds) {
Stmt earlyEnd = end.getO1();
Stmt exitmonitor = end.getO2();
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if (exitmonitor != null) {
if (newPrep != null) {
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, exitmonitor); // seems
// to
// avoid
// code
// generation
// bugs?
}
units.insertBefore(newExitmonitor, exitmonitor);
// redirectTraps(b, exitmonitor, newExitmonitor); //
// EXPERIMENTAL
units.remove(exitmonitor);
newEarlyEnds.add(new Pair<Stmt, Stmt>(earlyEnd, newExitmonitor));
} else {
if (newPrep != null) {
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, earlyEnd);
}
units.insertBefore(newExitmonitor, earlyEnd);
newEarlyEnds.add(new Pair<Stmt, Stmt>(earlyEnd, newExitmonitor));
}
}
csr.earlyEnds = newEarlyEnds;
// If fallthrough end, reuse or insert goto and exit
if (csr.after != null) {
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if (csr.end != null) {
Stmt exitmonitor = csr.end.getO2();
if (newPrep != null) {
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, exitmonitor);
}
units.insertBefore(newExitmonitor, exitmonitor);
// redirectTraps(b, exitmonitor, newExitmonitor); //
// EXPERIMENTAL
units.remove(exitmonitor);
csr.end = new Pair<Stmt, Stmt>(csr.end.getO1(), newExitmonitor);
} else {
if (newPrep != null) {
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, csr.after);
}
units.insertBefore(newExitmonitor, csr.after); // steal
// jumps
// to
// end,
// send
// them
// to
// monitorexit
Stmt newGotoStmt = Jimple.v().newGotoStmt(csr.after);
units.insertBeforeNoRedirect(newGotoStmt, csr.after);
csr.end = new Pair<Stmt, Stmt>(newGotoStmt, newExitmonitor);
csr.last = newGotoStmt;
}
}
// If exceptional end, reuse it, else insert it and traps
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if (csr.exceptionalEnd != null) {
Stmt exitmonitor = csr.exceptionalEnd.getO2();
if (newPrep != null) {
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, exitmonitor);
}
units.insertBefore(newExitmonitor, exitmonitor);
units.remove(exitmonitor);
csr.exceptionalEnd = new Pair<Stmt, Stmt>(csr.exceptionalEnd.getO1(), newExitmonitor);
} else {
// insert after the last end
Stmt lastEnd = null; // last end stmt (not same as last
// stmt)
if (csr.end != null) {
lastEnd = csr.end.getO1();
} else {
for (Pair earlyEnd : csr.earlyEnds) {
Stmt end = (Stmt) earlyEnd.getO1();
if (lastEnd == null || (units.contains(lastEnd) && units.contains(end) && units.follows(end, lastEnd))) {
lastEnd = end;
}
}
}
if (csr.last == null) {
csr.last = lastEnd; // last stmt and last end are
}
// the same
if (lastEnd == null) {
throw new RuntimeException("Lock Region has no ends! Where should we put the exception handling???");
}
// Add throwable
Local throwableLocal
= Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable"));
b.getLocals().add(throwableLocal);
// Add stmts
Stmt newCatch = Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef());
if (csr.last == null) {
throw new RuntimeException("WHY IS clr.last NULL???");
}
if (newCatch == null) {
throw new RuntimeException("WHY IS newCatch NULL???");
}
units.insertAfter(newCatch, csr.last);
units.insertAfter(newExitmonitor, newCatch);
Stmt newThrow = Jimple.v().newThrowStmt(throwableLocal);
units.insertAfter(newThrow, newExitmonitor);
// Add traps
SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable");
b.getTraps().addFirst(Jimple.v().newTrap(throwableClass, newExitmonitor, newThrow, newCatch));
b.getTraps().addFirst(Jimple.v().newTrap(throwableClass, csr.beginning, lastEnd, newCatch));
csr.exceptionalEnd = new Pair<Stmt, Stmt>(newThrow, newExitmonitor);
}
}
lockNum++;
}
// deal with waits and notifys
{
for (Unit uNotify : tn.notifys) {
Stmt sNotify = (Stmt) uNotify;
Stmt newNotify = Jimple.v()
.newInvokeStmt(Jimple.v().newVirtualInvokeExpr(clo,
sNotify.getInvokeExpr().getMethodRef().declaringClass().getMethod("void notifyAll()").makeRef(),
Collections.EMPTY_LIST));
if (newPrep != null) {
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, sNotify);
units.insertBefore(newNotify, tmp);
} else {
units.insertBefore(newNotify, sNotify);
}
redirectTraps(b, sNotify, newNotify);
units.remove(sNotify);
}
// Replace base object of calls to wait with appropriate lockobj
for (Unit uWait : tn.waits) {
Stmt sWait = (Stmt) uWait;
((InstanceInvokeExpr) sWait.getInvokeExpr()).setBase(clo); // WHAT
// IF
// THIS
// IS
// THE
// WRONG
// LOCK
// IN
// A
// PAIR
// OF
// NESTED
// LOCKS???
if (newPrep != null) {
units.insertBefore((Stmt) newPrep.clone(), sWait);
}
}
}
}
}
static int baseLocalNum = 0;
public InstanceFieldRef reconstruct(Body b, PatchingChain<Unit> units, InstanceFieldRef lock, Stmt insertBefore,
boolean redirect) {
logger.debug("Reconstructing " + lock);
if (!(lock.getBase() instanceof FakeJimpleLocal)) {
logger.debug(" base is not a FakeJimpleLocal");
return lock;
}
FakeJimpleLocal fakeBase = (FakeJimpleLocal) lock.getBase();
if (!(fakeBase.getInfo() instanceof LockableReferenceAnalysis)) {
throw new RuntimeException("InstanceFieldRef cannot be reconstructed due to missing LocksetAnalysis info: " + lock);
}
LockableReferenceAnalysis la = (LockableReferenceAnalysis) fakeBase.getInfo();
EquivalentValue baseEqVal = la.baseFor(lock);
if (baseEqVal == null) {
throw new RuntimeException("InstanceFieldRef cannot be reconstructed due to lost base from Lockset");
}
Value base = baseEqVal.getValue();
Local baseLocal;
if (base instanceof InstanceFieldRef) {
Value newBase = reconstruct(b, units, (InstanceFieldRef) base, insertBefore, redirect);
baseLocal = Jimple.v().newLocal("baseLocal" + (baseLocalNum++), newBase.getType());
b.getLocals().add(baseLocal);
// make it equal to the right value
Stmt baseAssign = Jimple.v().newAssignStmt(baseLocal, newBase);
if (redirect == true) {
units.insertBefore(baseAssign, insertBefore);
} else {
units.insertBeforeNoRedirect(baseAssign, insertBefore);
}
} else if (base instanceof Local) {
baseLocal = (Local) base;
} else {
throw new RuntimeException("InstanceFieldRef cannot be reconstructed because it's base is of an unsupported type"
+ base.getType() + ": " + base);
}
InstanceFieldRef newLock = Jimple.v().newInstanceFieldRef(baseLocal, lock.getField().makeRef());
logger.debug(" as " + newLock);
return newLock;
}
static int lockNumber = 0;
static Map<EquivalentValue, StaticFieldRef> lockEqValToLock = new HashMap<EquivalentValue, StaticFieldRef>();
static public Value getLockFor(EquivalentValue lockEqVal) {
Value lock = lockEqVal.getValue();
if (lock instanceof InstanceFieldRef) {
return lock;
}
if (lock instanceof ArrayRef) {
// ref for each value of the index!
return ((ArrayRef) lock).getBase();
}
if (lock instanceof Local) {
return lock;
}
if (lock instanceof StaticFieldRef || lock instanceof NewStaticLock) {
if (lockEqValToLock.containsKey(lockEqVal)) {
return lockEqValToLock.get(lockEqVal);
}
SootClass lockClass = null;
if (lock instanceof StaticFieldRef) {
StaticFieldRef sfrLock = (StaticFieldRef) lock;
lockClass = sfrLock.getField().getDeclaringClass();
} else if (lock instanceof NewStaticLock) {
DeadlockAvoidanceEdge dae = (DeadlockAvoidanceEdge) lock;
lockClass = dae.getLockClass();
}
SootMethod clinitMethod = null;
JimpleBody clinitBody = null;
Stmt firstStmt = null;
boolean addingNewClinit = !lockClass.declaresMethod("void <clinit>()");
if (addingNewClinit) {
clinitMethod
= Scene.v().makeSootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC);
clinitBody = Jimple.v().newBody(clinitMethod);
clinitMethod.setActiveBody(clinitBody);
lockClass.addMethod(clinitMethod);
} else {
clinitMethod = lockClass.getMethod("void <clinit>()");
clinitBody = (JimpleBody) clinitMethod.getActiveBody();
firstStmt = clinitBody.getFirstNonIdentityStmt();
}
PatchingChain<Unit> clinitUnits = clinitBody.getUnits();
Local lockLocal = Jimple.v().newLocal("objectLockLocal" + lockNumber, RefType.v("java.lang.Object"));
// lockNumber is increased below
clinitBody.getLocals().add(lockLocal); // TODO: add name conflict
// avoidance code
// assign new object to lock obj
Stmt newStmt = Jimple.v().newAssignStmt(lockLocal, Jimple.v().newNewExpr(RefType.v("java.lang.Object")));
if (addingNewClinit) {
clinitUnits.add(newStmt);
} else {
clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt);
}
// initialize new object
SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object");
RefType type = RefType.v(objectClass);
SootMethod initMethod = objectClass.getMethod("void <init>()");
Stmt initStmt = Jimple.v()
.newInvokeStmt(Jimple.v().newSpecialInvokeExpr(lockLocal, initMethod.makeRef(), Collections.EMPTY_LIST));
if (addingNewClinit) {
clinitUnits.add(initStmt);
} else {
clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt);
}
// copy new object to global static lock object (for use by other
// fns)
SootField actualLockObject = Scene.v().makeSootField("objectLockGlobal" + lockNumber, RefType.v("java.lang.Object"),
Modifier.STATIC | Modifier.PUBLIC);
lockNumber++;
lockClass.addField(actualLockObject);
StaticFieldRef actualLockSfr = Jimple.v().newStaticFieldRef(actualLockObject.makeRef());
Stmt assignStmt = Jimple.v().newAssignStmt(actualLockSfr, lockLocal);
if (addingNewClinit) {
clinitUnits.add(assignStmt);
} else {
clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt);
}
if (addingNewClinit) {
clinitUnits.add(Jimple.v().newReturnVoidStmt());
}
lockEqValToLock.put(lockEqVal, actualLockSfr);
return actualLockSfr;
}
throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef, ArrayRef, or Local");
}
public void redirectTraps(Body b, Unit oldUnit, Unit newUnit) {
Chain<Trap> traps = b.getTraps();
for (Trap trap : traps) {
if (trap.getHandlerUnit() == oldUnit) {
trap.setHandlerUnit(newUnit);
}
if (trap.getBeginUnit() == oldUnit) {
trap.setBeginUnit(newUnit);
}
if (trap.getEndUnit() == oldUnit) {
trap.setEndUnit(newUnit);
}
}
}
}
| 27,320
| 36.998609
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/LockAllocator.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.EquivalentValue;
import soot.G;
import soot.Local;
import soot.PhaseOptions;
import soot.PointsToAnalysis;
import soot.RefType;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.Ref;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.sets.HashPointsToSet;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.jimple.toolkits.infoflow.ClassInfoFlowAnalysis;
import soot.jimple.toolkits.infoflow.FakeJimpleLocal;
import soot.jimple.toolkits.infoflow.SmartMethodInfoFlowAnalysis;
import soot.jimple.toolkits.pointer.RWSet;
import soot.jimple.toolkits.thread.ThreadLocalObjectsAnalysis;
import soot.jimple.toolkits.thread.mhp.MhpTester;
import soot.jimple.toolkits.thread.mhp.SynchObliviousMhpAnalysis;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.HashMutableEdgeLabelledDirectedGraph;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.LocalDefs;
import soot.util.Chain;
public class LockAllocator extends SceneTransformer {
private static final Logger logger = LoggerFactory.getLogger(LockAllocator.class);
public LockAllocator(Singletons.Global g) {
}
public static LockAllocator v() {
return G.v().soot_jimple_toolkits_thread_synchronization_LockAllocator();
}
List<CriticalSection> criticalSections = null;
CriticalSectionInterferenceGraph interferenceGraph = null;
DirectedGraph deadlockGraph = null;
// Lock options
boolean optionOneGlobalLock = false;
boolean optionStaticLocks = false;
boolean optionUseLocksets = false;
boolean optionLeaveOriginalLocks = false;
boolean optionIncludeEmptyPossibleEdges = false;
// Semantic options
boolean optionAvoidDeadlock = true;
boolean optionOpenNesting = true;
// Analysis options
boolean optionDoMHP = false;
boolean optionDoTLO = false;
boolean optionOnFlyTLO = false; // not a CLI option yet // on-fly is more efficient, but harder to measure in time
// Output options
boolean optionPrintMhpSummary = true; // not a CLI option yet
boolean optionPrintGraph = false;
boolean optionPrintTable = false;
boolean optionPrintDebug = false;
protected void internalTransform(String phaseName, Map<String, String> options) {
// Get phase options
String lockingScheme = PhaseOptions.getString(options, "locking-scheme");
if (lockingScheme.equals("fine-grained")) {
optionOneGlobalLock = false;
optionStaticLocks = false;
optionUseLocksets = true;
optionLeaveOriginalLocks = false;
}
// if(lockingScheme.equals("fine-static"))
// {
// optionOneGlobalLock = false;
// optionStaticLocks = true;
// optionUseLocksets = true;
// optionLeaveOriginalLocks = false;
// }
if (lockingScheme.equals("medium-grained")) // rename to coarse-grained
{
optionOneGlobalLock = false;
optionStaticLocks = false;
optionUseLocksets = false;
optionLeaveOriginalLocks = false;
}
if (lockingScheme.equals("coarse-grained")) // rename to coarse-static
{
optionOneGlobalLock = false;
optionStaticLocks = true;
optionUseLocksets = false;
optionLeaveOriginalLocks = false;
}
if (lockingScheme.equals("single-static")) {
optionOneGlobalLock = true;
optionStaticLocks = true;
optionUseLocksets = false;
optionLeaveOriginalLocks = false;
}
if (lockingScheme.equals("leave-original")) {
optionOneGlobalLock = false;
optionStaticLocks = false;
optionUseLocksets = false;
optionLeaveOriginalLocks = true;
}
optionAvoidDeadlock = PhaseOptions.getBoolean(options, "avoid-deadlock");
optionOpenNesting = PhaseOptions.getBoolean(options, "open-nesting");
optionDoMHP = PhaseOptions.getBoolean(options, "do-mhp");
optionDoTLO = PhaseOptions.getBoolean(options, "do-tlo");
// optionOnFlyTLO = PhaseOptions.getBoolean( options, "on-fly-tlo" ); // not a real option yet
// optionPrintMhpSummary = PhaseOptions.getBoolean( options, "print-mhp" ); // not a real option yet
optionPrintGraph = PhaseOptions.getBoolean(options, "print-graph");
optionPrintTable = PhaseOptions.getBoolean(options, "print-table");
optionPrintDebug = PhaseOptions.getBoolean(options, "print-debug");
// optionIncludeEmptyPossibleEdges = PhaseOptions.getBoolean( options, "include-empty-edges" ); // not a real option yet
// *** Build May Happen In Parallel Info ***
MhpTester mhp = null;
if (optionDoMHP && Scene.v().getPointsToAnalysis() instanceof PAG) {
logger.debug("[wjtp.tn] *** Build May-Happen-in-Parallel Info *** " + (new Date()));
mhp = new SynchObliviousMhpAnalysis();
if (optionPrintMhpSummary) {
mhp.printMhpSummary();
}
}
// *** Find Thread-Local Objects ***
ThreadLocalObjectsAnalysis tlo = null;
if (optionDoTLO) {
logger.debug("[wjtp.tn] *** Find Thread-Local Objects *** " + (new Date()));
if (mhp != null) {
tlo = new ThreadLocalObjectsAnalysis(mhp);
} else {
tlo = new ThreadLocalObjectsAnalysis(new SynchObliviousMhpAnalysis());
}
if (!optionOnFlyTLO) {
tlo.precompute();
logger.debug("[wjtp.tn] TLO totals (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/"
+ ClassInfoFlowAnalysis.methodCount);
} else {
logger.debug("[wjtp.tn] TLO so far (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/"
+ ClassInfoFlowAnalysis.methodCount);
}
}
// *** Find and Name Transactions ***
// The transaction finder finds the start, end, and preparatory statements
// for each transaction. It also calculates the non-transitive read/write
// sets for each transaction.
// For all methods, run the intraprocedural analysis (TransactionAnalysis)
Date start = new Date();
logger.debug("[wjtp.tn] *** Find and Name Transactions *** " + start);
Map<SootMethod, FlowSet> methodToFlowSet = new HashMap<SootMethod, FlowSet>();
Map<SootMethod, ExceptionalUnitGraph> methodToExcUnitGraph = new HashMap<SootMethod, ExceptionalUnitGraph>();
Iterator<SootClass> runAnalysisClassesIt = Scene.v().getApplicationClasses().iterator();
while (runAnalysisClassesIt.hasNext()) {
SootClass appClass = runAnalysisClassesIt.next();
Iterator<SootMethod> methodsIt = appClass.getMethods().iterator();
while (methodsIt.hasNext()) {
SootMethod method = methodsIt.next();
if (method.isConcrete()) {
Body b = method.retrieveActiveBody();
ExceptionalUnitGraph eug = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b);
methodToExcUnitGraph.put(method, eug);
// run the intraprocedural analysis
SynchronizedRegionFinder ta = new SynchronizedRegionFinder(eug, b, optionPrintDebug, optionOpenNesting, tlo);
Chain<Unit> units = b.getUnits();
Unit lastUnit = units.getLast();
FlowSet fs = (FlowSet) ta.getFlowBefore(lastUnit);
// add the results to the list of results
methodToFlowSet.put(method, fs);
}
}
}
// Create a composite list of all transactions
criticalSections = new Vector<CriticalSection>();
for (FlowSet fs : methodToFlowSet.values()) {
List fList = fs.toList();
for (int i = 0; i < fList.size(); i++) {
criticalSections.add(((SynchronizedRegionFlowPair) fList.get(i)).tn);
}
}
// Assign Names To Transactions
assignNamesToTransactions(criticalSections);
if (optionOnFlyTLO) {
logger.debug("[wjtp.tn] TLO so far (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/"
+ ClassInfoFlowAnalysis.methodCount);
}
// *** Find Transitive Read/Write Sets ***
// Finds the transitive read/write set for each transaction using a given
// nesting model.
logger.debug("[wjtp.tn] *** Find Transitive Read/Write Sets *** " + (new Date()));
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
CriticalSectionAwareSideEffectAnalysis tasea = null;
tasea = new CriticalSectionAwareSideEffectAnalysis(pta, Scene.v().getCallGraph(),
(optionOpenNesting ? criticalSections : null), tlo);
Iterator<CriticalSection> tnIt = criticalSections.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = tnIt.next();
for (Unit unit : tn.invokes) {
Stmt stmt = (Stmt) unit;
HashSet uses = new HashSet();
RWSet stmtRead = tasea.readSet(tn.method, stmt, tn, uses);
if (stmtRead != null) {
tn.read.union(stmtRead);
}
RWSet stmtWrite = tasea.writeSet(tn.method, stmt, tn, uses);
if (stmtWrite != null) {
tn.write.union(stmtWrite);
}
}
}
long longTime = ((new Date()).getTime() - start.getTime()) / 100;
float time = ((float) longTime) / 10.0f;
if (optionOnFlyTLO) {
logger.debug("[wjtp.tn] TLO totals (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/"
+ ClassInfoFlowAnalysis.methodCount);
logger.debug("[wjtp.tn] Time for stages utilizing on-fly TLO: " + time + "s");
}
// *** Find Stray Reads/Writes *** (DISABLED)
// add external data races as one-line transactions
// note that finding them isn't that hard (though it is time consuming)
// For all methods, run the intraprocedural analysis (transaction finder)
// Note that these will only be transformed if they are either added to
// methodToFlowSet or if a loop and new body transformer are used for methodToStrayRWSet
/*
* Map methodToStrayRWSet = new HashMap(); Iterator runRWFinderClassesIt = Scene.v().getApplicationClasses().iterator();
* while (runRWFinderClassesIt.hasNext()) { SootClass appClass = (SootClass) runRWFinderClassesIt.next(); Iterator
* methodsIt = appClass.getMethods().iterator(); while (methodsIt.hasNext()) { SootMethod method = (SootMethod)
* methodsIt.next(); Body b = method.retrieveActiveBody(); UnitGraph g = (UnitGraph) methodToExcUnitGraph.get(method);
*
* // run the interprocedural analysis // PTFindStrayRW ptfrw = new PTFindStrayRW(new ExceptionalUnitGraph(b), b,
* AllTransactions); PTFindStrayRW ptfrw = new PTFindStrayRW(g, b, AllTransactions); Chain units = b.getUnits(); Unit
* firstUnit = (Unit) units.iterator().next(); FlowSet fs = (FlowSet) ptfrw.getFlowBefore(firstUnit);
*
* // add the results to the list of results methodToStrayRWSet.put(method, fs); } } //
*/
// *** Calculate Locking Groups ***
// Search for data dependencies between transactions, and split them into disjoint sets
logger.debug("[wjtp.tn] *** Calculate Locking Groups *** " + (new Date()));
CriticalSectionInterferenceGraph ig = new CriticalSectionInterferenceGraph(criticalSections, mhp, optionOneGlobalLock,
optionLeaveOriginalLocks, optionIncludeEmptyPossibleEdges);
interferenceGraph = ig; // save in field for later retrieval
// *** Detect the Possibility of Deadlock ***
logger.debug("[wjtp.tn] *** Detect the Possibility of Deadlock *** " + (new Date()));
DeadlockDetector dd = new DeadlockDetector(optionPrintDebug, optionAvoidDeadlock, true, criticalSections);
if (!optionUseLocksets) {
deadlockGraph = dd.detectComponentBasedDeadlock();
}
// *** Calculate Locking Objects ***
// Get a list of all dependencies for each group
logger.debug("[wjtp.tn] *** Calculate Locking Objects *** " + (new Date()));
if (!optionStaticLocks) {
// Calculate per-group contributing RWSet
// (Might be preferable to use per-transaction contributing RWSet)
for (CriticalSection tn : criticalSections) {
if (tn.setNumber <= 0) {
continue;
}
for (CriticalSectionDataDependency tdd : tn.edges) {
tn.group.rwSet.union(tdd.rw);
}
}
}
// Inspect each group's RW dependencies to determine if there's a possibility
// of a shared lock object (if all dependencies are fields/localobjs of the same object)
Map<Value, Integer> lockToLockNum = null;
List<PointsToSetInternal> lockPTSets = null;
if (optionLeaveOriginalLocks) {
analyzeExistingLocks(criticalSections, ig);
} else if (optionStaticLocks) {
setFlagsForStaticAllocations(ig);
} else // for locksets and dynamic locks
{
setFlagsForDynamicAllocations(ig);
// Data structures for determining lock numbers
lockPTSets = new ArrayList<PointsToSetInternal>();
lockToLockNum = new HashMap<Value, Integer>();
findLockableReferences(criticalSections, pta, tasea, lockToLockNum, lockPTSets);
// print out locksets
if (optionUseLocksets) {
for (CriticalSection tn : criticalSections) {
if (tn.group != null) {
logger.debug("[wjtp.tn] " + tn.name + " lockset: " + locksetToLockNumString(tn.lockset, lockToLockNum)
+ (tn.group.useLocksets ? "" : " (placeholder)"));
}
}
}
}
// *** Detect the Possibility of Deadlock for Locksets ***
if (optionUseLocksets) // deadlock detection and lock ordering for lockset allocations
{
logger.debug("[wjtp.tn] *** Detect " + (optionAvoidDeadlock ? "and Correct " : "")
+ "the Possibility of Deadlock for Locksets *** " + (new Date()));
deadlockGraph = dd.detectLocksetDeadlock(lockToLockNum, lockPTSets);
if (optionPrintDebug) {
((HashMutableEdgeLabelledDirectedGraph) deadlockGraph).printGraph();
}
logger.debug("[wjtp.tn] *** Reorder Locksets to Avoid Deadlock *** " + (new Date()));
dd.reorderLocksets(lockToLockNum, (HashMutableEdgeLabelledDirectedGraph) deadlockGraph);
}
// *** Print Output and Transform Program ***
logger.debug("[wjtp.tn] *** Print Output and Transform Program *** " + (new Date()));
// Print topological graph in graphviz format
if (optionPrintGraph) {
printGraph(criticalSections, ig, lockToLockNum);
}
// Print table of transaction information
if (optionPrintTable) {
printTable(criticalSections, mhp);
printGroups(criticalSections, ig);
}
// For all methods, run the lock transformer
if (!optionLeaveOriginalLocks) {
// Create an array of booleans to keep track of which global locks have been inserted into the program
boolean[] insertedGlobalLock = new boolean[ig.groupCount()];
insertedGlobalLock[0] = false;
for (int i = 1; i < ig.groupCount(); i++) {
CriticalSectionGroup tnGroup = ig.groups().get(i);
insertedGlobalLock[i] = (!optionOneGlobalLock) && (tnGroup.useDynamicLock || tnGroup.useLocksets);
}
for (SootClass appClass : Scene.v().getApplicationClasses()) {
for (SootMethod method : appClass.getMethods()) {
if (method.isConcrete()) {
FlowSet fs = methodToFlowSet.get(method);
if (fs != null) {
LockAllocationBodyTransformer.v().internalTransform(method.getActiveBody(), fs, ig.groups(),
insertedGlobalLock);
}
}
}
}
}
}
protected void findLockableReferences(List<CriticalSection> AllTransactions, PointsToAnalysis pta,
CriticalSectionAwareSideEffectAnalysis tasea, Map<Value, Integer> lockToLockNum,
List<PointsToSetInternal> lockPTSets) {
// For each transaction, if the group's R/Ws may be fields of the same object,
// then check for the transaction if they must be fields of the same RUNTIME OBJECT
Iterator<CriticalSection> tnIt9 = AllTransactions.iterator();
while (tnIt9.hasNext()) {
CriticalSection tn = tnIt9.next();
int group = tn.setNumber - 1;
if (group < 0) {
continue;
}
if (tn.group.useDynamicLock || tn.group.useLocksets) // if attempting to use a dynamic lock or locksets
{
// Get list of objects (FieldRef or Local) to be locked (lockset analysis)
logger.debug("[wjtp.tn] * " + tn.name + " *");
LockableReferenceAnalysis la = new LockableReferenceAnalysis(new BriefUnitGraph(tn.method.retrieveActiveBody()));
tn.lockset = la.getLocksetOf(tasea, tn.group.rwSet, tn);
// Determine if list is suitable for the selected locking scheme
// TODO check for nullness
if (optionUseLocksets) {
// Post-process the locksets
if (tn.lockset == null || tn.lockset.size() <= 0) {
// If the lockset is invalid, revert the entire group to static locks:
tn.group.useLocksets = false;
// Create a lockset containing a single placeholder static lock for each tn in the group
Value newStaticLock = new NewStaticLock(tn.method.getDeclaringClass());
EquivalentValue newStaticLockEqVal = new EquivalentValue(newStaticLock);
for (CriticalSection groupTn : tn.group) {
groupTn.lockset = new ArrayList<EquivalentValue>();
groupTn.lockset.add(newStaticLockEqVal);
}
// Assign a lock number to the placeholder
Integer lockNum = new Integer(-lockPTSets.size()); // negative indicates a static lock
logger.debug("[wjtp.tn] Lock: num " + lockNum + " type " + newStaticLock.getType() + " obj " + newStaticLock);
lockToLockNum.put(newStaticLockEqVal, lockNum);
lockToLockNum.put(newStaticLock, lockNum);
PointsToSetInternal dummyLockPT = new HashPointsToSet(newStaticLock.getType(), (PAG) pta); // KILLS CHA-BASED
// ANALYSIS (pointer
// exception)
lockPTSets.add(dummyLockPT);
} else {
// If the lockset is valid
// Assign a lock number for each lock in the lockset
for (EquivalentValue lockEqVal : tn.lockset) {
Value lock = lockEqVal.getValue();
// Get reaching objects for this lock
PointsToSetInternal lockPT;
if (lock instanceof Local) {
lockPT = (PointsToSetInternal) pta.reachingObjects((Local) lock);
} else if (lock instanceof StaticFieldRef) {
lockPT = null;
} else if (lock instanceof InstanceFieldRef) {
Local base = (Local) ((InstanceFieldRef) lock).getBase();
if (base instanceof FakeJimpleLocal) {
lockPT = (PointsToSetInternal) pta.reachingObjects(((FakeJimpleLocal) base).getRealLocal(),
((FieldRef) lock).getField());
} else {
lockPT = (PointsToSetInternal) pta.reachingObjects(base, ((FieldRef) lock).getField());
}
} else if (lock instanceof NewStaticLock) {
lockPT = null;
} else {
lockPT = null;
}
if (lockPT != null) {
// Assign an existing lock number if possible
boolean foundLock = false;
for (int i = 0; i < lockPTSets.size(); i++) {
PointsToSetInternal otherLockPT = lockPTSets.get(i);
if (lockPT.hasNonEmptyIntersection(otherLockPT)) // will never happen for empty, negative numbered sets
{
logger.debug("[wjtp.tn] Lock: num " + i + " type " + lock.getType() + " obj " + lock);
lockToLockNum.put(lock, new Integer(i));
otherLockPT.addAll(lockPT, null);
foundLock = true;
break;
}
}
// Assign a brand new lock number otherwise
if (!foundLock) {
logger.debug("[wjtp.tn] Lock: num " + lockPTSets.size() + " type " + lock.getType() + " obj " + lock);
lockToLockNum.put(lock, new Integer(lockPTSets.size()));
PointsToSetInternal otherLockPT = new HashPointsToSet(lockPT.getType(), (PAG) pta);
lockPTSets.add(otherLockPT);
otherLockPT.addAll(lockPT, null);
}
} else // static field locks and pathological cases...
{
// Assign an existing lock number if possible
if (lockToLockNum.get(lockEqVal) != null) {
Integer lockNum = lockToLockNum.get(lockEqVal);
logger.debug("[wjtp.tn] Lock: num " + lockNum + " type " + lock.getType() + " obj " + lock);
lockToLockNum.put(lock, lockNum);
} else {
Integer lockNum = new Integer(-lockPTSets.size()); // negative indicates a static lock
logger.debug("[wjtp.tn] Lock: num " + lockNum + " type " + lock.getType() + " obj " + lock);
lockToLockNum.put(lockEqVal, lockNum);
lockToLockNum.put(lock, lockNum);
PointsToSetInternal dummyLockPT = new HashPointsToSet(lock.getType(), (PAG) pta);
lockPTSets.add(dummyLockPT);
}
}
}
}
} else {
if (tn.lockset == null || tn.lockset.size() != 1) { // Found too few or too many locks
// So use a static lock instead
tn.lockObject = null;
tn.group.useDynamicLock = false;
tn.group.lockObject = null;
} else { // Found exactly one lock
// Use it!
tn.lockObject = (Value) tn.lockset.get(0);
// If it's the best lock we've found in the group yet, use it for display
if (tn.group.lockObject == null || tn.lockObject instanceof Ref) {
tn.group.lockObject = tn.lockObject;
}
}
}
}
}
if (optionUseLocksets) {
// If any lock has only a singleton reaching object, treat it like a static lock
for (int i = 0; i < lockPTSets.size(); i++) {
PointsToSetInternal pts = lockPTSets.get(i);
if (pts.size() == 1 && false) // isSingleton(pts)) // It's NOT easy to find a singleton: single alloc node must be
// run just once
{
for (Object e : lockToLockNum.entrySet()) {
Map.Entry entry = (Map.Entry) e;
Integer value = (Integer) entry.getValue();
if (value == i) {
entry.setValue(new Integer(-i));
}
}
}
}
}
}
public void setFlagsForDynamicAllocations(CriticalSectionInterferenceGraph ig) {
for (int group = 0; group < ig.groupCount() - 1; group++) {
CriticalSectionGroup tnGroup = ig.groups().get(group + 1);
if (optionUseLocksets) {
tnGroup.useLocksets = true; // initially, guess that this is true
} else {
tnGroup.isDynamicLock = (tnGroup.rwSet.getGlobals().size() == 0);
tnGroup.useDynamicLock = true;
tnGroup.lockObject = null;
}
// empty groups don't get locks
if (tnGroup.rwSet.size() <= 0) // There are no edges in this group
{
if (optionUseLocksets) {
tnGroup.useLocksets = false;
} else {
tnGroup.isDynamicLock = false;
tnGroup.useDynamicLock = false;
}
continue;
}
}
}
public void setFlagsForStaticAllocations(CriticalSectionInterferenceGraph ig) {
// Allocate one new static lock for each group.
for (int group = 0; group < ig.groupCount() - 1; group++) {
CriticalSectionGroup tnGroup = ig.groups().get(group + 1);
tnGroup.isDynamicLock = false;
tnGroup.useDynamicLock = false;
tnGroup.lockObject = null;
}
}
private void analyzeExistingLocks(List<CriticalSection> AllTransactions, CriticalSectionInterferenceGraph ig) {
setFlagsForStaticAllocations(ig);
// if for any lock there is any def to anything other than a static field, then it's a local lock.
// for each transaction, check every def of the lock
Iterator<CriticalSection> tnAIt = AllTransactions.iterator();
while (tnAIt.hasNext()) {
CriticalSection tn = tnAIt.next();
if (tn.setNumber <= 0) {
continue;
}
LocalDefs ld = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(tn.method.retrieveActiveBody());
if (tn.origLock == null || !(tn.origLock instanceof Local)) {
continue;
}
List<Unit> rDefs = ld.getDefsOfAt((Local) tn.origLock, tn.entermonitor);
if (rDefs == null) {
continue;
}
for (Unit u : rDefs) {
Stmt next = (Stmt) u;
if (next instanceof DefinitionStmt) {
Value rightOp = ((DefinitionStmt) next).getRightOp();
if (rightOp instanceof FieldRef) {
if (((FieldRef) rightOp).getField().isStatic()) {
// lock may be static
tn.group.lockObject = rightOp;
} else {
// this lock must be dynamic
tn.group.isDynamicLock = true;
tn.group.useDynamicLock = true;
tn.group.lockObject = tn.origLock;
}
} else {
// this lock is probably dynamic (but it's hard to tell for sure)
tn.group.isDynamicLock = true;
tn.group.useDynamicLock = true;
tn.group.lockObject = tn.origLock;
}
} else {
// this lock is probably dynamic (but it's hard to tell for sure)
tn.group.isDynamicLock = true;
tn.group.useDynamicLock = true;
tn.group.lockObject = tn.origLock;
}
}
}
}
public static String locksetToLockNumString(List<EquivalentValue> lockset, Map<Value, Integer> lockToLockNum) {
if (lockset == null) {
return "null";
}
String ret = "[";
boolean first = true;
for (EquivalentValue lockEqVal : lockset) {
if (!first) {
ret = ret + " ";
}
first = false;
ret = ret + lockToLockNum.get(lockEqVal.getValue());
}
return ret + "]";
}
public void assignNamesToTransactions(List<CriticalSection> AllTransactions) {
// Give each method a unique, deterministic identifier
// Sort transactions into bins... one for each method name
// Get list of method names
List<String> methodNamesTemp = new ArrayList<String>();
Iterator<CriticalSection> tnIt5 = AllTransactions.iterator();
while (tnIt5.hasNext()) {
CriticalSection tn1 = tnIt5.next();
String mname = tn1.method.getSignature(); // tn1.method.getSignature() + "." + tn1.method.getName();
if (!methodNamesTemp.contains(mname)) {
methodNamesTemp.add(mname);
}
}
String methodNames[] = new String[1];
methodNames = methodNamesTemp.toArray(methodNames);
Arrays.sort(methodNames);
// Initialize method-named bins
// this matrix is <# method names> wide and <max txns possible in one method> + 1 tall
int identMatrix[][] = new int[methodNames.length][CriticalSection.nextIDNum - methodNames.length + 2];
for (int i = 0; i < methodNames.length; i++) {
identMatrix[i][0] = 0;
for (int j = 1; j < CriticalSection.nextIDNum - methodNames.length + 1; j++) {
identMatrix[i][j] = 50000;
}
}
// Put transactions into bins
Iterator<CriticalSection> tnIt0 = AllTransactions.iterator();
while (tnIt0.hasNext()) {
CriticalSection tn1 = tnIt0.next();
int methodNum = Arrays.binarySearch(methodNames, tn1.method.getSignature());
identMatrix[methodNum][0]++;
identMatrix[methodNum][identMatrix[methodNum][0]] = tn1.IDNum;
}
// Sort bins by transaction IDNum
// IDNums vary, but always increase in code-order within a method
for (int j = 0; j < methodNames.length; j++) {
identMatrix[j][0] = 0; // set the counter to 0 so it sorts out (into slot 0).
Arrays.sort(identMatrix[j]); // sort this subarray
}
// Generate a name based on the bin number and location within the bin
Iterator<CriticalSection> tnIt4 = AllTransactions.iterator();
while (tnIt4.hasNext()) {
CriticalSection tn1 = tnIt4.next();
int methodNum = Arrays.binarySearch(methodNames, tn1.method.getSignature());
int tnNum = Arrays.binarySearch(identMatrix[methodNum], tn1.IDNum) - 1;
tn1.name
= "m" + (methodNum < 10 ? "00" : (methodNum < 100 ? "0" : "")) + methodNum + "n" + (tnNum < 10 ? "0" : "") + tnNum;
}
}
public void printGraph(Collection<CriticalSection> AllTransactions, CriticalSectionInterferenceGraph ig,
Map<Value, Integer> lockToLockNum) {
final String[] colors = { "black", "blue", "blueviolet", "chartreuse", "crimson", "darkgoldenrod1", "darkseagreen",
"darkslategray", "deeppink", "deepskyblue1", "firebrick1", "forestgreen", "gold", "gray80", "navy", "pink", "red",
"sienna", "turquoise1", "yellow" };
Map<Integer, String> lockColors = new HashMap<Integer, String>();
int colorNum = 0;
HashSet<CriticalSection> visited = new HashSet<CriticalSection>();
logger.debug("[transaction-graph]" + (optionUseLocksets ? "" : " strict") + " graph transactions {");
// "\n[transaction-graph]
// start=1;");
for (int group = 0; group < ig.groups().size(); group++) {
boolean printedHeading = false;
Iterator<CriticalSection> tnIt = AllTransactions.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = tnIt.next();
if (tn.setNumber == group + 1) {
if (!printedHeading) {
// if(localLock[group] && lockObject[group] != null)
if (tn.group.useDynamicLock && tn.group.lockObject != null) {
String typeString = "";
// if(lockObject[group].getType() instanceof RefType)
// typeString = ((RefType) lockObject[group].getType()).getSootClass().getShortName();
// else
// typeString = lockObject[group].getType().toString();
if (tn.group.lockObject.getType() instanceof RefType) {
typeString = ((RefType) tn.group.lockObject.getType()).getSootClass().getShortName();
} else {
typeString = tn.group.lockObject.getType().toString();
}
logger.debug("[transaction-graph] subgraph cluster_" + (group + 1)
+ " {\n[transaction-graph] color=blue;\n[transaction-graph] label=\"Lock: a \\n" + typeString
+ " object\";");
} else if (tn.group.useLocksets) {
logger.debug("[transaction-graph] subgraph cluster_" + (group + 1)
+ " {\n[transaction-graph] color=blue;\n[transaction-graph] label=\"Locksets\";");
} else {
String objString = "";
// if(lockObject[group] == null)
if (tn.group.lockObject == null) {
objString = "lockObj" + (group + 1);
}
// else if(lockObject[group] instanceof FieldRef)
else if (tn.group.lockObject instanceof FieldRef) {
// SootField field = ((FieldRef) lockObject[group]).getField();
SootField field = ((FieldRef) tn.group.lockObject).getField();
objString = field.getDeclaringClass().getShortName() + "." + field.getName();
} else {
objString = tn.group.lockObject.toString();
}
// objString = lockObject[group].toString();
logger.debug("[transaction-graph] subgraph cluster_" + (group + 1)
+ " {\n[transaction-graph] color=blue;\n[transaction-graph] label=\"Lock: \\n" + objString + "\";");
}
printedHeading = true;
}
if (Scene.v().getReachableMethods().contains(tn.method)) {
logger.debug(
"[transaction-graph] " + tn.name + " [name=\"" + tn.method.toString() + "\" style=\"setlinewidth(3)\"];");
} else {
logger.debug("[transaction-graph] " + tn.name + " [name=\"" + tn.method.toString()
+ "\" color=cadetblue1 style=\"setlinewidth(1)\"];");
}
if (tn.group.useLocksets) // print locks instead of dependence edges
{
for (EquivalentValue lockEqVal : tn.lockset) {
Integer lockNum = lockToLockNum.get(lockEqVal.getValue());
for (CriticalSection tn2 : tn.group) {
if (!visited.contains(tn2) && ig.mayHappenInParallel(tn, tn2)) {
for (EquivalentValue lock2EqVal : tn2.lockset) {
Integer lock2Num = lockToLockNum.get(lock2EqVal.getValue());
if (lockNum.intValue() == lock2Num.intValue()) {
// Get the color for this lock
if (!lockColors.containsKey(lockNum)) {
lockColors.put(lockNum, colors[colorNum % colors.length]);
colorNum++;
}
String color = lockColors.get(lockNum);
// Draw an edge for this lock
logger.debug("[transaction-graph] " + tn.name + " -- " + tn2.name + " [color=" + color + " style="
+ (lockNum >= 0 ? "dashed" : "solid") + " exactsize=1 style=\"setlinewidth(3)\"];");
}
}
}
}
visited.add(tn);
}
} else {
Iterator<CriticalSectionDataDependency> tnedgeit = tn.edges.iterator();
while (tnedgeit.hasNext()) {
CriticalSectionDataDependency edge = tnedgeit.next();
CriticalSection tnedge = edge.other;
if (tnedge.setNumber == group + 1) {
logger.debug("[transaction-graph] " + tn.name + " -- " + tnedge.name + " [color="
+ (edge.size > 0 ? "black" : "cadetblue1") + " style="
+ (tn.setNumber > 0 && tn.group.useDynamicLock ? "dashed" : "solid") + " exactsize=" + edge.size
+ " style=\"setlinewidth(3)\"];");
}
}
}
}
}
if (printedHeading) {
logger.debug("[transaction-graph] }");
}
}
// Print nodes with no group
{
boolean printedHeading = false;
Iterator<CriticalSection> tnIt = AllTransactions.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = tnIt.next();
if (tn.setNumber == -1) {
if (!printedHeading) {
// putting these nodes in a "source" ranked subgraph makes them appear above all the clusters
logger.debug("[transaction-graph] subgraph lone {\n[transaction-graph] rank=source;");
printedHeading = true;
}
if (Scene.v().getReachableMethods().contains(tn.method)) {
logger.debug(
"[transaction-graph] " + tn.name + " [name=\"" + tn.method.toString() + "\" style=\"setlinewidth(3)\"];");
} else {
logger.debug("[transaction-graph] " + tn.name + " [name=\"" + tn.method.toString()
+ "\" color=cadetblue1 style=\"setlinewidth(1)\"];");
}
Iterator<CriticalSectionDataDependency> tnedgeit = tn.edges.iterator();
while (tnedgeit.hasNext()) {
CriticalSectionDataDependency edge = tnedgeit.next();
CriticalSection tnedge = edge.other;
if (tnedge.setNumber != tn.setNumber || tnedge.setNumber == -1) {
logger.debug("[transaction-graph] " + tn.name + " -- " + tnedge.name + " [color="
+ (edge.size > 0 ? "black" : "cadetblue1") + " style="
+ (tn.setNumber > 0 && tn.group.useDynamicLock ? "dashed" : "solid") + " exactsize=" + edge.size
+ " style=\"setlinewidth(1)\"];");
}
}
}
}
if (printedHeading) {
logger.debug("[transaction-graph] }");
}
}
logger.debug("[transaction-graph] }");
}
public void printTable(Collection<CriticalSection> AllTransactions, MhpTester mhp) {
logger.debug("[transaction-table] ");
Iterator<CriticalSection> tnIt7 = AllTransactions.iterator();
while (tnIt7.hasNext()) {
CriticalSection tn = tnIt7.next();
// Figure out if it's reachable, and if it MHP itself
boolean reachable = false;
boolean mhpself = false;
{
ReachableMethods rm = Scene.v().getReachableMethods();
reachable = rm.contains(tn.method);
if (mhp != null) {
mhpself = mhp.mayHappenInParallel(tn.method, tn.method);
}
}
logger.debug("[transaction-table] Transaction " + tn.name + (reachable ? " reachable" : " dead")
+ (mhpself ? " [called from >= 2 threads]" : " [called from <= 1 thread]"));
logger.debug(
"[transaction-table] Where: " + tn.method.getDeclaringClass().toString() + ":" + tn.method.toString() + ": ");
logger.debug("[transaction-table] Orig : " + tn.origLock);
logger.debug("[transaction-table] Prep : " + tn.prepStmt);
logger.debug("[transaction-table] Begin: " + tn.entermonitor);
logger.debug("[transaction-table] End : early:" + tn.earlyEnds.toString() + " exc:" + tn.exceptionalEnd + " through:"
+ tn.end + " \n");
logger.debug("[transaction-table] Size : " + tn.units.size());
if (tn.read.size() < 100) {
logger.debug("[transaction-table] Read : " + tn.read.size() + "\n[transaction-table] "
+ tn.read.toString().replaceAll("\\[", " : [").replaceAll("\n", "\n[transaction-table] "));
} else {
logger.debug("[transaction-table] Read : " + tn.read.size() + " \n[transaction-table] ");
}
if (tn.write.size() < 100) {
logger.debug("Write: " + tn.write.size() + "\n[transaction-table] "
+ tn.write.toString().replaceAll("\\[", " : [").replaceAll("\n", "\n[transaction-table] ")); // label
// provided by
// previous
// print
// statement
} else {
logger.debug("Write: " + tn.write.size() + "\n[transaction-table] "); // label provided by previous print statement
}
logger.debug("Edges: (" + tn.edges.size() + ") "); // label provided by previous print statement
Iterator<CriticalSectionDataDependency> tnedgeit = tn.edges.iterator();
while (tnedgeit.hasNext()) {
logger.debug("" + tnedgeit.next().other.name + " ");
}
if (tn.group != null && tn.group.useLocksets) {
logger.debug("\n[transaction-table] Locks: " + tn.lockset);
} else {
logger.debug("\n[transaction-table] Lock : " + (tn.setNumber == -1 ? "-"
: (tn.lockObject == null ? "Global"
: (tn.lockObject.toString()
+ (tn.lockObjectArrayIndex == null ? "" : "[" + tn.lockObjectArrayIndex + "]")))));
}
logger.debug("[transaction-table] Group: " + tn.setNumber + "\n[transaction-table] ");
}
}
public void printGroups(Collection<CriticalSection> AllTransactions, CriticalSectionInterferenceGraph ig) {
logger.debug("[transaction-groups] Group Summaries\n[transaction-groups] ");
for (int group = 0; group < ig.groupCount() - 1; group++) {
CriticalSectionGroup tnGroup = ig.groups().get(group + 1);
if (tnGroup.size() > 0) {
logger.debug("Group " + (group + 1) + " ");
logger.debug("Locking: "
+ (tnGroup.useLocksets ? "using "
: (tnGroup.isDynamicLock && tnGroup.useDynamicLock ? "Dynamic on " : "Static on "))
+ (tnGroup.useLocksets ? "locksets" : (tnGroup.lockObject == null ? "null" : tnGroup.lockObject.toString())));
logger.debug("\n[transaction-groups] : ");
Iterator<CriticalSection> tnIt = AllTransactions.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = tnIt.next();
if (tn.setNumber == group + 1) {
logger.debug("" + tn.name + " ");
}
}
logger.debug("\n[transaction-groups] "
+ tnGroup.rwSet.toString().replaceAll("\\[", " : [").replaceAll("\n", "\n[transaction-groups] "));
}
}
logger.debug("Erasing \n[transaction-groups] : ");
Iterator<CriticalSection> tnIt = AllTransactions.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = tnIt.next();
if (tn.setNumber == -1) {
logger.debug("" + tn.name + " ");
}
}
logger.debug("\n[transaction-groups] ");
}
public CriticalSectionInterferenceGraph getInterferenceGraph() {
return interferenceGraph;
}
public DirectedGraph getDeadlockGraph() {
return deadlockGraph;
}
public List<CriticalSection> getCriticalSections() {
return criticalSections;
}
}
| 43,268
| 43.062118
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/LockableReferenceAnalysis.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.EquivalentValue;
import soot.Local;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AnyNewExpr;
import soot.jimple.ArrayRef;
import soot.jimple.CastExpr;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.IdentityRef;
import soot.jimple.IdentityStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.ParameterRef;
import soot.jimple.Ref;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.ThisRef;
import soot.jimple.toolkits.infoflow.FakeJimpleLocal;
import soot.jimple.toolkits.pointer.CodeBlockRWSet;
import soot.jimple.toolkits.pointer.RWSet;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.BackwardFlowAnalysis;
/**
* Finds the set of local variables and/or references that represent all of the relevant objects used in a synchronized
* region, as accessible at the start of that region. Basically this is value numbering, done in reverse, interprocedurally,
* and only tracking the values that contribute to the given set of side effects.
*
* @author Richard L. Halpert
* @since 2007-04-19
*/
public class LockableReferenceAnalysis extends BackwardFlowAnalysis<Unit, LocksetFlowInfo> {
private static final Logger logger = LoggerFactory.getLogger(LockableReferenceAnalysis.class);
UnitGraph graph;
SootMethod method;
CriticalSectionAwareSideEffectAnalysis tasea;
RWSet contributingRWSet;
CriticalSection tn;
Stmt begin;
boolean lostObjects;
// These two maps hold the final ref->base or ref->index relationship
Map<Ref, EquivalentValue> refToBase;
Map<Ref, EquivalentValue> refToIndex;
static Set<SootMethod> analyzing = new HashSet<SootMethod>();
public LockableReferenceAnalysis(UnitGraph g) {
super(g);
graph = g;
method = g.getBody().getMethod();
contributingRWSet = null;
tn = null;
begin = null;
lostObjects = false;
refToBase = new HashMap<Ref, EquivalentValue>();
refToIndex = new HashMap<Ref, EquivalentValue>();
// analysis is done on-demand, not now
}
public void printMsg(String msg) {
logger.debug("[wjtp.tn] ");
for (int i = 0; i < analyzing.size() - 1; i++) {
logger.debug(" ");
}
logger.debug("" + msg);
}
public List<EquivalentValue> getLocksetOf(CriticalSectionAwareSideEffectAnalysis tasea, RWSet contributingRWSet,
CriticalSection tn) {
analyzing.add(method);
this.tasea = tasea;
tasea.setExemptTransaction(tn);
this.contributingRWSet = contributingRWSet;
this.tn = tn;
this.begin = (tn == null ? null : tn.beginning);
lostObjects = false;
doAnalysis();
if (lostObjects) {
printMsg("Failed lockset:");
analyzing.remove(method);
return null;
}
// STOP
List<EquivalentValue> lockset = new ArrayList<EquivalentValue>();
LocksetFlowInfo resultsInfo = null;
Map<soot.EquivalentValue, java.lang.Integer> results = null;
if (begin == null) {
for (Unit u : graph) {
resultsInfo = getFlowBefore(u); // flow before first unit
}
} else {
resultsInfo = getFlowBefore(begin); // flow before begin unit
}
if (resultsInfo == null) {
analyzing.remove(method);
throw new RuntimeException("Why is getFlowBefore null???");
}
results = resultsInfo.groups;
// Reverse the results so it maps value->keys instead of key->value
// Then we can pick just one object (key) per group (value)
Map<Integer, List<EquivalentValue>> reversed = new HashMap<Integer, List<EquivalentValue>>();
for (Map.Entry<EquivalentValue, Integer> e : results.entrySet()) {
EquivalentValue key = e.getKey();
Integer value = e.getValue();
List<EquivalentValue> keys;
if (!reversed.containsKey(value)) {
keys = new ArrayList<EquivalentValue>();
reversed.put(value, keys);
} else {
keys = reversed.get(value);
}
keys.add(key);
}
// For each group, choose the one best object to put in the lockset
for (List<EquivalentValue> objects : reversed.values()) {
EquivalentValue bestLock = null;
for (EquivalentValue object : objects) {
if (bestLock == null || object.getValue() instanceof IdentityRef
|| (object.getValue() instanceof Ref && !(bestLock instanceof IdentityRef))) {
bestLock = object;
}
}
Integer group = (results.get(bestLock));
// record if bestLock is the base or index for a reference
for (Ref ref : resultsInfo.refToBaseGroup.keySet()) {
if (group == resultsInfo.refToBaseGroup.get(ref)) {
refToBase.put(ref, bestLock);
}
}
for (Ref ref : resultsInfo.refToIndexGroup.keySet()) {
if (group == resultsInfo.refToIndexGroup.get(ref)) {
refToIndex.put(ref, bestLock);
}
}
// add bestLock to lockset if it's from a group that requires a lock
if (group >= 0) {
lockset.add(bestLock); // a lock for each positively-numbered group
}
}
if (lockset.size() == 0) {
printMsg("Empty lockset: S" + lockset.size() + "/G" + reversed.keySet().size() + "/O" + results.keySet().size()
+ " Method:" + method + " Begin:" + begin + " Result:" + results + " RW:" + contributingRWSet);
printMsg("|= results:" + results + " refToBaseGroup:" + resultsInfo.refToBaseGroup);
} else {
printMsg("Healthy lockset: S" + lockset.size() + "/G" + reversed.keySet().size() + "/O" + results.keySet().size() + " "
+ lockset + " refToBase:" + refToBase + " refToIndex:" + refToIndex);
printMsg("|= results:" + results + " refToBaseGroup:" + resultsInfo.refToBaseGroup);
}
analyzing.remove(method);
return lockset;
}
public EquivalentValue baseFor(Ref ref) {
return refToBase.get(ref);
}
public EquivalentValue indexFor(Ref ref) {
return refToIndex.get(ref);
}
protected void merge(LocksetFlowInfo in1, LocksetFlowInfo in2, LocksetFlowInfo out) {
LocksetFlowInfo tmpInfo = new LocksetFlowInfo();
// union of the two maps,
// When the same key is present, if the groups are different, then they get merged
// (ensure every new group gets a new number)
// copy in1 into out
copy(in1, out);
// copy in2 into tmp
copy(in2, tmpInfo);
// for each tmpentry in tmpMap
for (EquivalentValue key : tmpInfo.groups.keySet()) {
Integer newvalue = tmpInfo.groups.get(key);
// if the key ISN'T in outMap, add it
if (!out.groups.containsKey(key)) {
out.groups.put(key, newvalue);
}
// if the key IS in outMap with the same value, do nothing
// if the key IS in outMap with a different value,
else if (out.groups.get(key) != tmpInfo.groups.get(key)) {
// replace oldvalue with value in both maps,
// and also in the base and index tracker maps
Object oldvalue = out.groups.get(key);
// every entry in outMap with the old value gets the new value
for (Map.Entry<?, Integer> entry : out.groups.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == oldvalue) {
entry.setValue(newvalue);
}
}
// every entry in tmpMap with the old value gets the new value
for (Map.Entry<?, Integer> entry : tmpInfo.groups.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == oldvalue) {
entry.setValue(newvalue);
}
}
// every entry in refToBaseGroup with the old value gets the new value
for (Map.Entry<?, Integer> entry : out.refToBaseGroup.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == oldvalue) {
entry.setValue(newvalue);
}
}
// every entry in refToIndexGroup with the old value gets the new value
for (Map.Entry<?, Integer> entry : out.refToIndexGroup.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == oldvalue) {
entry.setValue(newvalue);
}
}
// every entry in refToBaseGroup with the old value gets the new value
for (Map.Entry<?, Integer> entry : tmpInfo.refToBaseGroup.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == oldvalue) {
entry.setValue(newvalue);
}
}
// every entry in refToIndexGroup with the old value gets the new value
for (Map.Entry<?, Integer> entry : tmpInfo.refToIndexGroup.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == oldvalue) {
entry.setValue(newvalue);
}
}
}
}
for (Ref ref : tmpInfo.refToBaseGroup.keySet()) {
if (!out.refToBaseGroup.containsKey(ref)) {
out.refToBaseGroup.put(ref, tmpInfo.refToBaseGroup.get(ref));
}
}
for (Ref ref : tmpInfo.refToIndexGroup.keySet()) {
if (!out.refToIndexGroup.containsKey(ref)) {
out.refToIndexGroup.put(ref, tmpInfo.refToIndexGroup.get(ref));
}
}
}
// adds a value from a subanalysis into this analysis, and returns the group it gets put into
public Integer addFromSubanalysis(LocksetFlowInfo outInfo, LockableReferenceAnalysis la, Stmt stmt, Value lock) {
Map<EquivalentValue, Integer> out = outInfo.groups;
InvokeExpr ie = stmt.getInvokeExpr();
printMsg("Attempting to bring up '" + lock + "' from inner lockset at (" + stmt.hashCode() + ") " + stmt);
if (lock instanceof ThisRef && ie instanceof InstanceInvokeExpr) {
Value use = ((InstanceInvokeExpr) ie).getBase();
if (!out.containsKey(new EquivalentValue(use))) {
int newGroup = groupNum++;
out.put(new EquivalentValue(use), newGroup);
return newGroup;
}
return out.get(new EquivalentValue(use));
} else if (lock instanceof ParameterRef) {
Value use = ie.getArg(((ParameterRef) lock).getIndex());
if (!out.containsKey(new EquivalentValue(use))) {
int newGroup = groupNum++;
out.put(new EquivalentValue(use), newGroup);
return newGroup;
}
return out.get(new EquivalentValue(use));
} else if (lock instanceof StaticFieldRef) {
Value use = lock;
if (!out.containsKey(new EquivalentValue(use))) {
int newGroup = groupNum++;
out.put(new EquivalentValue(use), newGroup);
return newGroup;
}
return out.get(new EquivalentValue(use));
} else if (lock instanceof InstanceFieldRef) {
// Step 0: redirect fakejimplelocals to this
if (((InstanceFieldRef) lock).getBase() instanceof FakeJimpleLocal) {
((FakeJimpleLocal) ((InstanceFieldRef) lock).getBase()).setInfo(this);
}
// Step 1: make sure base is accessible (process it)
// Step 2: get the group number (here) for the base
EquivalentValue baseEqVal = la.baseFor((Ref) lock);
if (baseEqVal == null) {
printMsg("Lost Object from inner Lockset (InstanceFieldRef w/ previously lost base) at " + stmt);
return 0;
}
Value base = baseEqVal.getValue();
Integer baseGroup = addFromSubanalysis(outInfo, la, stmt, base);
if (baseGroup == 0) {
printMsg("Lost Object from inner Lockset (InstanceFieldRef w/ newly lost base) at " + stmt);
return 0;
}
// Step 3: put the FieldRef and basegroupnum into refToBaseGroup
outInfo.refToBaseGroup.put((Ref) lock, baseGroup); // track relationship between ref and base group
// Step 4: put the FieldRef into a new group in 'out' unless already there
// InstanceFieldRef ifr = (InstanceFieldRef) lock;
// Local oldbase = (Local) ifr.getBase();
// Local newbase = new FakeJimpleLocal("fakethis", oldbase.getType(), oldbase);
// Value node = Jimple.v().newInstanceFieldRef(newbase, ifr.getField().makeRef());
// EquivalentValue nodeEqVal = new EquivalentValue( node ); // fake thisLocal
Value use = lock;
if (!out.containsKey(new EquivalentValue(use))) {
int newGroup = groupNum++;
out.put(new EquivalentValue(use), newGroup);
return newGroup;
}
return out.get(new EquivalentValue(use));
} else if (lock instanceof ArrayRef) {
// Step 0: redirect fakejimplelocals to this
if (((ArrayRef) lock).getBase() instanceof FakeJimpleLocal) {
((FakeJimpleLocal) ((ArrayRef) lock).getBase()).setInfo(this);
}
if (((ArrayRef) lock).getIndex() instanceof FakeJimpleLocal) {
((FakeJimpleLocal) ((ArrayRef) lock).getIndex()).setInfo(this);
}
// Step 1: make sure base is accessible (process it)
// Step 2: get the group number (here) for the base
EquivalentValue baseEqVal = la.baseFor((Ref) lock);
EquivalentValue indexEqVal = la.indexFor((Ref) lock);
if (baseEqVal == null) {
printMsg("Lost Object from inner Lockset (InstanceFieldRef w/ previously lost base) at " + stmt);
return 0;
}
if (indexEqVal == null) {
printMsg("Lost Object from inner Lockset (InstanceFieldRef w/ previously lost index) at " + stmt);
return 0;
}
Value base = baseEqVal.getValue();
Value index = indexEqVal.getValue();
Integer baseGroup = addFromSubanalysis(outInfo, la, stmt, base);
if (baseGroup == 0) {
printMsg("Lost Object from inner Lockset (InstanceFieldRef w/ newly lost base) at " + stmt);
return 0;
}
Integer indexGroup = addFromSubanalysis(outInfo, la, stmt, index);
if (indexGroup == 0) {
printMsg("Lost Object from inner Lockset (InstanceFieldRef w/ newly lost index) at " + stmt);
return 0;
}
// Step 3: put the FieldRef and basegroupnum into refToBaseGroup
outInfo.refToBaseGroup.put((Ref) lock, baseGroup); // track relationship between ref and base group
outInfo.refToIndexGroup.put((Ref) lock, indexGroup); // track relationship between ref and index group
// Step 4: put the FieldRef into a new group in 'out' unless already there
// InstanceFieldRef ifr = (InstanceFieldRef) lock;
// Local oldbase = (Local) ifr.getBase();
// Local newbase = new FakeJimpleLocal("fakethis", oldbase.getType(), oldbase);
// Value node = Jimple.v().newInstanceFieldRef(newbase, ifr.getField().makeRef());
// EquivalentValue nodeEqVal = new EquivalentValue( node ); // fake thisLocal
Value use = lock;
if (!out.containsKey(new EquivalentValue(use))) {
int newGroup = groupNum++;
out.put(new EquivalentValue(use), newGroup);
return newGroup;
}
return out.get(new EquivalentValue(use));
} else if (lock instanceof Constant) {
Value use = lock;
if (!out.containsKey(new EquivalentValue(use))) {
int newGroup = groupNum++;
out.put(new EquivalentValue(use), newGroup);
return newGroup;
}
return out.get(new EquivalentValue(use));
} else {
printMsg("Lost Object from inner Lockset (unknown or unhandled object type) at " + stmt);
}
return 0; // failure code... the only number that is never a valid group
}
static int groupNum = 1;
@Override
protected void flowThrough(LocksetFlowInfo inInfo, Unit u, LocksetFlowInfo outInfo) {
copy(inInfo, outInfo);
Stmt stmt = (Stmt) u;
Map<EquivalentValue, Integer> out = outInfo.groups;
// If this statement contains a contributing use
if ((tn == null || tn.units.contains(stmt)) && !lostObjects) {
// Prepare the RW set for the statement
CodeBlockRWSet stmtRW = null;
Set<Value> allUses = new HashSet<Value>();
RWSet stmtRead = tasea.readSet(method, stmt, tn, allUses);
if (stmtRead != null) {
stmtRW = (CodeBlockRWSet) stmtRead;
}
RWSet stmtWrite = tasea.writeSet(method, stmt, tn, allUses);
if (stmtWrite != null) {
if (stmtRW != null) {
stmtRW.union(stmtWrite);
} else {
stmtRW = (CodeBlockRWSet) stmtWrite;
}
}
// If the stmtRW intersects the contributingRW
if (stmtRW != null && stmtRW.hasNonEmptyIntersection(contributingRWSet)) {
List<Value> uses = new ArrayList<Value>();
Iterator<Value> allUsesIt = allUses.iterator();
while (allUsesIt.hasNext()) {
Value vEqVal = allUsesIt.next();
Value v = vEqVal; // ((vEqVal instanceof EquivalentValue) ? ((EquivalentValue) vEqVal).getValue() : vEqVal);
if (stmt.containsFieldRef()) {
FieldRef fr = stmt.getFieldRef();
if (fr instanceof InstanceFieldRef) {
if (((InstanceFieldRef) fr).getBase() == v) {
v = fr;
}
}
}
if (stmt.containsArrayRef()) {
ArrayRef ar = stmt.getArrayRef();
if (ar.getBase() == v) {
v = ar;
}
}
// it would be better to just check if the value has reaching objects in common with the bases of the
// contributingRWSet
RWSet valRW = tasea.valueRWSet(v, method, stmt, tn);
if (valRW != null && valRW.hasNonEmptyIntersection(contributingRWSet)) {
uses.add(vEqVal);
}
}
if (stmt.containsInvokeExpr()) {
InvokeExpr ie = stmt.getInvokeExpr();
SootMethod called = ie.getMethod();
if (called.isConcrete()) {
if (called.getDeclaringClass().toString().startsWith("java.util")
|| called.getDeclaringClass().toString().startsWith("java.lang")) {
// these uses should already be in use list
if (uses.size() <= 0) {
printMsg("Lost Object at library call at " + stmt);
lostObjects = true;
}
} else {
// find and add this callsite's uses
if (!analyzing.contains(called)) {
LockableReferenceAnalysis la
= new LockableReferenceAnalysis(new BriefUnitGraph(called.retrieveActiveBody()));
List<EquivalentValue> innerLockset = la.getLocksetOf(tasea, stmtRW, null);
if (innerLockset == null || innerLockset.size() <= 0) {
printMsg("innerLockset: " + (innerLockset == null ? "Lost Objects" : "Mysteriously Empty"));
lostObjects = true;
} else {
printMsg("innerLockset: " + innerLockset.toString());
// Add used receiver and args to uses
for (EquivalentValue lockEqVal : innerLockset) {
Value lock = lockEqVal.getValue();
if (addFromSubanalysis(outInfo, la, stmt, lock) == 0) {
lostObjects = true;
printMsg("Lost Object in addFromSubanalysis()");
break;
}
}
}
} else {
lostObjects = true;
printMsg("Lost Object due to recursion " + stmt);
}
}
} else if (uses.size() <= 0) {
lostObjects = true;
printMsg("Lost Object from non-concrete method call at " + stmt);
}
} else if (uses.size() <= 0) {
lostObjects = true;
printMsg("Lost Object SOMEHOW at " + stmt);
}
// For each use, either add it to an existing lock, or add a new lock
Iterator<Value> usesIt = uses.iterator();
while (usesIt.hasNext() && !lostObjects) {
Value use = (Value) usesIt.next();
// if present, ok, if not, add as new group
if (use instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) use;
Local oldbase = (Local) ifr.getBase();
if (!(oldbase instanceof FakeJimpleLocal)) {
Local newbase = new FakeJimpleLocal("fakethis", oldbase.getType(), oldbase, this);
Value node = Jimple.v().newInstanceFieldRef(newbase, ifr.getField().makeRef());
EquivalentValue nodeEqVal = new EquivalentValue(node); // fake thisLocal
use = node;
}
} else if (use instanceof ArrayRef) // requires special packaging
{
ArrayRef ar = (ArrayRef) use;
Local oldbase = (Local) ar.getBase();
Value oldindex = ar.getIndex();
if (!(oldbase instanceof FakeJimpleLocal)) {
Local newbase = new FakeJimpleLocal("fakethis", oldbase.getType(), oldbase, this);
Value newindex = (oldindex instanceof Local)
? new FakeJimpleLocal("fakeindex", oldindex.getType(), (Local) oldindex, this)
: oldindex;
Value node = Jimple.v().newArrayRef(newbase, newindex);
EquivalentValue nodeEqVal = new EquivalentValue(node); // fake thisLocal
use = node;
}
}
if (!out.containsKey(new EquivalentValue(use))) {
out.put(new EquivalentValue(use), groupNum++);
}
}
}
}
if (graph.getBody().getUnits().getSuccOf(stmt) == begin) {
out.clear();
}
// if lvalue is in a group:
// if rvalue is in a group, group containing lvalue gets merged with group containing rvalue
// if rvalue is not in a group
// if rvalue is a local or a static field ref, rvalue gets put into lvalue's group
// if rvalue is an instance field ref, DO SOMETHING WITH IT?
// if rvalue is anything else, set "lost objects" flag
// lvalue gets removed from group
if ((tn == null || tn.units.contains(stmt)) && !out.isEmpty() && stmt instanceof DefinitionStmt && !lostObjects) {
DefinitionStmt ds = (DefinitionStmt) stmt;
// Retrieve and package the lvalue
EquivalentValue lvalue = new EquivalentValue(ds.getLeftOp());
if (ds.getLeftOp() instanceof InstanceFieldRef) // requires special packaging
{
InstanceFieldRef ifr = (InstanceFieldRef) ds.getLeftOp();
Local oldbase = (Local) ifr.getBase();
if (!(oldbase instanceof FakeJimpleLocal)) {
Local newbase = new FakeJimpleLocal("fakethis", oldbase.getType(), oldbase, this);
Value node = Jimple.v().newInstanceFieldRef(newbase, ifr.getField().makeRef());
EquivalentValue nodeEqVal = new EquivalentValue(node); // fake thisLocal
lvalue = nodeEqVal;
}
} else if (ds.getLeftOp() instanceof ArrayRef) // requires special packaging
{
ArrayRef ar = (ArrayRef) ds.getLeftOp();
Local oldbase = (Local) ar.getBase();
Value oldindex = ar.getIndex();
if (!(oldbase instanceof FakeJimpleLocal)) {
Local newbase = new FakeJimpleLocal("fakethis", oldbase.getType(), oldbase, this);
Value newindex
= (oldindex instanceof Local) ? new FakeJimpleLocal("fakeindex", oldindex.getType(), (Local) oldindex, this)
: oldindex;
Value node = Jimple.v().newArrayRef(newbase, newindex);
EquivalentValue nodeEqVal = new EquivalentValue(node); // fake thisLocal
lvalue = nodeEqVal;
}
}
// Retrieve and package the rvalue
EquivalentValue rvalue = new EquivalentValue(ds.getRightOp());
if (ds.getRightOp() instanceof CastExpr) {
rvalue = new EquivalentValue(((CastExpr) ds.getRightOp()).getOp());
} else if (ds.getRightOp() instanceof InstanceFieldRef) // requires special packaging
{
InstanceFieldRef ifr = (InstanceFieldRef) ds.getRightOp();
Local oldbase = (Local) ifr.getBase();
if (!(oldbase instanceof FakeJimpleLocal)) {
Local newbase = new FakeJimpleLocal("fakethis", oldbase.getType(), oldbase, this);
Value node = Jimple.v().newInstanceFieldRef(newbase, ifr.getField().makeRef());
EquivalentValue nodeEqVal = new EquivalentValue(node); // fake thisLocal
rvalue = nodeEqVal;
}
} else if (ds.getRightOp() instanceof ArrayRef) // requires special packaging
{
ArrayRef ar = (ArrayRef) ds.getRightOp();
Local oldbase = (Local) ar.getBase();
Value oldindex = ar.getIndex();
if (!(oldbase instanceof FakeJimpleLocal)) {
Local newbase = new FakeJimpleLocal("fakethis", oldbase.getType(), oldbase, this);
Value newindex
= (oldindex instanceof Local) ? new FakeJimpleLocal("fakeindex", oldindex.getType(), (Local) oldindex, this)
: oldindex;
Value node = Jimple.v().newArrayRef(newbase, newindex);
EquivalentValue nodeEqVal = new EquivalentValue(node); // fake thisLocal
rvalue = nodeEqVal;
}
}
// Perform merging, unmerging, additions, and subtractions to flowset
if (out.containsKey(lvalue)) {
Integer lvaluevalue = out.get(lvalue);
if (stmt instanceof IdentityStmt) {
if (out.containsKey(rvalue)) {
// Merge the two groups
Integer rvaluevalue = out.get(rvalue);
// every entry in 'out' with the left value gets the right value
for (Map.Entry<?, Integer> entry : out.entrySet()) {
if (entry.getValue() == lvaluevalue) {
entry.setValue(rvaluevalue);
}
}
// every entry in refToBaseGroup with the left value gets the right value
for (Map.Entry<?, Integer> entry : outInfo.refToBaseGroup.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == lvaluevalue) {
entry.setValue(rvaluevalue);
}
}
// every entry in refToIndexGroup with the left value gets the right value
for (Map.Entry<?, Integer> entry : outInfo.refToIndexGroup.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == lvaluevalue) {
entry.setValue(rvaluevalue);
}
}
} else {
out.put(rvalue, lvaluevalue);
}
} else // if( !(lvalue.getValue() instanceof StaticFieldRef && !(lvalue.getValue().getType() instanceof RefLikeType))
// )
{
if (out.containsKey(rvalue)) {
// Merge the two groups
Integer rvaluevalue = out.get(rvalue);
// every entry in 'out' with the left value gets the right value
for (Map.Entry<?, Integer> entry : out.entrySet()) {
if (entry.getValue() == lvaluevalue) {
entry.setValue(rvaluevalue);
}
}
// every entry in refToBaseGroup with the left value gets the right value
for (Map.Entry<?, Integer> entry : outInfo.refToBaseGroup.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == lvaluevalue) {
entry.setValue(rvaluevalue);
}
}
// every entry in refToIndexGroup with the left value gets the right value
for (Map.Entry<?, Integer> entry : outInfo.refToIndexGroup.entrySet()) {
// if the current value == oldvalue, change it to newvalue
if (entry.getValue() == lvaluevalue) {
entry.setValue(rvaluevalue);
}
}
} else {
if (rvalue.getValue() instanceof Local || rvalue.getValue() instanceof StaticFieldRef
|| rvalue.getValue() instanceof Constant) {
out.put(rvalue, lvaluevalue); // value not lost
} else if (rvalue.getValue() instanceof InstanceFieldRef) {
// value is not lost, but it is now dependant on both fieldref and base
// rvalue has already been packaged w/ a fakethis
InstanceFieldRef ifr = (InstanceFieldRef) rvalue.getValue();
FakeJimpleLocal newbase = (FakeJimpleLocal) ifr.getBase();
Local oldbase = newbase.getRealLocal();
out.put(rvalue, lvaluevalue);
Integer baseGroup;
if (out.containsKey(new EquivalentValue(oldbase))) {
baseGroup = out.get(new EquivalentValue(oldbase));
} else {
baseGroup = new Integer(-(groupNum++));
}
if (!outInfo.refToBaseGroup.containsKey(ifr)) {
outInfo.refToBaseGroup.put(ifr, baseGroup); // track relationship between ref and base group
}
out.put(new EquivalentValue(oldbase), baseGroup); // track base group, no lock required
} else if (rvalue.getValue() instanceof ArrayRef) {
// value is not lost, but it is now dependant on all of arrayref, base, and index
// we need to somehow note that, if used as a lock, arrayref's base and index must come from the new groups we
// create here
ArrayRef ar = (ArrayRef) rvalue.getValue();
FakeJimpleLocal newbase = (FakeJimpleLocal) ar.getBase();
Local oldbase = newbase.getRealLocal();
FakeJimpleLocal newindex = (ar.getIndex() instanceof FakeJimpleLocal) ? (FakeJimpleLocal) ar.getIndex() : null;
Value oldindex = (newindex != null) ? (Value) newindex.getRealLocal() : ar.getIndex(); // it's a FJL or a
// Constant
out.put(rvalue, lvaluevalue);
Integer indexGroup;
if (out.containsKey(new EquivalentValue(oldindex))) {
indexGroup = out.get(new EquivalentValue(oldindex));
} else {
indexGroup = new Integer(-(groupNum++));
}
if (!outInfo.refToIndexGroup.containsKey(ar)) {
outInfo.refToIndexGroup.put(ar, indexGroup); // track relationship between ref and index group
}
out.put(new EquivalentValue(oldindex), indexGroup); // track index group, no lock required
Integer baseGroup;
if (out.containsKey(new EquivalentValue(oldbase))) {
baseGroup = out.get(new EquivalentValue(oldbase));
} else {
baseGroup = new Integer(-(groupNum++));
}
if (!outInfo.refToBaseGroup.containsKey(ar)) {
outInfo.refToBaseGroup.put(ar, baseGroup); // track relationship between ref and base group
}
out.put(new EquivalentValue(oldbase), baseGroup); // track base group, no lock required
} else if (rvalue.getValue() instanceof AnyNewExpr) // value doesn't need locking!
{
// ok to lose these values
printMsg("Ignored Object (assigned new value) at " + stmt);
} else {
printMsg("Lost Object (assigned unacceptable value) at " + stmt);
lostObjects = true;
}
}
out.remove(lvalue);
}
}
}
}
protected void copy(LocksetFlowInfo sourceInfo, LocksetFlowInfo destInfo) {
destInfo.groups.clear();
destInfo.groups.putAll(sourceInfo.groups);
destInfo.refToBaseGroup.clear();
destInfo.refToBaseGroup.putAll(sourceInfo.refToBaseGroup);
destInfo.refToIndexGroup.clear();
destInfo.refToIndexGroup.putAll(sourceInfo.refToIndexGroup);
}
protected LocksetFlowInfo newInitialFlow() {
return new LocksetFlowInfo();
}
}
class LocksetFlowInfo {
public Map<EquivalentValue, Integer> groups; // map from each value to a value number
// These two maps track the relationship between array & field refs
// and the base & index groups they come from
public Map<Ref, Integer> refToBaseGroup; // map from ArrayRef or InstanceFieldRef to base group number
public Map<Ref, Integer> refToIndexGroup; // map from ArrayRef to index group number
public LocksetFlowInfo() {
groups = new HashMap<EquivalentValue, Integer>();
refToBaseGroup = new HashMap<Ref, Integer>();
refToIndexGroup = new HashMap<Ref, Integer>();
}
public Object clone() {
LocksetFlowInfo ret = new LocksetFlowInfo();
ret.groups.putAll(groups);
ret.refToBaseGroup.putAll(refToBaseGroup);
ret.refToIndexGroup.putAll(refToIndexGroup);
return ret;
}
public int hashCode() {
return groups.hashCode(); // + refToBaseGroup.keySet().hashCode() + refToIndexGroup.keySet().hashCode();
}
public boolean equals(Object o) {
if (o instanceof LocksetFlowInfo) {
LocksetFlowInfo other = (LocksetFlowInfo) o;
return groups.equals(other.groups);
// &&
// refToBaseGroup.keySet().equals(other.refToBaseGroup.keySet()) &&
// refToIndexGroup.keySet().equals(other.refToIndexGroup.keySet());
}
return false;
}
}
| 34,615
| 39.392065
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/NewStaticLock.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%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.Collections;
import java.util.List;
import soot.NullType;
import soot.SootClass;
import soot.Type;
import soot.UnitPrinter;
import soot.Value;
import soot.ValueBox;
import soot.util.Switch;
// Written by Richard L. Halpert on August 11, 2007
// Acts as a dummy value that gets put in a transaction's lockset,
// indicating that a new static object needs to be inserted into the
// program for use as a lock.
public class NewStaticLock implements Value {
SootClass sc; // The class to which to add a static lock.
static int nextidnum = 1;
int idnum;
public NewStaticLock(SootClass sc) {
this.sc = sc;
this.idnum = nextidnum++;
}
public SootClass getLockClass() {
return sc;
}
@Override
public List<ValueBox> getUseBoxes() {
return Collections.emptyList();
}
/** Clones the object. Not implemented here. */
public Object clone() {
return new NewStaticLock(sc);
}
/**
* Returns true if this object is structurally equivalent to c. AbstractDataSources are equal and equivalent if their
* sourcename is the same
*/
public boolean equivTo(Object c) {
return equals(c);
}
public boolean equals(Object c) {
if (c instanceof NewStaticLock) {
return ((NewStaticLock) c).idnum == idnum;
}
return false;
}
/** Returns a hash code consistent with structural equality for this object. */
public int equivHashCode() {
return hashCode();
}
public int hashCode() {
return idnum;
}
public void toString(UnitPrinter up) {
}
public Type getType() {
return NullType.v();
}
public void apply(Switch sw) {
throw new RuntimeException("Not Implemented");
}
public String toString() {
return "<new static lock in " + sc.toString() + ">";
}
}
| 2,654
| 24.285714
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/StrayRWFinder.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.Body;
import soot.G;
import soot.Scene;
import soot.Unit;
import soot.jimple.Stmt;
import soot.jimple.toolkits.pointer.FullObjectSet;
import soot.jimple.toolkits.pointer.RWSet;
import soot.jimple.toolkits.pointer.SideEffectAnalysis;
import soot.jimple.toolkits.pointer.Union;
import soot.jimple.toolkits.pointer.UnionFactory;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.BackwardFlowAnalysis;
import soot.toolkits.scalar.FlowSet;
/**
* @author Richard L. Halpert StrayRWFinder - Analysis to locate reads/writes to shared data that appear outside
* synchronization
*/
public class StrayRWFinder extends BackwardFlowAnalysis {
FlowSet emptySet = new ArraySparseSet();
Map unitToGenerateSet;
Body body;
SideEffectAnalysis sea;
List tns;
StrayRWFinder(UnitGraph graph, Body b, List tns) {
super(graph);
body = b;
this.tns = tns;
if (G.v().Union_factory == null) {
G.v().Union_factory = new UnionFactory() {
public Union newUnion() {
return FullObjectSet.v();
}
};
}
sea = Scene.v().getSideEffectAnalysis();
sea.findNTRWSets(body.getMethod());
doAnalysis();
}
/**
* All INs are initialized to the empty set.
**/
protected Object newInitialFlow() {
return emptySet.clone();
}
/**
* IN(Start) is the empty set
**/
protected Object entryInitialFlow() {
return emptySet.clone();
}
/**
* OUT is the same as (IN minus killSet) plus the genSet.
**/
protected void flowThrough(Object inValue, Object unit, Object outValue) {
FlowSet in = (FlowSet) inValue, out = (FlowSet) outValue;
RWSet stmtRead = sea.readSet(body.getMethod(), (Stmt) unit);
RWSet stmtWrite = sea.writeSet(body.getMethod(), (Stmt) unit);
Boolean addSelf = Boolean.FALSE;
Iterator tnIt = tns.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = (CriticalSection) tnIt.next();
if (stmtRead.hasNonEmptyIntersection(tn.write) || stmtWrite.hasNonEmptyIntersection(tn.read)
|| stmtWrite.hasNonEmptyIntersection(tn.write)) {
addSelf = Boolean.TRUE;
}
}
in.copy(out);
if (addSelf.booleanValue()) {
CriticalSection tn = new CriticalSection(false, body.getMethod(), 0);
tn.entermonitor = (Stmt) unit;
tn.units.add((Unit) unit);
tn.read.union(stmtRead);
tn.write.union(stmtWrite);
out.add(tn);
}
}
/**
* union, except for transactions in progress. They get joined
**/
protected void merge(Object in1, Object in2, Object out) {
FlowSet inSet1 = ((FlowSet) in1).clone(), inSet2 = ((FlowSet) in2).clone(), outSet = (FlowSet) out;
/*
* boolean hasANull1 = false; Transaction tn1 = null; Iterator inIt1 = inSet1.iterator(); while(inIt1.hasNext()) { tn1 =
* (Transaction) inIt1.next(); if(tn1.entermonitor == null) { hasANull1 = true; break; } }
*
* boolean hasANull2 = false; Transaction tn2 = null; Iterator inIt2 = inSet2.iterator(); while(inIt2.hasNext()) { tn2 =
* (Transaction) inIt2.next(); if(tn2.entermonitor == null) { hasANull2 = true; break; } } if(hasANull1 && hasANull2) {
* inSet1.remove(tn1); Iterator itends = tn1.exitmonitors.iterator(); while(itends.hasNext()) { Stmt stmt = (Stmt)
* itends.next(); if(!tn2.exitmonitors.contains(stmt)) tn2.exitmonitors.add(stmt); } tn2.read.union(tn1.read);
* tn2.write.union(tn1.write); }
*/
inSet1.union(inSet2, outSet);
}
protected void copy(Object source, Object dest) {
FlowSet sourceSet = (FlowSet) source, destSet = (FlowSet) dest;
sourceSet.copy(destSet);
}
}
| 4,631
| 32.085714
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/SynchronizedRegion.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import soot.jimple.Stmt;
import soot.toolkits.scalar.Pair;
public class SynchronizedRegion {
public Stmt prepStmt;
public Stmt entermonitor;
public Stmt beginning; // first stmt of body
public List<Pair<Stmt, Stmt>> earlyEnds; // list of <return/branch stmt, exitmonitor> pairs
public Pair<Stmt, Stmt> exceptionalEnd; // <throw stmt, exitmonitor> pair
public Pair<Stmt, Stmt> end; // <goto stmt, exitmonitor> pair
public Stmt last; // the last stmt before exception handling (usually a goto, return, or branch stmt from one of the ends)
public Stmt after;
public SynchronizedRegion() {
this.prepStmt = null;
this.entermonitor = null;
this.beginning = null;
this.earlyEnds = new ArrayList<Pair<Stmt, Stmt>>();
this.exceptionalEnd = null;
this.end = null;
this.last = null;
this.after = null;
}
public SynchronizedRegion(SynchronizedRegion sr) {
this.prepStmt = sr.prepStmt;
this.entermonitor = sr.entermonitor;
this.beginning = sr.beginning;
this.earlyEnds = new ArrayList<Pair<Stmt, Stmt>>();
this.earlyEnds.addAll(sr.earlyEnds);
this.exceptionalEnd = null;
this.end = sr.end;
this.last = sr.last;
this.after = sr.after;
}
protected Object clone() {
return new SynchronizedRegion(this);
}
}
| 2,219
| 31.647059
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/SynchronizedRegionFinder.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.AssignStmt;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.GotoStmt;
import soot.jimple.JimpleBody;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.internal.JNopStmt;
import soot.jimple.toolkits.pointer.FullObjectSet;
import soot.jimple.toolkits.pointer.RWSet;
import soot.jimple.toolkits.pointer.Union;
import soot.jimple.toolkits.pointer.UnionFactory;
import soot.jimple.toolkits.thread.ThreadLocalObjectsAnalysis;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
import soot.toolkits.scalar.LocalUses;
import soot.toolkits.scalar.Pair;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
/**
* @author Richard L. Halpert Finds Synchronized Regions and creates a set of CriticalSection objects from them.
*/
public class SynchronizedRegionFinder extends ForwardFlowAnalysis<Unit, FlowSet<SynchronizedRegionFlowPair>> {
private static final Logger logger = LoggerFactory.getLogger(SynchronizedRegionFinder.class);
FlowSet<SynchronizedRegionFlowPair> emptySet = new ArraySparseSet<SynchronizedRegionFlowPair>();
Map unitToGenerateSet;
Body body;
Chain<Unit> units;
SootMethod method;
ExceptionalUnitGraph egraph;
LocalUses slu;
CriticalSectionAwareSideEffectAnalysis tasea;
// SideEffectAnalysis sea;
List<Object> prepUnits;
CriticalSection methodTn;
public boolean optionPrintDebug = false;
public boolean optionOpenNesting = true;
SynchronizedRegionFinder(UnitGraph graph, Body b, boolean optionPrintDebug, boolean optionOpenNesting,
ThreadLocalObjectsAnalysis tlo) {
super(graph);
this.optionPrintDebug = optionPrintDebug;
this.optionOpenNesting = optionOpenNesting;
body = b;
units = b.getUnits();
method = body.getMethod();
if (graph instanceof ExceptionalUnitGraph) {
egraph = (ExceptionalUnitGraph) graph;
} else {
egraph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b);
}
slu = LocalUses.Factory.newLocalUses(egraph);
if (G.v().Union_factory == null) {
G.v().Union_factory = new UnionFactory() {
public Union newUnion() {
return FullObjectSet.v();
}
};
}
tasea = new CriticalSectionAwareSideEffectAnalysis(Scene.v().getPointsToAnalysis(), Scene.v().getCallGraph(), null, tlo);
prepUnits = new ArrayList<Object>();
methodTn = null;
if (method.isSynchronized()) {
// Entire method is transactional
methodTn = new CriticalSection(true, method, 1);
methodTn.beginning = ((JimpleBody) body).getFirstNonIdentityStmt();
}
doAnalysis();
if (method.isSynchronized() && methodTn != null) {
for (Iterator<Unit> tailIt = graph.getTails().iterator(); tailIt.hasNext();) {
Stmt tail = (Stmt) tailIt.next();
methodTn.earlyEnds.add(new Pair(tail, null)); // has no exitmonitor stmt yet
}
}
}
/**
* All INs are initialized to the empty set.
**/
protected FlowSet<SynchronizedRegionFlowPair> newInitialFlow() {
FlowSet<SynchronizedRegionFlowPair> ret = emptySet.clone();
if (method.isSynchronized() && methodTn != null) {
ret.add(new SynchronizedRegionFlowPair(methodTn, true));
}
return ret;
}
/**
* OUT is the same as (IN minus killSet) plus the genSet.
**/
protected void flowThrough(FlowSet<SynchronizedRegionFlowPair> in, Unit unit, FlowSet<SynchronizedRegionFlowPair> out) {
Stmt stmt = (Stmt) unit;
copy(in, out);
// Determine if this statement is a preparatory statement for an
// upcoming transactional region. Such a statement would be a definition
// which contains no invoke statement, and which corresponds only to
// EnterMonitorStmt and ExitMonitorStmt uses. In this case, the read
// set of this statement should not be considered part of the read set
// of any containing transaction
if (unit instanceof AssignStmt) {
boolean isPrep = true;
Iterator<UnitValueBoxPair> uses = slu.getUsesOf((Unit) unit).iterator();
if (!uses.hasNext()) {
isPrep = false;
}
while (uses.hasNext()) {
UnitValueBoxPair use = uses.next();
Unit useStmt = use.getUnit();
if (!(useStmt instanceof EnterMonitorStmt) && !(useStmt instanceof ExitMonitorStmt)) {
isPrep = false;
break;
}
}
if (isPrep) {
prepUnits.add(unit);
if (optionPrintDebug) {
logger.debug("prep: " + unit.toString());
}
return;
}
}
// Determine if this statement is the start of a transaction
boolean addSelf = (unit instanceof EnterMonitorStmt);
// Determine the level of transaction nesting of this statement
int nestLevel = 0;
Iterator<SynchronizedRegionFlowPair> outIt0 = out.iterator();
while (outIt0.hasNext()) {
SynchronizedRegionFlowPair srfp = outIt0.next();
if (srfp.tn.nestLevel > nestLevel && srfp.inside == true) {
nestLevel = srfp.tn.nestLevel;
}
}
// Process this unit's effect on each txn
RWSet stmtRead = null;
RWSet stmtWrite = null;
Iterator outIt = out.iterator();
boolean printed = false;
while (outIt.hasNext()) {
SynchronizedRegionFlowPair srfp = (SynchronizedRegionFlowPair) outIt.next();
CriticalSection tn = srfp.tn;
// Check if we are revisting the start of this existing transaction
if (tn.entermonitor == stmt) {
srfp.inside = true;
addSelf = false; // this transaction already exists...
}
// if this is the immediately enclosing transaction
if (srfp.inside == true && (tn.nestLevel == nestLevel || optionOpenNesting == false)) {
printed = true; // for debugging purposes, indicated that we'll print a debug output for this statement
// Add this unit to the current transactional region
if (!tn.units.contains(unit)) {
tn.units.add(unit);
}
// Check what kind of statement this is
// If it contains an invoke, save it for later processing as part of this transaction
// If it is a monitorexit, mark that it's the end of the transaction
// Otherwise, add it's read/write sets to the transaction's read/write sets
if (stmt.containsInvokeExpr()) {
// Note if this unit is a call to wait() or notify()/notifyAll()
String InvokeSig = stmt.getInvokeExpr().getMethod().getSubSignature();
if ((InvokeSig.equals("void notify()") || InvokeSig.equals("void notifyAll()")) && tn.nestLevel == nestLevel)
// only
// applies
// to
// outermost
// txn
{
if (!tn.notifys.contains(unit)) {
tn.notifys.add(unit);
}
if (optionPrintDebug) {
logger.debug("{x,x} ");
}
} else if ((InvokeSig.equals("void wait()") || InvokeSig.equals("void wait(long)")
|| InvokeSig.equals("void wait(long,int)")) && tn.nestLevel == nestLevel) // only applies to outermost txn
{
if (!tn.waits.contains(unit)) {
tn.waits.add(unit);
}
if (optionPrintDebug) {
logger.debug("{x,x} ");
}
}
if (!tn.invokes.contains(unit)) {
// Mark this unit for later read/write set calculation (must be deferred until all tns have been found)
tn.invokes.add(unit);
// Debug Output
if (optionPrintDebug) {
stmtRead = tasea.readSet(tn.method, stmt, tn, new HashSet());
stmtWrite = tasea.writeSet(tn.method, stmt, tn, new HashSet());
logger.debug("{");
if (stmtRead != null) {
logger.debug("" + ((stmtRead.getGlobals() != null ? stmtRead.getGlobals().size() : 0)
+ (stmtRead.getFields() != null ? stmtRead.getFields().size() : 0)));
} else {
logger.debug("" + "0");
}
logger.debug(",");
if (stmtWrite != null) {
logger.debug("" + ((stmtWrite.getGlobals() != null ? stmtWrite.getGlobals().size() : 0)
+ (stmtWrite.getFields() != null ? stmtWrite.getFields().size() : 0)));
} else {
logger.debug("" + "0");
}
logger.debug("} ");
}
}
} else if (unit instanceof ExitMonitorStmt && tn.nestLevel == nestLevel) // only applies to outermost txn
{
// Mark this as end of this tn
srfp.inside = false;
// Check if this is an early end or fallthrough end
Stmt nextUnit = stmt;
do {
nextUnit = (Stmt) units.getSuccOf(nextUnit);
} while (nextUnit instanceof JNopStmt);
if (nextUnit instanceof ReturnStmt || nextUnit instanceof ReturnVoidStmt || nextUnit instanceof ExitMonitorStmt) {
tn.earlyEnds.add(new Pair(nextUnit, stmt)); // <early end stmt, exitmonitor stmt>
} else if (nextUnit instanceof GotoStmt) {
tn.end = new Pair(nextUnit, stmt); // <end stmt, exitmonitor stmt>
tn.after = (Stmt) ((GotoStmt) nextUnit).getTarget();
} else if (nextUnit instanceof ThrowStmt) {
tn.exceptionalEnd = new Pair(nextUnit, stmt);
} else {
throw new RuntimeException(
"Unknown bytecode pattern: exitmonitor not followed by return, exitmonitor, goto, or throw");
}
if (optionPrintDebug) {
logger.debug("[0,0] ");
}
} else {
// Add this unit's read and write sets to this transactional region
HashSet uses = new HashSet();
stmtRead = tasea.readSet(method, stmt, tn, uses);
stmtWrite = tasea.writeSet(method, stmt, tn, uses);
tn.read.union(stmtRead);
tn.write.union(stmtWrite);
// Debug Output
if (optionPrintDebug) {
logger.debug("[");
if (stmtRead != null) {
logger.debug("" + ((stmtRead.getGlobals() != null ? stmtRead.getGlobals().size() : 0)
+ (stmtRead.getFields() != null ? stmtRead.getFields().size() : 0)));
} else {
logger.debug("" + "0");
}
logger.debug(",");
if (stmtWrite != null) {
logger.debug("" + ((stmtWrite.getGlobals() != null ? stmtWrite.getGlobals().size() : 0)
+ (stmtWrite.getFields() != null ? stmtWrite.getFields().size() : 0)));
} else {
logger.debug("" + "0");
}
logger.debug("] ");
}
}
}
}
// DEBUG output
if (optionPrintDebug) {
if (!printed) {
logger.debug("[0,0] ");
}
logger.debug("" + unit.toString());
// If this unit is an invoke statement calling a library function and the R/W sets are huge, print out the targets
if (stmt.containsInvokeExpr() && stmt.getInvokeExpr().getMethod().getDeclaringClass().toString().startsWith("java.")
&& stmtRead != null && stmtWrite != null) {
if (stmtRead.size() < 25 && stmtWrite.size() < 25) {
logger.debug(" Read/Write Set for LibInvoke:");
logger.debug("Read Set:(" + stmtRead.size() + ")" + stmtRead.toString().replaceAll("\n", "\n "));
logger.debug("Write Set:(" + stmtWrite.size() + ")" + stmtWrite.toString().replaceAll("\n", "\n "));
}
}
}
// If this statement was a monitorenter, and no transaction object yet exists for it,
// create one.
if (addSelf) {
CriticalSection newTn = new CriticalSection(false, method, nestLevel + 1);
newTn.entermonitor = stmt;
newTn.beginning = (Stmt) units.getSuccOf(stmt);
if (stmt instanceof EnterMonitorStmt) {
newTn.origLock = ((EnterMonitorStmt) stmt).getOp();
}
if (optionPrintDebug) {
logger.debug("Transaction found in method: " + newTn.method.toString());
}
out.add(new SynchronizedRegionFlowPair(newTn, true));
// This is a really stupid way to find out which prep applies to this txn.
Iterator<Object> prepUnitsIt = prepUnits.iterator();
while (prepUnitsIt.hasNext()) {
Unit prepUnit = (Unit) prepUnitsIt.next();
Iterator<UnitValueBoxPair> uses = slu.getUsesOf(prepUnit).iterator();
while (uses.hasNext()) {
UnitValueBoxPair use = (UnitValueBoxPair) uses.next();
if (use.getUnit() == (Unit) unit) { // if this transaction's monitorenter statement is one of the uses of this
// preparatory unit
newTn.prepStmt = (Stmt) prepUnit;
}
}
}
}
}
/**
* union
**/
protected void merge(FlowSet<SynchronizedRegionFlowPair> inSet1, FlowSet<SynchronizedRegionFlowPair> inSet2,
FlowSet<SynchronizedRegionFlowPair> outSet) {
inSet1.union(inSet2, outSet);
}
protected void copy(FlowSet<SynchronizedRegionFlowPair> sourceSet, FlowSet<SynchronizedRegionFlowPair> destSet) {
destSet.clear();
Iterator<SynchronizedRegionFlowPair> it = sourceSet.iterator();
while (it.hasNext()) {
SynchronizedRegionFlowPair tfp = it.next();
destSet.add((SynchronizedRegionFlowPair) tfp.clone());
}
}
}
| 14,943
| 36.174129
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/SynchronizedRegionFlowPair.java
|
package soot.jimple.toolkits.thread.synchronization;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class SynchronizedRegionFlowPair {
private static final Logger logger = LoggerFactory.getLogger(SynchronizedRegionFlowPair.class);
// Information about the transactional region
public CriticalSection tn;
public boolean inside;
SynchronizedRegionFlowPair(CriticalSection tn, boolean inside) {
this.tn = tn;
this.inside = inside;
}
SynchronizedRegionFlowPair(SynchronizedRegionFlowPair tfp) {
this.tn = tfp.tn;
this.inside = tfp.inside;
}
public void copy(SynchronizedRegionFlowPair tfp) {
tfp.tn = this.tn;
tfp.inside = this.inside;
}
public SynchronizedRegionFlowPair clone() {
return new SynchronizedRegionFlowPair(tn, inside);
}
public boolean equals(Object other) {
// logger.debug(".");
if (other instanceof SynchronizedRegionFlowPair) {
SynchronizedRegionFlowPair tfp = (SynchronizedRegionFlowPair) other;
if (this.tn.IDNum == tfp.tn.IDNum) {
return true;
}
}
return false;
}
public String toString() {
return "[" + (inside ? "in," : "out,") + tn.toString() + "]";
}
}
| 2,016
| 28.661765
| 97
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/ClassHierarchy.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.G;
import soot.IntType;
import soot.NullType;
import soot.RefType;
import soot.Scene;
import soot.ShortType;
import soot.Type;
import soot.TypeSwitch;
import soot.options.Options;
/**
* This class encapsulates the typing class hierarchy, as well as non-reference types.
*
* <P>
* This class is primarily used by the TypeResolver class, to optimize its computation.
**/
public class ClassHierarchy {
/** Map: Scene -> ClassHierarchy **/
public final TypeNode OBJECT;
public final TypeNode CLONEABLE;
public final TypeNode SERIALIZABLE;
public final TypeNode NULL;
public final TypeNode INT;
// public final TypeNode UNKNOWN;
// public final TypeNode ERROR;
/** All type node instances **/
private final List<TypeNode> typeNodeList = new ArrayList<TypeNode>();
/** Map: Type -> TypeNode **/
private final HashMap<Type, TypeNode> typeNodeMap = new HashMap<Type, TypeNode>();
/** Used to transform boolean, byte, short and char to int **/
private final ToInt transform = new ToInt();
/** Used to create TypeNode instances **/
private final ConstructorChooser make = new ConstructorChooser();
private ClassHierarchy(Scene scene) {
if (scene == null) {
throw new InternalTypingException();
}
G.v().ClassHierarchy_classHierarchyMap.put(scene, this);
this.NULL = typeNode(NullType.v());
this.OBJECT = typeNode(RefType.v("java.lang.Object"));
// hack for J2ME library which does not have Cloneable and Serializable
// reported by Stephen Chen
if (!Options.v().j2me()) {
this.CLONEABLE = typeNode(RefType.v("java.lang.Cloneable"));
this.SERIALIZABLE = typeNode(RefType.v("java.io.Serializable"));
} else {
this.CLONEABLE = null;
this.SERIALIZABLE = null;
}
this.INT = typeNode(IntType.v());
}
/** Get the class hierarchy for the given scene. **/
public static ClassHierarchy classHierarchy(Scene scene) {
if (scene == null) {
throw new InternalTypingException();
}
ClassHierarchy classHierarchy = G.v().ClassHierarchy_classHierarchyMap.get(scene);
if (classHierarchy == null) {
classHierarchy = new ClassHierarchy(scene);
}
return classHierarchy;
}
/** Get the type node for the given type. **/
public TypeNode typeNode(Type type) {
if (type == null) {
throw new InternalTypingException();
}
type = transform.toInt(type);
TypeNode typeNode = typeNodeMap.get(type);
if (typeNode == null) {
int id = typeNodeList.size();
typeNodeList.add(null);
typeNode = make.typeNode(id, type, this);
typeNodeList.set(id, typeNode);
typeNodeMap.put(type, typeNode);
}
return typeNode;
}
/** Returns a string representation of this object **/
@Override
public String toString() {
StringBuilder s = new StringBuilder("ClassHierarchy:{");
boolean colon = false;
for (TypeNode typeNode : typeNodeList) {
if (colon) {
s.append(',');
} else {
colon = true;
}
s.append(typeNode);
}
s.append('}');
return s.toString();
}
/**
* Transforms boolean, byte, short and char into int.
**/
private static class ToInt extends TypeSwitch<Type> {
private final Type intType = IntType.v();
/** Transform boolean, byte, short and char into int. **/
public Type toInt(Type type) {
type.apply(this);
return getResult();
}
@Override
public void caseBooleanType(BooleanType type) {
setResult(intType);
}
@Override
public void caseByteType(ByteType type) {
setResult(intType);
}
@Override
public void caseShortType(ShortType type) {
setResult(intType);
}
@Override
public void caseCharType(CharType type) {
setResult(intType);
}
@Override
public void defaultCase(Type type) {
setResult(type);
}
}
/**
* Creates new TypeNode instances usign the appropriate constructor.
**/
private static class ConstructorChooser extends TypeSwitch<TypeNode> {
private int id;
private ClassHierarchy hierarchy;
/** Create a new TypeNode instance for the type parameter. **/
public TypeNode typeNode(int id, Type type, ClassHierarchy hierarchy) {
if (type == null || hierarchy == null) {
throw new InternalTypingException();
}
this.id = id;
this.hierarchy = hierarchy;
type.apply(this);
return getResult();
}
@Override
public void caseRefType(RefType type) {
setResult(new TypeNode(id, type, hierarchy));
}
@Override
public void caseArrayType(ArrayType type) {
setResult(new TypeNode(id, type, hierarchy));
}
@Override
public void defaultCase(Type type) {
setResult(new TypeNode(id, type, hierarchy));
}
}
}
| 5,883
| 25.267857
| 87
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/ConstraintChecker.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LocalGenerator;
import soot.LongType;
import soot.NullType;
import soot.RefType;
import soot.Scene;
import soot.SootMethodRef;
import soot.TrapManager;
import soot.Type;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.DynamicInvokeExpr;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.XorExpr;
class ConstraintChecker extends AbstractStmtSwitch {
private static final Logger logger = LoggerFactory.getLogger(ConstraintChecker.class);
private final ClassHierarchy hierarchy;
private final boolean fix; // if true, fix constraint violations
private JimpleBody stmtBody;
private LocalGenerator localGenerator;
public ConstraintChecker(TypeResolver resolver, boolean fix) {
this.fix = fix;
this.hierarchy = resolver.hierarchy();
}
public void check(Stmt stmt, JimpleBody stmtBody) throws TypeException {
try {
this.stmtBody = stmtBody;
this.localGenerator = Scene.v().createLocalGenerator(stmtBody);
stmt.apply(this);
} catch (RuntimeTypeException e) {
logger.error(e.getMessage(), e);
throw new TypeException(e.getMessage(), e);
}
}
@SuppressWarnings("serial")
private static class RuntimeTypeException extends RuntimeException {
RuntimeTypeException(String message) {
super(message);
}
}
static void error(String message) {
throw new RuntimeTypeException(message);
}
private void handleInvokeExpr(InvokeExpr ie, Stmt invokestmt) {
// Handle the parameters
SootMethodRef method = ie.getMethodRef();
for (int i = 0; i < ie.getArgCount(); i++) {
Value arg = ie.getArg(i);
if (arg instanceof Local) {
Local local = (Local) arg;
Type parameterType = method.getParameterType(i);
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(parameterType))) {
if (fix) {
ie.setArg(i, insertCast(local, parameterType, invokestmt));
} else {
error("Type Error");
}
}
}
}
if (ie instanceof InterfaceInvokeExpr) {
InterfaceInvokeExpr invoke = (InterfaceInvokeExpr) ie;
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
RefType classType = method.getDeclaringClass().getType();
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(classType))) {
if (fix) {
invoke.setBase(insertCast(local, classType, invokestmt));
} else {
error("Type Error(7): local " + local + " is of incompatible type " + local.getType());
}
}
}
} else if (ie instanceof SpecialInvokeExpr) {
SpecialInvokeExpr invoke = (SpecialInvokeExpr) ie;
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
RefType classType = method.getDeclaringClass().getType();
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(classType))) {
if (fix) {
invoke.setBase(insertCast(local, classType, invokestmt));
} else {
error("Type Error(9)");
}
}
}
} else if (ie instanceof VirtualInvokeExpr) {
VirtualInvokeExpr invoke = (VirtualInvokeExpr) ie;
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
RefType classType = method.getDeclaringClass().getType();
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(classType))) {
if (fix) {
invoke.setBase(insertCast(local, classType, invokestmt));
} else {
error("Type Error(13)");
}
}
}
} else if (ie instanceof StaticInvokeExpr) {
// No base to handle
} else if (ie instanceof DynamicInvokeExpr) {
DynamicInvokeExpr die = (DynamicInvokeExpr) ie;
SootMethodRef bootstrapMethod = die.getMethodRef();
for (int i = 0; i < die.getBootstrapArgCount(); i++) {
if (die.getBootstrapArg(i) instanceof Local) {
Local local = (Local) die.getBootstrapArg(i);
Type parameterType = bootstrapMethod.getParameterType(i);
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(parameterType))) {
if (fix) {
ie.setArg(i, insertCast(local, parameterType, invokestmt));
} else {
error("Type Error");
}
}
}
}
} else {
throw new RuntimeException("Unhandled invoke expression type: " + ie.getClass());
}
}
@Override
public void caseBreakpointStmt(BreakpointStmt stmt) {
// Do nothing
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
handleInvokeExpr(stmt.getInvokeExpr(), stmt);
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
final Value l = stmt.getLeftOp();
final Value r = stmt.getRightOp();
TypeNode left = null;
// ******** LEFT ********
if (l instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) l;
TypeNode base = hierarchy.typeNode(((Local) ref.getBase()).getType());
if (!base.isArray()) {
error("Type Error(16)");
}
left = base.element();
Value index = ref.getIndex();
if (index instanceof Local) {
if (!hierarchy.typeNode(((Local) index).getType()).hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(17)");
}
}
} else if (l instanceof Local) {
try {
left = hierarchy.typeNode(((Local) l).getType());
} catch (InternalTypingException e) {
logger.debug("untyped local: " + l);
throw e;
}
} else if (l instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) l;
Local base = (Local) ref.getBase();
RefType classTy = ref.getField().getDeclaringClass().getType();
if (!hierarchy.typeNode(base.getType()).hasAncestorOrSelf(hierarchy.typeNode(classTy))) {
if (fix) {
ref.setBase(insertCast(base, classTy, stmt));
} else {
error("Type Error(18)");
}
}
left = hierarchy.typeNode(ref.getField().getType());
} else if (l instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) l;
left = hierarchy.typeNode(ref.getField().getType());
} else {
throw new RuntimeException("Unhandled assignment left hand side type: " + l.getClass());
}
// ******** RIGHT ********
if (r instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) r;
Local base = (Local) ref.getBase();
TypeNode baseTy = hierarchy.typeNode((base).getType());
if (!baseTy.isArray()) {
error("Type Error(19): " + baseTy + " is not an array type");
}
if (baseTy == hierarchy.NULL) {
return;
}
if (!left.hasDescendantOrSelf(baseTy.element())) {
if (fix) {
Type lefttype = left.type();
if (lefttype instanceof ArrayType) {
ArrayType atype = (ArrayType) lefttype;
ref.setBase(insertCast(base, ArrayType.v(atype.baseType, atype.numDimensions + 1), stmt));
} else {
ref.setBase(insertCast(base, ArrayType.v(lefttype, 1), stmt));
}
} else {
error("Type Error(20)");
}
}
Value index = ref.getIndex();
if (index instanceof Local) {
if (!hierarchy.typeNode(((Local) index).getType()).hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(21)");
}
}
} else if (r instanceof DoubleConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(DoubleType.v()))) {
error("Type Error(22)");
}
} else if (r instanceof FloatConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(FloatType.v()))) {
error("Type Error(45)");
}
} else if (r instanceof IntConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(23)");
}
} else if (r instanceof LongConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(LongType.v()))) {
error("Type Error(24)");
}
} else if (r instanceof NullConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(NullType.v()))) {
error("Type Error(25)");
}
} else if (r instanceof StringConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(RefType.v("java.lang.String")))) {
error("Type Error(26)");
}
} else if (r instanceof ClassConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(RefType.v("java.lang.Class")))) {
error("Type Error(27)");
}
} else if (r instanceof BinopExpr) {
// ******** BINOP EXPR ********
final BinopExpr be = (BinopExpr) r;
final Value lv = be.getOp1();
final Value rv = be.getOp2();
TypeNode lop;
TypeNode rop;
// ******** LEFT ********
if (lv instanceof Local) {
lop = hierarchy.typeNode(((Local) lv).getType());
} else if (lv instanceof DoubleConstant) {
lop = hierarchy.typeNode(DoubleType.v());
} else if (lv instanceof FloatConstant) {
lop = hierarchy.typeNode(FloatType.v());
} else if (lv instanceof IntConstant) {
lop = hierarchy.typeNode(IntType.v());
} else if (lv instanceof LongConstant) {
lop = hierarchy.typeNode(LongType.v());
} else if (lv instanceof NullConstant) {
lop = hierarchy.typeNode(NullType.v());
} else if (lv instanceof StringConstant) {
lop = hierarchy.typeNode(RefType.v("java.lang.String"));
} else if (lv instanceof ClassConstant) {
lop = hierarchy.typeNode(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
rop = hierarchy.typeNode(((Local) rv).getType());
} else if (rv instanceof DoubleConstant) {
rop = hierarchy.typeNode(DoubleType.v());
} else if (rv instanceof FloatConstant) {
rop = hierarchy.typeNode(FloatType.v());
} else if (rv instanceof IntConstant) {
rop = hierarchy.typeNode(IntType.v());
} else if (rv instanceof LongConstant) {
rop = hierarchy.typeNode(LongType.v());
} else if (rv instanceof NullConstant) {
rop = hierarchy.typeNode(NullType.v());
} else if (rv instanceof StringConstant) {
rop = hierarchy.typeNode(RefType.v("java.lang.String"));
} else if (rv instanceof ClassConstant) {
rop = hierarchy.typeNode(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if ((be instanceof AddExpr) || (be instanceof SubExpr) || (be instanceof MulExpr) || (be instanceof DivExpr)
|| (be instanceof RemExpr) || (be instanceof AndExpr) || (be instanceof OrExpr) || (be instanceof XorExpr)) {
if (!(left.hasDescendantOrSelf(lop) && left.hasDescendantOrSelf(rop))) {
error("Type Error(27)");
}
} else if ((be instanceof ShlExpr) || (be instanceof ShrExpr) || (be instanceof UshrExpr)) {
if (!(left.hasDescendantOrSelf(lop) && hierarchy.typeNode(IntType.v()).hasAncestorOrSelf(rop))) {
error("Type Error(28)");
}
} else if ((be instanceof CmpExpr) || (be instanceof CmpgExpr) || (be instanceof CmplExpr) || (be instanceof EqExpr)
|| (be instanceof GeExpr) || (be instanceof GtExpr) || (be instanceof LeExpr) || (be instanceof LtExpr)
|| (be instanceof NeExpr)) {
try {
lop.lca(rop);
} catch (TypeException e) {
error(e.getMessage());
}
if (!left.hasDescendantOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(29)");
}
} else {
throw new RuntimeException("Unhandled binary expression type: " + be.getClass());
}
} else if (r instanceof CastExpr) {
CastExpr ce = (CastExpr) r;
TypeNode castTy = hierarchy.typeNode(ce.getCastType());
Value op = ce.getOp();
if (op instanceof Local) {
TypeNode opTy = hierarchy.typeNode(((Local) op).getType());
try {
// we must be careful not to reject primitive type casts (e.g. int to long)
if (castTy.isClassOrInterface() || opTy.isClassOrInterface()) {
castTy.lca(opTy);
}
} catch (TypeException e) {
logger.debug(r + "[" + opTy + "<->" + castTy + "]");
error(e.getMessage());
}
}
if (!left.hasDescendantOrSelf(castTy)) {
error("Type Error(30)");
}
} else if (r instanceof InstanceOfExpr) {
InstanceOfExpr ioe = (InstanceOfExpr) r;
TypeNode type = hierarchy.typeNode(ioe.getCheckType());
TypeNode op = hierarchy.typeNode(ioe.getOp().getType());
try {
op.lca(type);
} catch (TypeException e) {
logger.debug(r + "[" + op + "<->" + type + "]");
error(e.getMessage());
}
if (!left.hasDescendantOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(31)");
}
} else if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
handleInvokeExpr(ie, stmt);
if (!left.hasDescendantOrSelf(hierarchy.typeNode(ie.getMethodRef().getReturnType()))) {
error("Type Error(32)");
}
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
Type baseType = nae.getBaseType();
TypeNode right;
if (baseType instanceof ArrayType) {
right = hierarchy.typeNode(ArrayType.v(((ArrayType) baseType).baseType, ((ArrayType) baseType).numDimensions + 1));
} else {
right = hierarchy.typeNode(ArrayType.v(baseType, 1));
}
if (!left.hasDescendantOrSelf(right)) {
error("Type Error(33)");
}
Value size = nae.getSize();
if (size instanceof Local) {
TypeNode var = hierarchy.typeNode(((Local) size).getType());
if (!var.hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(34)");
}
}
} else if (r instanceof NewExpr) {
NewExpr ne = (NewExpr) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(ne.getBaseType()))) {
error("Type Error(35)");
}
} else if (r instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(nmae.getBaseType()))) {
error("Type Error(36)");
}
for (int i = 0; i < nmae.getSizeCount(); i++) {
Value size = nmae.getSize(i);
if (size instanceof Local) {
TypeNode var = hierarchy.typeNode(((Local) size).getType());
if (!var.hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(37)");
}
}
}
} else if (r instanceof LengthExpr) {
LengthExpr le = (LengthExpr) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(38)");
}
Value op = le.getOp();
if (op instanceof Local) {
if (!hierarchy.typeNode(((Local) op).getType()).isArray()) {
error("Type Error(39)");
}
}
} else if (r instanceof NegExpr) {
NegExpr ne = (NegExpr) r;
TypeNode right;
Value op = ne.getOp();
if (op instanceof Local) {
right = hierarchy.typeNode(((Local) op).getType());
} else if (op instanceof DoubleConstant) {
right = hierarchy.typeNode(DoubleType.v());
} else if (op instanceof FloatConstant) {
right = hierarchy.typeNode(FloatType.v());
} else if (op instanceof IntConstant) {
right = hierarchy.typeNode(IntType.v());
} else if (op instanceof LongConstant) {
right = hierarchy.typeNode(LongType.v());
} else {
throw new RuntimeException("Unhandled neg expression operand type: " + op.getClass());
}
if (!left.hasDescendantOrSelf(right)) {
error("Type Error(40)");
}
} else if (r instanceof Local) {
Local loc = (Local) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(loc.getType()))) {
if (fix) {
stmt.setRightOp(insertCast(loc, left.type(), stmt));
} else {
error("Type Error(41)");
}
}
} else if (r instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) r;
Local base = (Local) ref.getBase();
RefType classTy = ref.getField().getDeclaringClass().getType();
if (!hierarchy.typeNode(base.getType()).hasAncestorOrSelf(hierarchy.typeNode(classTy))) {
if (fix) {
ref.setBase(insertCast(base, classTy, stmt));
} else {
error("Type Error(42)");
}
}
if (!left.hasDescendantOrSelf(hierarchy.typeNode(ref.getField().getType()))) {
error("Type Error(43)");
}
} else if (r instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(ref.getField().getType()))) {
error("Type Error(44)");
}
} else {
throw new RuntimeException("Unhandled assignment right hand side type: " + r.getClass());
}
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
TypeNode left = hierarchy.typeNode(((Local) stmt.getLeftOp()).getType());
Value r = stmt.getRightOp();
if (r instanceof CaughtExceptionRef) {
for (Type t : TrapManager.getExceptionTypesOf(stmt, stmtBody)) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(t))) {
error("Type Error(47)");
}
}
if (!left.hasAncestorOrSelf(hierarchy.typeNode(RefType.v("java.lang.Throwable")))) {
error("Type Error(48)");
}
} else {
TypeNode right = hierarchy.typeNode(r.getType());
if (!left.hasDescendantOrSelf(right)) {
error("Type Error(46) [" + left + " <- " + right + "]");
}
}
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
Value op = stmt.getOp();
if (op instanceof Local) {
TypeNode opTy = hierarchy.typeNode(((Local) op).getType());
if (!opTy.hasAncestorOrSelf(hierarchy.typeNode(RefType.v("java.lang.Object")))) {
error("Type Error(49)");
}
}
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
Value op = stmt.getOp();
if (op instanceof Local) {
TypeNode opTy = hierarchy.typeNode(((Local) op).getType());
if (!opTy.hasAncestorOrSelf(hierarchy.typeNode(RefType.v("java.lang.Object")))) {
error("Type Error(49)");
}
}
}
@Override
public void caseGotoStmt(GotoStmt stmt) {
}
@Override
public void caseIfStmt(IfStmt stmt) {
final ConditionExpr expr = (ConditionExpr) stmt.getCondition();
final Value lv = expr.getOp1();
final Value rv = expr.getOp2();
TypeNode lop;
TypeNode rop;
// ******** LEFT ********
if (lv instanceof Local) {
lop = hierarchy.typeNode(((Local) lv).getType());
} else if (lv instanceof DoubleConstant) {
lop = hierarchy.typeNode(DoubleType.v());
} else if (lv instanceof FloatConstant) {
lop = hierarchy.typeNode(FloatType.v());
} else if (lv instanceof IntConstant) {
lop = hierarchy.typeNode(IntType.v());
} else if (lv instanceof LongConstant) {
lop = hierarchy.typeNode(LongType.v());
} else if (lv instanceof NullConstant) {
lop = hierarchy.typeNode(NullType.v());
} else if (lv instanceof StringConstant) {
lop = hierarchy.typeNode(RefType.v("java.lang.String"));
} else if (lv instanceof ClassConstant) {
lop = hierarchy.typeNode(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
rop = hierarchy.typeNode(((Local) rv).getType());
} else if (rv instanceof DoubleConstant) {
rop = hierarchy.typeNode(DoubleType.v());
} else if (rv instanceof FloatConstant) {
rop = hierarchy.typeNode(FloatType.v());
} else if (rv instanceof IntConstant) {
rop = hierarchy.typeNode(IntType.v());
} else if (rv instanceof LongConstant) {
rop = hierarchy.typeNode(LongType.v());
} else if (rv instanceof NullConstant) {
rop = hierarchy.typeNode(NullType.v());
} else if (rv instanceof StringConstant) {
rop = hierarchy.typeNode(RefType.v("java.lang.String"));
} else if (rv instanceof ClassConstant) {
rop = hierarchy.typeNode(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
try {
lop.lca(rop);
} catch (TypeException e) {
error(e.getMessage());
}
}
@Override
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
Value key = stmt.getKey();
if (key instanceof Local) {
if (!hierarchy.typeNode(((Local) key).getType()).hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(50)");
}
}
}
@Override
public void caseNopStmt(NopStmt stmt) {
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
Value op = stmt.getOp();
if (op instanceof Local) {
Local opLocal = (Local) op;
Type returnType = stmtBody.getMethod().getReturnType();
if (!hierarchy.typeNode(opLocal.getType()).hasAncestorOrSelf(hierarchy.typeNode(returnType))) {
if (fix) {
stmt.setOp(insertCast(opLocal, returnType, stmt));
} else {
error("Type Error(51)");
}
}
}
}
@Override
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
@Override
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
Value key = stmt.getKey();
if (key instanceof Local) {
if (!hierarchy.typeNode(((Local) key).getType()).hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(52)");
}
}
}
@Override
public void caseThrowStmt(ThrowStmt stmt) {
Value op = stmt.getOp();
if (op instanceof Local) {
Local opLocal = (Local) op;
TypeNode opTy = hierarchy.typeNode(opLocal.getType());
if (!opTy.hasAncestorOrSelf(hierarchy.typeNode(RefType.v("java.lang.Throwable")))) {
if (fix) {
stmt.setOp(insertCast(opLocal, RefType.v("java.lang.Throwable"), stmt));
} else {
error("Type Error(53)");
}
}
}
}
public void defaultCase(Stmt stmt) {
throw new RuntimeException("Unhandled statement type: " + stmt.getClass());
}
private Local insertCast(Local oldlocal, Type type, Stmt stmt) {
final Jimple jimp = Jimple.v();
Local newlocal = localGenerator.generateLocal(type);
stmtBody.getUnits().insertBefore(jimp.newAssignStmt(newlocal, jimp.newCastExpr(oldlocal, type)),
Util.findFirstNonIdentityUnit(stmtBody, stmt));
return newlocal;
}
}
| 26,296
| 33.646904
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/ConstraintCheckerBV.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.RefType;
import soot.SootMethodRef;
import soot.TrapManager;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.XorExpr;
/**
* @deprecated use {@link soot.jimple.toolkits.typing.fast.TypeResolver} instead
*/
@Deprecated
class ConstraintCheckerBV extends AbstractStmtSwitch {
private static final Logger logger = LoggerFactory.getLogger(ConstraintCheckerBV.class);
private final ClassHierarchy hierarchy;
private final boolean fix; // if true, fix constraint violations
private JimpleBody stmtBody;
public ConstraintCheckerBV(TypeResolverBV resolver, boolean fix) {
this.fix = fix;
hierarchy = resolver.hierarchy();
}
public void check(Stmt stmt, JimpleBody stmtBody) throws TypeException {
try {
this.stmtBody = stmtBody;
stmt.apply(this);
} catch (RuntimeTypeException e) {
StringWriter st = new StringWriter();
PrintWriter pw = new PrintWriter(st);
logger.error(e.getMessage(), e);
pw.close();
throw new TypeException(st.toString());
}
}
@SuppressWarnings("serial")
private static class RuntimeTypeException extends RuntimeException {
RuntimeTypeException(String message) {
super(message);
}
}
static void error(String message) {
throw new RuntimeTypeException(message);
}
private void handleInvokeExpr(InvokeExpr ie, Stmt invokestmt) {
if (ie instanceof InterfaceInvokeExpr) {
InterfaceInvokeExpr invoke = (InterfaceInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(method.declaringClass().getType()))) {
if (fix) {
invoke.setBase(insertCast(local, method.declaringClass().getType(), invokestmt));
} else {
error("Type Error(7): local " + local + " is of incompatible type " + local.getType());
}
}
}
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(method.parameterType(i)))) {
if (fix) {
invoke.setArg(i, insertCast(local, method.parameterType(i), invokestmt));
} else {
error("Type Error(8)");
}
}
}
}
} else if (ie instanceof SpecialInvokeExpr) {
SpecialInvokeExpr invoke = (SpecialInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(method.declaringClass().getType()))) {
if (fix) {
invoke.setBase(insertCast(local, method.declaringClass().getType(), invokestmt));
} else {
error("Type Error(9)");
}
}
}
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(method.parameterType(i)))) {
if (fix) {
invoke.setArg(i, insertCast(local, method.parameterType(i), invokestmt));
} else {
error("Type Error(10)");
}
}
}
}
} else if (ie instanceof VirtualInvokeExpr) {
VirtualInvokeExpr invoke = (VirtualInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(method.declaringClass().getType()))) {
if (fix) {
invoke.setBase(insertCast(local, method.declaringClass().getType(), invokestmt));
} else {
error("Type Error(13)");
}
}
}
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(method.parameterType(i)))) {
if (fix) {
invoke.setArg(i, insertCast(local, method.parameterType(i), invokestmt));
} else {
error("Type Error(14)");
}
}
}
}
} else if (ie instanceof StaticInvokeExpr) {
StaticInvokeExpr invoke = (StaticInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
if (!hierarchy.typeNode(local.getType()).hasAncestorOrSelf(hierarchy.typeNode(method.parameterType(i)))) {
if (fix) {
invoke.setArg(i, insertCast(local, method.parameterType(i), invokestmt));
} else {
error("Type Error(15)");
}
}
}
}
} else {
throw new RuntimeException("Unhandled invoke expression type: " + ie.getClass());
}
}
public void caseBreakpointStmt(BreakpointStmt stmt) {
// Do nothing
}
public void caseInvokeStmt(InvokeStmt stmt) {
handleInvokeExpr(stmt.getInvokeExpr(), stmt);
}
public void caseAssignStmt(AssignStmt stmt) {
Value l = stmt.getLeftOp();
Value r = stmt.getRightOp();
TypeNode left = null;
// ******** LEFT ********
if (l instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) l;
TypeNode base = hierarchy.typeNode(((Local) ref.getBase()).getType());
if (!base.isArray()) {
error("Type Error(16)");
}
left = base.element();
Value index = ref.getIndex();
if (index instanceof Local) {
if (!hierarchy.typeNode(((Local) index).getType()).hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(17)");
}
}
} else if (l instanceof Local) {
try {
left = hierarchy.typeNode(((Local) l).getType());
} catch (InternalTypingException e) {
logger.debug("untyped local: " + l);
throw e;
}
} else if (l instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) l;
TypeNode base = hierarchy.typeNode(((Local) ref.getBase()).getType());
if (!base.hasAncestorOrSelf(hierarchy.typeNode(ref.getField().getDeclaringClass().getType()))) {
if (fix) {
ref.setBase(insertCast((Local) ref.getBase(), ref.getField().getDeclaringClass().getType(), stmt));
} else {
error("Type Error(18)");
}
}
left = hierarchy.typeNode(ref.getField().getType());
} else if (l instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) l;
left = hierarchy.typeNode(ref.getField().getType());
} else {
throw new RuntimeException("Unhandled assignment left hand side type: " + l.getClass());
}
// ******** RIGHT ********
if (r instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) r;
TypeNode base = hierarchy.typeNode(((Local) ref.getBase()).getType());
if (!base.isArray()) {
error("Type Error(19): " + base + " is not an array type");
}
if (base == hierarchy.NULL) {
return;
}
if (!left.hasDescendantOrSelf(base.element())) {
if (fix) {
Type lefttype = left.type();
if (lefttype instanceof ArrayType) {
ArrayType atype = (ArrayType) lefttype;
ref.setBase(insertCast((Local) ref.getBase(), ArrayType.v(atype.baseType, atype.numDimensions + 1), stmt));
} else {
ref.setBase(insertCast((Local) ref.getBase(), ArrayType.v(lefttype, 1), stmt));
}
} else {
error("Type Error(20)");
}
}
Value index = ref.getIndex();
if (index instanceof Local) {
if (!hierarchy.typeNode(((Local) index).getType()).hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(21)");
}
}
} else if (r instanceof DoubleConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(DoubleType.v()))) {
error("Type Error(22)");
}
} else if (r instanceof FloatConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(FloatType.v()))) {
error("Type Error(45)");
}
} else if (r instanceof IntConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(23)");
}
} else if (r instanceof LongConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(LongType.v()))) {
error("Type Error(24)");
}
} else if (r instanceof NullConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(NullType.v()))) {
error("Type Error(25)");
}
} else if (r instanceof StringConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(RefType.v("java.lang.String")))) {
error("Type Error(26)");
}
} else if (r instanceof ClassConstant) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(RefType.v("java.lang.Class")))) {
error("Type Error(27)");
}
} else if (r instanceof BinopExpr) {
// ******** BINOP EXPR ********
BinopExpr be = (BinopExpr) r;
Value lv = be.getOp1();
Value rv = be.getOp2();
TypeNode lop;
TypeNode rop;
// ******** LEFT ********
if (lv instanceof Local) {
lop = hierarchy.typeNode(((Local) lv).getType());
} else if (lv instanceof DoubleConstant) {
lop = hierarchy.typeNode(DoubleType.v());
} else if (lv instanceof FloatConstant) {
lop = hierarchy.typeNode(FloatType.v());
} else if (lv instanceof IntConstant) {
lop = hierarchy.typeNode(IntType.v());
} else if (lv instanceof LongConstant) {
lop = hierarchy.typeNode(LongType.v());
} else if (lv instanceof NullConstant) {
lop = hierarchy.typeNode(NullType.v());
} else if (lv instanceof StringConstant) {
lop = hierarchy.typeNode(RefType.v("java.lang.String"));
} else if (lv instanceof ClassConstant) {
lop = hierarchy.typeNode(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
rop = hierarchy.typeNode(((Local) rv).getType());
} else if (rv instanceof DoubleConstant) {
rop = hierarchy.typeNode(DoubleType.v());
} else if (rv instanceof FloatConstant) {
rop = hierarchy.typeNode(FloatType.v());
} else if (rv instanceof IntConstant) {
rop = hierarchy.typeNode(IntType.v());
} else if (rv instanceof LongConstant) {
rop = hierarchy.typeNode(LongType.v());
} else if (rv instanceof NullConstant) {
rop = hierarchy.typeNode(NullType.v());
} else if (rv instanceof StringConstant) {
rop = hierarchy.typeNode(RefType.v("java.lang.String"));
} else if (rv instanceof ClassConstant) {
rop = hierarchy.typeNode(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if ((be instanceof AddExpr) || (be instanceof SubExpr) || (be instanceof MulExpr) || (be instanceof DivExpr)
|| (be instanceof RemExpr) || (be instanceof AndExpr) || (be instanceof OrExpr) || (be instanceof XorExpr)) {
if (!(left.hasDescendantOrSelf(lop) && left.hasDescendantOrSelf(rop))) {
error("Type Error(27)");
}
} else if ((be instanceof ShlExpr) || (be instanceof ShrExpr) || (be instanceof UshrExpr)) {
if (!(left.hasDescendantOrSelf(lop) && hierarchy.typeNode(IntType.v()).hasAncestorOrSelf(rop))) {
error("Type Error(28)");
}
} else if ((be instanceof CmpExpr) || (be instanceof CmpgExpr) || (be instanceof CmplExpr) || (be instanceof EqExpr)
|| (be instanceof GeExpr) || (be instanceof GtExpr) || (be instanceof LeExpr) || (be instanceof LtExpr)
|| (be instanceof NeExpr)) {
try {
lop.lca(rop);
} catch (TypeException e) {
error(e.getMessage());
}
if (!left.hasDescendantOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(29)");
}
} else {
throw new RuntimeException("Unhandled binary expression type: " + be.getClass());
}
} else if (r instanceof CastExpr) {
CastExpr ce = (CastExpr) r;
TypeNode cast = hierarchy.typeNode(ce.getCastType());
if (ce.getOp() instanceof Local) {
TypeNode op = hierarchy.typeNode(((Local) ce.getOp()).getType());
try {
// we must be careful not to reject primitive type casts (e.g. int to long)
if (cast.isClassOrInterface() || op.isClassOrInterface()) {
cast.lca(op);
}
} catch (TypeException e) {
logger.debug("" + r + "[" + op + "<->" + cast + "]");
error(e.getMessage());
}
}
if (!left.hasDescendantOrSelf(cast)) {
error("Type Error(30)");
}
} else if (r instanceof InstanceOfExpr) {
InstanceOfExpr ioe = (InstanceOfExpr) r;
TypeNode type = hierarchy.typeNode(ioe.getCheckType());
TypeNode op = hierarchy.typeNode(ioe.getOp().getType());
try {
op.lca(type);
} catch (TypeException e) {
logger.debug("" + r + "[" + op + "<->" + type + "]");
error(e.getMessage());
}
if (!left.hasDescendantOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(31)");
}
} else if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
handleInvokeExpr(ie, stmt);
if (!left.hasDescendantOrSelf(hierarchy.typeNode(ie.getMethodRef().returnType()))) {
error("Type Error(32)");
}
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
Type baseType = nae.getBaseType();
TypeNode right;
if (baseType instanceof ArrayType) {
right = hierarchy.typeNode(ArrayType.v(((ArrayType) baseType).baseType, ((ArrayType) baseType).numDimensions + 1));
} else {
right = hierarchy.typeNode(ArrayType.v(baseType, 1));
}
if (!left.hasDescendantOrSelf(right)) {
error("Type Error(33)");
}
Value size = nae.getSize();
if (size instanceof Local) {
TypeNode var = hierarchy.typeNode(((Local) size).getType());
if (!var.hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(34)");
}
}
} else if (r instanceof NewExpr) {
NewExpr ne = (NewExpr) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(ne.getBaseType()))) {
error("Type Error(35)");
}
} else if (r instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(nmae.getBaseType()))) {
error("Type Error(36)");
}
for (int i = 0; i < nmae.getSizeCount(); i++) {
Value size = nmae.getSize(i);
if (size instanceof Local) {
TypeNode var = hierarchy.typeNode(((Local) size).getType());
if (!var.hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(37)");
}
}
}
} else if (r instanceof LengthExpr) {
LengthExpr le = (LengthExpr) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(38)");
}
if (le.getOp() instanceof Local) {
if (!hierarchy.typeNode(((Local) le.getOp()).getType()).isArray()) {
error("Type Error(39)");
}
}
} else if (r instanceof NegExpr) {
NegExpr ne = (NegExpr) r;
TypeNode right;
if (ne.getOp() instanceof Local) {
right = hierarchy.typeNode(((Local) ne.getOp()).getType());
} else if (ne.getOp() instanceof DoubleConstant) {
right = hierarchy.typeNode(DoubleType.v());
} else if (ne.getOp() instanceof FloatConstant) {
right = hierarchy.typeNode(FloatType.v());
} else if (ne.getOp() instanceof IntConstant) {
right = hierarchy.typeNode(IntType.v());
} else if (ne.getOp() instanceof LongConstant) {
right = hierarchy.typeNode(LongType.v());
} else {
throw new RuntimeException("Unhandled neg expression operand type: " + ne.getOp().getClass());
}
if (!left.hasDescendantOrSelf(right)) {
error("Type Error(40)");
}
} else if (r instanceof Local) {
if (!left.hasDescendantOrSelf(hierarchy.typeNode(((Local) r).getType()))) {
if (fix) {
stmt.setRightOp(insertCast((Local) r, left.type(), stmt));
} else {
error("Type Error(41)");
}
}
} else if (r instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) r;
TypeNode baseType = hierarchy.typeNode(((Local) ref.getBase()).getType());
if (!baseType.hasAncestorOrSelf(hierarchy.typeNode(ref.getField().getDeclaringClass().getType()))) {
if (fix) {
ref.setBase(insertCast((Local) ref.getBase(), ref.getField().getDeclaringClass().getType(), stmt));
} else {
error("Type Error(42)");
}
}
if (!left.hasDescendantOrSelf(hierarchy.typeNode(ref.getField().getType()))) {
error("Type Error(43)");
}
} else if (r instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) r;
if (!left.hasDescendantOrSelf(hierarchy.typeNode(ref.getField().getType()))) {
error("Type Error(44)");
}
} else {
throw new RuntimeException("Unhandled assignment right hand side type: " + r.getClass());
}
}
public void caseIdentityStmt(IdentityStmt stmt) {
TypeNode left = hierarchy.typeNode(((Local) stmt.getLeftOp()).getType());
Value r = stmt.getRightOp();
if (!(r instanceof CaughtExceptionRef)) {
TypeNode right = hierarchy.typeNode(r.getType());
if (!left.hasDescendantOrSelf(right)) {
error("Type Error(46) [" + left + " <- " + right + "]");
}
} else {
List<RefType> exceptionTypes = TrapManager.getExceptionTypesOf(stmt, stmtBody);
Iterator<RefType> typeIt = exceptionTypes.iterator();
while (typeIt.hasNext()) {
Type t = typeIt.next();
if (!left.hasDescendantOrSelf(hierarchy.typeNode(t))) {
error("Type Error(47)");
}
}
if (!left.hasAncestorOrSelf(hierarchy.typeNode(RefType.v("java.lang.Throwable")))) {
error("Type Error(48)");
}
}
}
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
if (stmt.getOp() instanceof Local) {
TypeNode op = hierarchy.typeNode(((Local) stmt.getOp()).getType());
if (!op.hasAncestorOrSelf(hierarchy.typeNode(RefType.v("java.lang.Object")))) {
error("Type Error(49)");
}
}
}
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
if (stmt.getOp() instanceof Local) {
TypeNode op = hierarchy.typeNode(((Local) stmt.getOp()).getType());
if (!op.hasAncestorOrSelf(hierarchy.typeNode(RefType.v("java.lang.Object")))) {
error("Type Error(49)");
}
}
}
public void caseGotoStmt(GotoStmt stmt) {
}
public void caseIfStmt(IfStmt stmt) {
ConditionExpr cond = (ConditionExpr) stmt.getCondition();
BinopExpr expr = cond;
Value lv = expr.getOp1();
Value rv = expr.getOp2();
TypeNode lop;
TypeNode rop;
// ******** LEFT ********
if (lv instanceof Local) {
lop = hierarchy.typeNode(((Local) lv).getType());
} else if (lv instanceof DoubleConstant) {
lop = hierarchy.typeNode(DoubleType.v());
} else if (lv instanceof FloatConstant) {
lop = hierarchy.typeNode(FloatType.v());
} else if (lv instanceof IntConstant) {
lop = hierarchy.typeNode(IntType.v());
} else if (lv instanceof LongConstant) {
lop = hierarchy.typeNode(LongType.v());
} else if (lv instanceof NullConstant) {
lop = hierarchy.typeNode(NullType.v());
} else if (lv instanceof StringConstant) {
lop = hierarchy.typeNode(RefType.v("java.lang.String"));
} else if (lv instanceof ClassConstant) {
lop = hierarchy.typeNode(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
rop = hierarchy.typeNode(((Local) rv).getType());
} else if (rv instanceof DoubleConstant) {
rop = hierarchy.typeNode(DoubleType.v());
} else if (rv instanceof FloatConstant) {
rop = hierarchy.typeNode(FloatType.v());
} else if (rv instanceof IntConstant) {
rop = hierarchy.typeNode(IntType.v());
} else if (rv instanceof LongConstant) {
rop = hierarchy.typeNode(LongType.v());
} else if (rv instanceof NullConstant) {
rop = hierarchy.typeNode(NullType.v());
} else if (rv instanceof StringConstant) {
rop = hierarchy.typeNode(RefType.v("java.lang.String"));
} else if (rv instanceof ClassConstant) {
rop = hierarchy.typeNode(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
try {
lop.lca(rop);
} catch (TypeException e) {
error(e.getMessage());
}
}
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
Value key = stmt.getKey();
if (key instanceof Local) {
if (!hierarchy.typeNode(((Local) key).getType()).hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(50)");
}
}
}
public void caseNopStmt(NopStmt stmt) {
}
public void caseReturnStmt(ReturnStmt stmt) {
if (stmt.getOp() instanceof Local) {
if (!hierarchy.typeNode(((Local) stmt.getOp()).getType())
.hasAncestorOrSelf(hierarchy.typeNode(stmtBody.getMethod().getReturnType()))) {
if (fix) {
stmt.setOp(insertCast((Local) stmt.getOp(), stmtBody.getMethod().getReturnType(), stmt));
} else {
error("Type Error(51)");
}
}
}
}
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
Value key = stmt.getKey();
if (key instanceof Local) {
if (!hierarchy.typeNode(((Local) key).getType()).hasAncestorOrSelf(hierarchy.typeNode(IntType.v()))) {
error("Type Error(52)");
}
}
}
public void caseThrowStmt(ThrowStmt stmt) {
if (stmt.getOp() instanceof Local) {
TypeNode op = hierarchy.typeNode(((Local) stmt.getOp()).getType());
if (!op.hasAncestorOrSelf(hierarchy.typeNode(RefType.v("java.lang.Throwable")))) {
if (fix) {
stmt.setOp(insertCast((Local) stmt.getOp(), RefType.v("java.lang.Throwable"), stmt));
} else {
error("Type Error(53)");
}
}
}
}
public void defaultCase(Stmt stmt) {
throw new RuntimeException("Unhandled statement type: " + stmt.getClass());
}
private Local insertCast(Local oldlocal, Type type, Stmt stmt) {
Local newlocal = Jimple.v().newLocal("tmp", type);
stmtBody.getLocals().add(newlocal);
Unit u = Util.findFirstNonIdentityUnit(stmtBody, stmt);
stmtBody.getUnits().insertBefore(Jimple.v().newAssignStmt(newlocal, Jimple.v().newCastExpr(oldlocal, type)), u);
return newlocal;
}
}
| 27,359
| 32.777778
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/ConstraintCollector.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.ArrayType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.RefType;
import soot.SootField;
import soot.SootMethodRef;
import soot.TrapManager;
import soot.Type;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.DynamicInvokeExpr;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.XorExpr;
class ConstraintCollector extends AbstractStmtSwitch {
private final TypeResolver resolver;
private final boolean uses; // if true, include use constraints
private JimpleBody stmtBody;
public ConstraintCollector(TypeResolver resolver, boolean uses) {
this.resolver = resolver;
this.uses = uses;
}
public void collect(Stmt stmt, JimpleBody stmtBody) {
this.stmtBody = stmtBody;
stmt.apply(this);
}
private void handleInvokeExpr(InvokeExpr ie) {
if (!uses) {
return;
}
// Handle the parameters
SootMethodRef method = ie.getMethodRef();
for (int i = 0; i < ie.getArgCount(); i++) {
Value arg = ie.getArg(i);
if (arg instanceof Local) {
TypeVariable localType = resolver.typeVariable((Local) arg);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
if (ie instanceof InterfaceInvokeExpr) {
InterfaceInvokeExpr invoke = (InterfaceInvokeExpr) ie;
Value base = invoke.getBase();
if (base instanceof Local) {
TypeVariable localType = resolver.typeVariable((Local) base);
localType.addParent(resolver.typeVariable(method.declaringClass()));
}
} else if (ie instanceof SpecialInvokeExpr) {
SpecialInvokeExpr invoke = (SpecialInvokeExpr) ie;
Value base = invoke.getBase();
if (base instanceof Local) {
TypeVariable localType = resolver.typeVariable((Local) base);
localType.addParent(resolver.typeVariable(method.declaringClass()));
}
} else if (ie instanceof VirtualInvokeExpr) {
VirtualInvokeExpr invoke = (VirtualInvokeExpr) ie;
Value base = invoke.getBase();
if (base instanceof Local) {
TypeVariable localType = resolver.typeVariable((Local) base);
localType.addParent(resolver.typeVariable(method.declaringClass()));
}
} else if (ie instanceof StaticInvokeExpr) {
// no base to handle
} else if (ie instanceof DynamicInvokeExpr) {
DynamicInvokeExpr invoke = (DynamicInvokeExpr) ie;
SootMethodRef bootstrapMethod = invoke.getBootstrapMethodRef();
for (int i = 0; i < invoke.getBootstrapArgCount(); i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getBootstrapArg(i);
TypeVariable localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(bootstrapMethod.parameterType(i)));
}
}
} else {
throw new RuntimeException("Unhandled invoke expression type: " + ie.getClass());
}
}
@Override
public void caseBreakpointStmt(BreakpointStmt stmt) {
// Do nothing
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
handleInvokeExpr(stmt.getInvokeExpr());
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
final Value l = stmt.getLeftOp();
final Value r = stmt.getRightOp();
TypeVariable left = null;
TypeVariable right = null;
// ******** LEFT ********
if (l instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) l;
Value index = ref.getIndex();
Value base = ref.getBase();
TypeVariable baseType = resolver.typeVariable((Local) base);
baseType.makeElement();
left = baseType.element();
if (index instanceof Local) {
if (uses) {
resolver.typeVariable((Local) index).addParent(resolver.typeVariable(IntType.v()));
}
}
} else if (l instanceof Local) {
left = resolver.typeVariable((Local) l);
} else if (l instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) l;
if (uses) {
TypeVariable baseType = resolver.typeVariable((Local) ref.getBase());
SootField field = ref.getField();
baseType.addParent(resolver.typeVariable(field.getDeclaringClass()));
left = resolver.typeVariable(field.getType());
}
} else if (l instanceof StaticFieldRef) {
if (uses) {
StaticFieldRef ref = (StaticFieldRef) l;
left = resolver.typeVariable(ref.getField().getType());
}
} else {
throw new RuntimeException("Unhandled assignment left hand side type: " + l.getClass());
}
// ******** RIGHT ********
if (r instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) r;
Value index = ref.getIndex();
Value base = ref.getBase();
TypeVariable baseType = resolver.typeVariable((Local) base);
baseType.makeElement();
right = baseType.element();
if (index instanceof Local) {
if (uses) {
resolver.typeVariable((Local) index).addParent(resolver.typeVariable(IntType.v()));
}
}
} else if (r instanceof DoubleConstant) {
right = resolver.typeVariable(DoubleType.v());
} else if (r instanceof FloatConstant) {
right = resolver.typeVariable(FloatType.v());
} else if (r instanceof IntConstant) {
right = resolver.typeVariable(IntType.v());
} else if (r instanceof LongConstant) {
right = resolver.typeVariable(LongType.v());
} else if (r instanceof NullConstant) {
right = resolver.typeVariable(NullType.v());
} else if (r instanceof StringConstant) {
right = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (r instanceof ClassConstant) {
right = resolver.typeVariable(RefType.v("java.lang.Class"));
} else if (r instanceof BinopExpr) {
// ******** BINOP EXPR ********
final BinopExpr be = (BinopExpr) r;
final Value lv = be.getOp1();
final Value rv = be.getOp2();
TypeVariable lop;
TypeVariable rop;
// ******** LEFT ********
if (lv instanceof Local) {
lop = resolver.typeVariable((Local) lv);
} else if (lv instanceof DoubleConstant) {
lop = resolver.typeVariable(DoubleType.v());
} else if (lv instanceof FloatConstant) {
lop = resolver.typeVariable(FloatType.v());
} else if (lv instanceof IntConstant) {
lop = resolver.typeVariable(IntType.v());
} else if (lv instanceof LongConstant) {
lop = resolver.typeVariable(LongType.v());
} else if (lv instanceof NullConstant) {
lop = resolver.typeVariable(NullType.v());
} else if (lv instanceof StringConstant) {
lop = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (lv instanceof ClassConstant) {
lop = resolver.typeVariable(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
rop = resolver.typeVariable((Local) rv);
} else if (rv instanceof DoubleConstant) {
rop = resolver.typeVariable(DoubleType.v());
} else if (rv instanceof FloatConstant) {
rop = resolver.typeVariable(FloatType.v());
} else if (rv instanceof IntConstant) {
rop = resolver.typeVariable(IntType.v());
} else if (rv instanceof LongConstant) {
rop = resolver.typeVariable(LongType.v());
} else if (rv instanceof NullConstant) {
rop = resolver.typeVariable(NullType.v());
} else if (rv instanceof StringConstant) {
rop = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (rv instanceof ClassConstant) {
rop = resolver.typeVariable(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if ((be instanceof AddExpr) || (be instanceof SubExpr) || (be instanceof MulExpr) || (be instanceof DivExpr)
|| (be instanceof RemExpr) || (be instanceof AndExpr) || (be instanceof OrExpr) || (be instanceof XorExpr)) {
if (uses) {
TypeVariable common = resolver.typeVariable();
rop.addParent(common);
lop.addParent(common);
}
if (left != null) {
rop.addParent(left);
lop.addParent(left);
}
} else if ((be instanceof ShlExpr) || (be instanceof ShrExpr) || (be instanceof UshrExpr)) {
if (uses) {
rop.addParent(resolver.typeVariable(IntType.v()));
}
right = lop;
} else if ((be instanceof CmpExpr) || (be instanceof CmpgExpr) || (be instanceof CmplExpr) || (be instanceof EqExpr)
|| (be instanceof GeExpr) || (be instanceof GtExpr) || (be instanceof LeExpr) || (be instanceof LtExpr)
|| (be instanceof NeExpr)) {
if (uses) {
TypeVariable common = resolver.typeVariable();
rop.addParent(common);
lop.addParent(common);
}
right = resolver.typeVariable(IntType.v());
} else {
throw new RuntimeException("Unhandled binary expression type: " + be.getClass());
}
} else if (r instanceof CastExpr) {
CastExpr ce = (CastExpr) r;
right = resolver.typeVariable(ce.getCastType());
} else if (r instanceof InstanceOfExpr) {
right = resolver.typeVariable(IntType.v());
} else if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
handleInvokeExpr(ie);
right = resolver.typeVariable(ie.getMethodRef().returnType());
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
Type baseType = nae.getBaseType();
if (baseType instanceof ArrayType) {
ArrayType arrTy = (ArrayType) baseType;
right = resolver.typeVariable(ArrayType.v(arrTy.baseType, arrTy.numDimensions + 1));
} else {
right = resolver.typeVariable(ArrayType.v(baseType, 1));
}
if (uses) {
Value size = nae.getSize();
if (size instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) size);
var.addParent(resolver.typeVariable(IntType.v()));
}
}
} else if (r instanceof NewExpr) {
NewExpr na = (NewExpr) r;
right = resolver.typeVariable(na.getBaseType());
} else if (r instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) r;
right = resolver.typeVariable(nmae.getBaseType());
if (uses) {
for (int i = 0; i < nmae.getSizeCount(); i++) {
Value size = nmae.getSize(i);
if (size instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) size);
var.addParent(resolver.typeVariable(IntType.v()));
}
}
}
} else if (r instanceof LengthExpr) {
if (uses) {
Value op = ((LengthExpr) r).getOp();
if (op instanceof Local) {
resolver.typeVariable((Local) op).makeElement();
}
}
right = resolver.typeVariable(IntType.v());
} else if (r instanceof NegExpr) {
Value op = ((NegExpr) r).getOp();
if (op instanceof Local) {
right = resolver.typeVariable((Local) op);
} else if (op instanceof DoubleConstant) {
right = resolver.typeVariable(DoubleType.v());
} else if (op instanceof FloatConstant) {
right = resolver.typeVariable(FloatType.v());
} else if (op instanceof IntConstant) {
right = resolver.typeVariable(IntType.v());
} else if (op instanceof LongConstant) {
right = resolver.typeVariable(LongType.v());
} else {
throw new RuntimeException("Unhandled neg expression operand type: " + op.getClass());
}
} else if (r instanceof Local) {
right = resolver.typeVariable((Local) r);
} else if (r instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) r;
if (uses) {
TypeVariable baseType = resolver.typeVariable((Local) ref.getBase());
baseType.addParent(resolver.typeVariable(ref.getField().getDeclaringClass()));
}
right = resolver.typeVariable(ref.getField().getType());
} else if (r instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) r;
right = resolver.typeVariable(ref.getField().getType());
} else {
throw new RuntimeException("Unhandled assignment right hand side type: " + r.getClass());
}
if (left != null && right != null) {
right.addParent(left);
}
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
final Value l = stmt.getLeftOp();
final Value r = stmt.getRightOp();
if (l instanceof Local) {
TypeVariable left = resolver.typeVariable((Local) l);
if (r instanceof CaughtExceptionRef) {
for (Type t : TrapManager.getExceptionTypesOf(stmt, stmtBody)) {
resolver.typeVariable(t).addParent(left);
}
if (uses) {
left.addParent(resolver.typeVariable(RefType.v("java.lang.Throwable")));
}
} else {
TypeVariable right = resolver.typeVariable(r.getType());
right.addParent(left);
}
}
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
if (uses) {
Value op = stmt.getOp();
if (op instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) op);
var.addParent(resolver.typeVariable(RefType.v("java.lang.Object")));
}
}
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
if (uses) {
Value op = stmt.getOp();
if (op instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) op);
var.addParent(resolver.typeVariable(RefType.v("java.lang.Object")));
}
}
}
@Override
public void caseGotoStmt(GotoStmt stmt) {
}
@Override
public void caseIfStmt(IfStmt stmt) {
if (uses) {
final ConditionExpr expr = (ConditionExpr) stmt.getCondition();
final Value lv = expr.getOp1();
final Value rv = expr.getOp2();
TypeVariable lop;
TypeVariable rop;
// ******** LEFT ********
if (lv instanceof Local) {
lop = resolver.typeVariable((Local) lv);
} else if (lv instanceof DoubleConstant) {
lop = resolver.typeVariable(DoubleType.v());
} else if (lv instanceof FloatConstant) {
lop = resolver.typeVariable(FloatType.v());
} else if (lv instanceof IntConstant) {
lop = resolver.typeVariable(IntType.v());
} else if (lv instanceof LongConstant) {
lop = resolver.typeVariable(LongType.v());
} else if (lv instanceof NullConstant) {
lop = resolver.typeVariable(NullType.v());
} else if (lv instanceof StringConstant) {
lop = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (lv instanceof ClassConstant) {
lop = resolver.typeVariable(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
rop = resolver.typeVariable((Local) rv);
} else if (rv instanceof DoubleConstant) {
rop = resolver.typeVariable(DoubleType.v());
} else if (rv instanceof FloatConstant) {
rop = resolver.typeVariable(FloatType.v());
} else if (rv instanceof IntConstant) {
rop = resolver.typeVariable(IntType.v());
} else if (rv instanceof LongConstant) {
rop = resolver.typeVariable(LongType.v());
} else if (rv instanceof NullConstant) {
rop = resolver.typeVariable(NullType.v());
} else if (rv instanceof StringConstant) {
rop = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (rv instanceof ClassConstant) {
rop = resolver.typeVariable(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
TypeVariable common = resolver.typeVariable();
rop.addParent(common);
lop.addParent(common);
}
}
@Override
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) key);
var.addParent(resolver.typeVariable(IntType.v()));
}
}
}
@Override
public void caseNopStmt(NopStmt stmt) {
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
if (uses) {
Value op = stmt.getOp();
if (op instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) op);
var.addParent(resolver.typeVariable(stmtBody.getMethod().getReturnType()));
}
}
}
@Override
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
@Override
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.typeVariable(IntType.v()));
}
}
}
@Override
public void caseThrowStmt(ThrowStmt stmt) {
if (uses) {
Value op = stmt.getOp();
if (op instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) op);
var.addParent(resolver.typeVariable(RefType.v("java.lang.Throwable")));
}
}
}
public void defaultCase(Stmt stmt) {
throw new RuntimeException("Unhandled statement type: " + stmt.getClass());
}
}
| 20,475
| 33.529511
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/ConstraintCollectorBV.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.List;
import soot.ArrayType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.RefType;
import soot.SootMethodRef;
import soot.TrapManager;
import soot.Type;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.XorExpr;
/**
*
* @deprecated use {@link soot.jimple.toolkits.typing.fast.TypeResolver} instead
*/
@Deprecated
class ConstraintCollectorBV extends AbstractStmtSwitch {
private TypeResolverBV resolver;
private boolean uses; // if true, include use contraints
private JimpleBody stmtBody;
public ConstraintCollectorBV(TypeResolverBV resolver, boolean uses) {
this.resolver = resolver;
this.uses = uses;
}
public void collect(Stmt stmt, JimpleBody stmtBody) {
this.stmtBody = stmtBody;
stmt.apply(this);
}
private void handleInvokeExpr(InvokeExpr ie) {
if (!uses) {
return;
}
if (ie instanceof InterfaceInvokeExpr) {
InterfaceInvokeExpr invoke = (InterfaceInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
TypeVariableBV localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.declaringClass()));
}
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
TypeVariableBV localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
} else if (ie instanceof SpecialInvokeExpr) {
SpecialInvokeExpr invoke = (SpecialInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
TypeVariableBV localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.declaringClass()));
}
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
TypeVariableBV localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
} else if (ie instanceof VirtualInvokeExpr) {
VirtualInvokeExpr invoke = (VirtualInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
Value base = invoke.getBase();
if (base instanceof Local) {
Local local = (Local) base;
TypeVariableBV localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.declaringClass()));
}
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
TypeVariableBV localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
} else if (ie instanceof StaticInvokeExpr) {
StaticInvokeExpr invoke = (StaticInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
TypeVariableBV localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
} else {
throw new RuntimeException("Unhandled invoke expression type: " + ie.getClass());
}
}
public void caseBreakpointStmt(BreakpointStmt stmt) {
// Do nothing
}
public void caseInvokeStmt(InvokeStmt stmt) {
handleInvokeExpr(stmt.getInvokeExpr());
}
public void caseAssignStmt(AssignStmt stmt) {
Value l = stmt.getLeftOp();
Value r = stmt.getRightOp();
TypeVariableBV left = null;
TypeVariableBV right = null;
// ******** LEFT ********
if (l instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) l;
Value base = ref.getBase();
Value index = ref.getIndex();
TypeVariableBV baseType = resolver.typeVariable((Local) base);
baseType.makeElement();
left = baseType.element();
if (index instanceof Local) {
if (uses) {
resolver.typeVariable((Local) index).addParent(resolver.typeVariable(IntType.v()));
}
}
} else if (l instanceof Local) {
left = resolver.typeVariable((Local) l);
} else if (l instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) l;
if (uses) {
TypeVariableBV baseType = resolver.typeVariable((Local) ref.getBase());
baseType.addParent(resolver.typeVariable(ref.getField().getDeclaringClass()));
left = resolver.typeVariable(ref.getField().getType());
}
} else if (l instanceof StaticFieldRef) {
if (uses) {
StaticFieldRef ref = (StaticFieldRef) l;
left = resolver.typeVariable(ref.getField().getType());
}
} else {
throw new RuntimeException("Unhandled assignment left hand side type: " + l.getClass());
}
// ******** RIGHT ********
if (r instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) r;
Value base = ref.getBase();
Value index = ref.getIndex();
TypeVariableBV baseType = resolver.typeVariable((Local) base);
baseType.makeElement();
right = baseType.element();
if (index instanceof Local) {
if (uses) {
resolver.typeVariable((Local) index).addParent(resolver.typeVariable(IntType.v()));
}
}
} else if (r instanceof DoubleConstant) {
right = resolver.typeVariable(DoubleType.v());
} else if (r instanceof FloatConstant) {
right = resolver.typeVariable(FloatType.v());
} else if (r instanceof IntConstant) {
right = resolver.typeVariable(IntType.v());
} else if (r instanceof LongConstant) {
right = resolver.typeVariable(LongType.v());
} else if (r instanceof NullConstant) {
right = resolver.typeVariable(NullType.v());
} else if (r instanceof StringConstant) {
right = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (r instanceof ClassConstant) {
right = resolver.typeVariable(RefType.v("java.lang.Class"));
} else if (r instanceof BinopExpr) {
// ******** BINOP EXPR ********
BinopExpr be = (BinopExpr) r;
Value lv = be.getOp1();
Value rv = be.getOp2();
TypeVariableBV lop;
TypeVariableBV rop;
// ******** LEFT ********
if (lv instanceof Local) {
lop = resolver.typeVariable((Local) lv);
} else if (lv instanceof DoubleConstant) {
lop = resolver.typeVariable(DoubleType.v());
} else if (lv instanceof FloatConstant) {
lop = resolver.typeVariable(FloatType.v());
} else if (lv instanceof IntConstant) {
lop = resolver.typeVariable(IntType.v());
} else if (lv instanceof LongConstant) {
lop = resolver.typeVariable(LongType.v());
} else if (lv instanceof NullConstant) {
lop = resolver.typeVariable(NullType.v());
} else if (lv instanceof StringConstant) {
lop = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (lv instanceof ClassConstant) {
lop = resolver.typeVariable(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
rop = resolver.typeVariable((Local) rv);
} else if (rv instanceof DoubleConstant) {
rop = resolver.typeVariable(DoubleType.v());
} else if (rv instanceof FloatConstant) {
rop = resolver.typeVariable(FloatType.v());
} else if (rv instanceof IntConstant) {
rop = resolver.typeVariable(IntType.v());
} else if (rv instanceof LongConstant) {
rop = resolver.typeVariable(LongType.v());
} else if (rv instanceof NullConstant) {
rop = resolver.typeVariable(NullType.v());
} else if (rv instanceof StringConstant) {
rop = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (rv instanceof ClassConstant) {
rop = resolver.typeVariable(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if ((be instanceof AddExpr) || (be instanceof SubExpr) || (be instanceof MulExpr) || (be instanceof DivExpr)
|| (be instanceof RemExpr) || (be instanceof AndExpr) || (be instanceof OrExpr) || (be instanceof XorExpr)) {
if (uses) {
TypeVariableBV common = resolver.typeVariable();
rop.addParent(common);
lop.addParent(common);
}
if (left != null) {
rop.addParent(left);
lop.addParent(left);
}
} else if ((be instanceof ShlExpr) || (be instanceof ShrExpr) || (be instanceof UshrExpr)) {
if (uses) {
rop.addParent(resolver.typeVariable(IntType.v()));
}
right = lop;
} else if ((be instanceof CmpExpr) || (be instanceof CmpgExpr) || (be instanceof CmplExpr) || (be instanceof EqExpr)
|| (be instanceof GeExpr) || (be instanceof GtExpr) || (be instanceof LeExpr) || (be instanceof LtExpr)
|| (be instanceof NeExpr)) {
if (uses) {
TypeVariableBV common = resolver.typeVariable();
rop.addParent(common);
lop.addParent(common);
}
right = resolver.typeVariable(IntType.v());
} else {
throw new RuntimeException("Unhandled binary expression type: " + be.getClass());
}
} else if (r instanceof CastExpr) {
CastExpr ce = (CastExpr) r;
right = resolver.typeVariable(ce.getCastType());
} else if (r instanceof InstanceOfExpr) {
right = resolver.typeVariable(IntType.v());
} else if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
handleInvokeExpr(ie);
right = resolver.typeVariable(ie.getMethodRef().returnType());
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
Type baseType = nae.getBaseType();
if (baseType instanceof ArrayType) {
right
= resolver.typeVariable(ArrayType.v(((ArrayType) baseType).baseType, ((ArrayType) baseType).numDimensions + 1));
} else {
right = resolver.typeVariable(ArrayType.v(baseType, 1));
}
if (uses) {
Value size = nae.getSize();
if (size instanceof Local) {
TypeVariableBV var = resolver.typeVariable((Local) size);
var.addParent(resolver.typeVariable(IntType.v()));
}
}
} else if (r instanceof NewExpr) {
NewExpr na = (NewExpr) r;
right = resolver.typeVariable(na.getBaseType());
} else if (r instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) r;
right = resolver.typeVariable(nmae.getBaseType());
if (uses) {
for (int i = 0; i < nmae.getSizeCount(); i++) {
Value size = nmae.getSize(i);
if (size instanceof Local) {
TypeVariableBV var = resolver.typeVariable((Local) size);
var.addParent(resolver.typeVariable(IntType.v()));
}
}
}
} else if (r instanceof LengthExpr) {
LengthExpr le = (LengthExpr) r;
if (uses) {
if (le.getOp() instanceof Local) {
resolver.typeVariable((Local) le.getOp()).makeElement();
}
}
right = resolver.typeVariable(IntType.v());
} else if (r instanceof NegExpr) {
NegExpr ne = (NegExpr) r;
if (ne.getOp() instanceof Local) {
right = resolver.typeVariable((Local) ne.getOp());
} else if (ne.getOp() instanceof DoubleConstant) {
right = resolver.typeVariable(DoubleType.v());
} else if (ne.getOp() instanceof FloatConstant) {
right = resolver.typeVariable(FloatType.v());
} else if (ne.getOp() instanceof IntConstant) {
right = resolver.typeVariable(IntType.v());
} else if (ne.getOp() instanceof LongConstant) {
right = resolver.typeVariable(LongType.v());
} else {
throw new RuntimeException("Unhandled neg expression operand type: " + ne.getOp().getClass());
}
} else if (r instanceof Local) {
right = resolver.typeVariable((Local) r);
} else if (r instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) r;
if (uses) {
TypeVariableBV baseType = resolver.typeVariable((Local) ref.getBase());
baseType.addParent(resolver.typeVariable(ref.getField().getDeclaringClass()));
}
right = resolver.typeVariable(ref.getField().getType());
} else if (r instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) r;
right = resolver.typeVariable(ref.getField().getType());
} else {
throw new RuntimeException("Unhandled assignment right hand side type: " + r.getClass());
}
if (left != null && right != null) {
right.addParent(left);
}
}
public void caseIdentityStmt(IdentityStmt stmt) {
Value l = stmt.getLeftOp();
Value r = stmt.getRightOp();
if (l instanceof Local) {
TypeVariableBV left = resolver.typeVariable((Local) l);
if (!(r instanceof CaughtExceptionRef)) {
TypeVariableBV right = resolver.typeVariable(r.getType());
right.addParent(left);
} else {
List<RefType> exceptionTypes = TrapManager.getExceptionTypesOf(stmt, stmtBody);
Iterator<RefType> typeIt = exceptionTypes.iterator();
while (typeIt.hasNext()) {
Type t = typeIt.next();
resolver.typeVariable(t).addParent(left);
}
if (uses) {
left.addParent(resolver.typeVariable(RefType.v("java.lang.Throwable")));
}
}
}
}
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
if (uses) {
if (stmt.getOp() instanceof Local) {
TypeVariableBV op = resolver.typeVariable((Local) stmt.getOp());
op.addParent(resolver.typeVariable(RefType.v("java.lang.Object")));
}
}
}
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
if (uses) {
if (stmt.getOp() instanceof Local) {
TypeVariableBV op = resolver.typeVariable((Local) stmt.getOp());
op.addParent(resolver.typeVariable(RefType.v("java.lang.Object")));
}
}
}
public void caseGotoStmt(GotoStmt stmt) {
}
public void caseIfStmt(IfStmt stmt) {
if (uses) {
ConditionExpr cond = (ConditionExpr) stmt.getCondition();
BinopExpr expr = cond;
Value lv = expr.getOp1();
Value rv = expr.getOp2();
TypeVariableBV lop;
TypeVariableBV rop;
// ******** LEFT ********
if (lv instanceof Local) {
lop = resolver.typeVariable((Local) lv);
} else if (lv instanceof DoubleConstant) {
lop = resolver.typeVariable(DoubleType.v());
} else if (lv instanceof FloatConstant) {
lop = resolver.typeVariable(FloatType.v());
} else if (lv instanceof IntConstant) {
lop = resolver.typeVariable(IntType.v());
} else if (lv instanceof LongConstant) {
lop = resolver.typeVariable(LongType.v());
} else if (lv instanceof NullConstant) {
lop = resolver.typeVariable(NullType.v());
} else if (lv instanceof StringConstant) {
lop = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (lv instanceof ClassConstant) {
lop = resolver.typeVariable(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
rop = resolver.typeVariable((Local) rv);
} else if (rv instanceof DoubleConstant) {
rop = resolver.typeVariable(DoubleType.v());
} else if (rv instanceof FloatConstant) {
rop = resolver.typeVariable(FloatType.v());
} else if (rv instanceof IntConstant) {
rop = resolver.typeVariable(IntType.v());
} else if (rv instanceof LongConstant) {
rop = resolver.typeVariable(LongType.v());
} else if (rv instanceof NullConstant) {
rop = resolver.typeVariable(NullType.v());
} else if (rv instanceof StringConstant) {
rop = resolver.typeVariable(RefType.v("java.lang.String"));
} else if (rv instanceof ClassConstant) {
rop = resolver.typeVariable(RefType.v("java.lang.Class"));
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
TypeVariableBV common = resolver.typeVariable();
rop.addParent(common);
lop.addParent(common);
}
}
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.typeVariable(IntType.v()));
}
}
}
public void caseNopStmt(NopStmt stmt) {
}
public void caseReturnStmt(ReturnStmt stmt) {
if (uses) {
if (stmt.getOp() instanceof Local) {
resolver.typeVariable((Local) stmt.getOp()).addParent(resolver.typeVariable(stmtBody.getMethod().getReturnType()));
}
}
}
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.typeVariable(IntType.v()));
}
}
}
public void caseThrowStmt(ThrowStmt stmt) {
if (uses) {
if (stmt.getOp() instanceof Local) {
TypeVariableBV op = resolver.typeVariable((Local) stmt.getOp());
op.addParent(resolver.typeVariable(RefType.v("java.lang.Throwable")));
}
}
}
public void defaultCase(Stmt stmt) {
throw new RuntimeException("Unhandled statement type: " + stmt.getClass());
}
}
| 21,347
| 31.995363
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/InternalTypingException.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class InternalTypingException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 8336012847501378889L;
}
| 1,021
| 30.9375
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/StronglyConnectedComponents.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class StronglyConnectedComponents {
private static final Logger logger = LoggerFactory.getLogger(StronglyConnectedComponents.class);
private static final boolean DEBUG = false;
private final Set<TypeVariable> black = new TreeSet<TypeVariable>();
private final List<TypeVariable> finished = new LinkedList<TypeVariable>();
private List<TypeVariable> current_tree;
public static void merge(List<TypeVariable> typeVariableList) throws TypeException {
new StronglyConnectedComponents(typeVariableList);
}
private StronglyConnectedComponents(List<TypeVariable> typeVariableList) throws TypeException {
for (TypeVariable var : typeVariableList) {
if (!black.add(var)) {
dfsg_visit(var);
}
}
black.clear();
List<List<TypeVariable>> forest = new LinkedList<List<TypeVariable>>();
for (TypeVariable var : finished) {
if (!black.add(var)) {
current_tree = new LinkedList<TypeVariable>();
forest.add(current_tree);
dfsgt_visit(var);
}
}
for (List<TypeVariable> list : forest) {
StringBuilder s = DEBUG ? new StringBuilder("scc:\n") : null;
TypeVariable previous = null;
for (TypeVariable current : list) {
if (DEBUG) {
s.append(' ').append(current).append('\n');
}
if (previous == null) {
previous = current;
} else {
try {
previous = previous.union(current);
} catch (TypeException e) {
if (DEBUG) {
logger.debug(s.toString());
}
throw e;
}
}
}
}
}
private void dfsg_visit(TypeVariable var) {
for (TypeVariable parent : var.parents()) {
if (!black.add(parent)) {
dfsg_visit(parent);
}
}
finished.add(0, var);
}
private void dfsgt_visit(TypeVariable var) {
current_tree.add(var);
for (TypeVariable child : var.children()) {
if (!black.add(child)) {
dfsgt_visit(child);
}
}
}
}
| 3,059
| 28.142857
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/StronglyConnectedComponentsBV.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.util.BitSetIterator;
import soot.util.BitVector;
/**
* @deprecated use {@link soot.jimple.toolkits.typing.fast.TypeResolver} instead
*/
@Deprecated
class StronglyConnectedComponentsBV {
private static final Logger logger = LoggerFactory.getLogger(StronglyConnectedComponentsBV.class);
BitVector variables;
Set<TypeVariableBV> black;
LinkedList<TypeVariableBV> finished;
TypeResolverBV resolver;
LinkedList<LinkedList<TypeVariableBV>> forest = new LinkedList<LinkedList<TypeVariableBV>>();
LinkedList<TypeVariableBV> current_tree;
private static final boolean DEBUG = false;
public StronglyConnectedComponentsBV(BitVector typeVariableList, TypeResolverBV resolver) throws TypeException {
this.resolver = resolver;
variables = typeVariableList;
black = new TreeSet<TypeVariableBV>();
finished = new LinkedList<TypeVariableBV>();
for (BitSetIterator i = variables.iterator(); i.hasNext();) {
TypeVariableBV var = resolver.typeVariableForId(i.next());
if (!black.contains(var)) {
black.add(var);
dfsg_visit(var);
}
}
black = new TreeSet<TypeVariableBV>();
for (TypeVariableBV var : finished) {
if (!black.contains(var)) {
current_tree = new LinkedList<TypeVariableBV>();
forest.add(current_tree);
black.add(var);
dfsgt_visit(var);
}
}
for (Iterator<LinkedList<TypeVariableBV>> i = forest.iterator(); i.hasNext();) {
LinkedList<TypeVariableBV> list = i.next();
TypeVariableBV previous = null;
StringBuffer s = null;
if (DEBUG) {
s = new StringBuffer("scc:\n");
}
for (Iterator<TypeVariableBV> j = list.iterator(); j.hasNext();) {
TypeVariableBV current = j.next();
if (DEBUG) {
s.append(" " + current + "\n");
}
if (previous == null) {
previous = current;
} else {
try {
previous = previous.union(current);
} catch (TypeException e) {
if (DEBUG) {
logger.debug("" + s);
}
throw e;
}
}
}
}
}
private void dfsg_visit(TypeVariableBV var) {
BitVector parents = var.parents();
for (BitSetIterator i = parents.iterator(); i.hasNext();) {
TypeVariableBV parent = resolver.typeVariableForId(i.next());
if (!black.contains(parent)) {
black.add(parent);
dfsg_visit(parent);
}
}
finished.add(0, var);
}
private void dfsgt_visit(TypeVariableBV var) {
current_tree.add(var);
BitVector children = var.children();
for (BitSetIterator i = children.iterator(); i.hasNext();) {
TypeVariableBV child = resolver.typeVariableForId(i.next());
if (!black.contains(child)) {
black.add(child);
dfsgt_visit(child);
}
}
}
}
| 3,918
| 26.794326
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/TypeAssigner.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon.
* Copyright (C) 2008 Ben Bellamy
* Copyright (C) 2008 Eric Bodden
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.ByteType;
import soot.CharType;
import soot.ErroneousType;
import soot.G;
import soot.Local;
import soot.NullType;
import soot.PhaseOptions;
import soot.Scene;
import soot.ShortType;
import soot.Singletons;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.JimpleBody;
import soot.jimple.Stmt;
import soot.jimple.toolkits.scalar.ConstantPropagatorAndFolder;
import soot.jimple.toolkits.scalar.DeadAssignmentEliminator;
import soot.options.JBTROptions;
import soot.options.Options;
import soot.toolkits.scalar.UnusedLocalEliminator;
/**
* This transformer assigns types to local variables.
*
* @author Etienne Gagnon
* @author Ben Bellamy
* @author Eric Bodden
*/
public class TypeAssigner extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(TypeAssigner.class);
public TypeAssigner(Singletons.Global g) {
}
public static TypeAssigner v() {
return G.v().soot_jimple_toolkits_typing_TypeAssigner();
}
/** Assign types to local variables. * */
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
if (b == null) {
throw new NullPointerException();
}
final Date start;
if (Options.v().verbose()) {
start = new Date();
logger.debug("[TypeAssigner] typing system started on " + start);
} else {
start = null;
}
final JBTROptions opt = new JBTROptions(options);
final JimpleBody jb = (JimpleBody) b;
//
// Setting this guard to true enables comparison of the original and new type assigners.
// This will be slow since type assignment will always happen twice. The actual types
// used for Jimple are determined by the use-old-type-assigner option.
//
// Each comparison is written as a separate semicolon-delimited line to the standard
// output, and the first field is always 'cmp' for use in grep. The format is:
//
// cmp;Method Name;Stmt Count;Old Inference Time (ms); New Inference Time (ms);Typing Comparison
//
// The Typing Comparison field compares the old and new typings:
// -2 = Old typing contains fewer variables (BAD!)
// -1 = Old typing is tighter (BAD!)
// 0 = Typings are equal
// 1 = New typing is tighter
// 2 = New typing contains fewer variables
// 3 = Typings are incomparable (inspect manually)
//
// In a final release this guard, and anything in the first branch, would probably be removed.
//
if (opt.compare_type_assigners()) {
compareTypeAssigners(jb, opt.use_older_type_assigner());
} else {
if (opt.use_older_type_assigner()) {
soot.jimple.toolkits.typing.TypeResolver.resolve(jb, Scene.v());
} else {
(new soot.jimple.toolkits.typing.fast.TypeResolver(jb)).inferTypes();
}
}
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("[TypeAssigner] typing system ended. It took " + mins + " mins and " + secs + " secs.");
}
if (!opt.ignore_nullpointer_dereferences()) {
replaceNullType(jb);
}
if (typingFailed(jb)) {
throw new RuntimeException("type inference failed!");
}
}
/**
* Replace statements using locals with null_type type and that would throw a NullPointerException at runtime by a set of
* instructions throwing a NullPointerException.
*
* This is done to remove locals with null_type type.
*
* @param b
*/
protected static void replaceNullType(Body b) {
// check if any local has null_type
boolean hasNullType = false;
for (Local l : b.getLocals()) {
if (l.getType() instanceof NullType) {
hasNullType = true;
break;
}
}
// No local with null_type
if (!hasNullType) {
return;
}
// force to propagate null constants
Map<String, String> opts = PhaseOptions.v().getPhaseOptions("jop.cpf");
if (!opts.containsKey("enabled") || !"true".equals(opts.get("enabled"))) {
logger.warn("Cannot run TypeAssigner.replaceNullType(Body). Try to enable jop.cfg.");
return;
}
ConstantPropagatorAndFolder.v().transform(b);
List<Unit> unitToReplaceByException = new ArrayList<Unit>();
for (Unit u : b.getUnits()) {
Stmt s = (Stmt) u;
for (ValueBox vb : u.getUseBoxes()) {
Value value = vb.getValue();
if (value instanceof Local && value.getType() instanceof NullType) {
boolean replace = false;
if (s.containsArrayRef()) {
ArrayRef r = s.getArrayRef();
if (r.getBase() == value) {
replace = true;
}
} else if (s.containsFieldRef()) {
FieldRef r = s.getFieldRef();
if (r instanceof InstanceFieldRef) {
InstanceFieldRef ir = (InstanceFieldRef) r;
if (ir.getBase() == value) {
replace = true;
}
}
} else if (s.containsInvokeExpr()) {
InvokeExpr ie = s.getInvokeExpr();
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
if (iie.getBase() == value) {
replace = true;
}
}
}
if (replace) {
unitToReplaceByException.add(u);
}
}
}
}
for (Unit u : unitToReplaceByException) {
soot.dexpler.Util.addExceptionAfterUnit(b, "java.lang.NullPointerException", u,
"This statement would have triggered an Exception: " + u);
b.getUnits().remove(u);
}
// should be done on a separate phase
DeadAssignmentEliminator.v().transform(b);
UnusedLocalEliminator.v().transform(b);
}
private void compareTypeAssigners(JimpleBody jb, boolean useOlderTypeAssigner) {
int size = jb.getUnits().size();
JimpleBody oldJb, newJb;
long oldTime, newTime;
if (useOlderTypeAssigner) {
// Use old type assigner last
newJb = (JimpleBody) jb.clone();
newTime = System.currentTimeMillis();
(new soot.jimple.toolkits.typing.fast.TypeResolver(newJb)).inferTypes();
newTime = System.currentTimeMillis() - newTime;
oldTime = System.currentTimeMillis();
soot.jimple.toolkits.typing.TypeResolver.resolve(jb, Scene.v());
oldTime = System.currentTimeMillis() - oldTime;
oldJb = jb;
} else {
// Use new type assigner last
oldJb = (JimpleBody) jb.clone();
oldTime = System.currentTimeMillis();
soot.jimple.toolkits.typing.TypeResolver.resolve(oldJb, Scene.v());
oldTime = System.currentTimeMillis() - oldTime;
newTime = System.currentTimeMillis();
(new soot.jimple.toolkits.typing.fast.TypeResolver(jb)).inferTypes();
newTime = System.currentTimeMillis() - newTime;
newJb = jb;
}
int cmp;
if (newJb.getLocals().size() < oldJb.getLocals().size()) {
cmp = 2;
} else if (newJb.getLocals().size() > oldJb.getLocals().size()) {
cmp = -2;
} else {
cmp = compareTypings(oldJb, newJb);
}
logger.debug("cmp;" + jb.getMethod() + ";" + size + ";" + oldTime + ";" + newTime + ";" + cmp);
}
private boolean typingFailed(JimpleBody b) {
// Check to see if any locals are untyped
final UnknownType unknownType = UnknownType.v();
final ErroneousType erroneousType = ErroneousType.v();
for (Local l : b.getLocals()) {
Type t = l.getType();
if (unknownType.equals(t) || erroneousType.equals(t)) {
return true;
}
}
return false;
}
/* Returns -1 if a < b, +1 if b < a, 0 if a = b and 3 otherwise. */
private static int compareTypings(JimpleBody a, JimpleBody b) {
int r = 0;
Iterator<Local> ib = b.getLocals().iterator();
for (Local v : a.getLocals()) {
Type ta = v.getType(), tb = ib.next().getType();
if (soot.jimple.toolkits.typing.fast.TypeResolver.typesEqual(ta, tb)) {
continue;
} else if ((ta instanceof CharType && (tb instanceof ByteType || tb instanceof ShortType))
|| (tb instanceof CharType && (ta instanceof ByteType || ta instanceof ShortType))) {
continue;
} else if (soot.jimple.toolkits.typing.fast.AugHierarchy.ancestor_(ta, tb)) {
if (r == -1) {
return 3;
} else {
r = 1;
}
} else if (soot.jimple.toolkits.typing.fast.AugHierarchy.ancestor_(tb, ta)) {
if (r == 1) {
return 3;
} else {
r = -1;
}
} else {
return 3;
}
}
return r;
}
}
| 10,131
| 31.063291
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/TypeException.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class TypeException extends Exception {
/**
*
*/
private static final long serialVersionUID = -2484942383485179989L;
public TypeException(String message) {
super(message);
if (message == null) {
throw new InternalTypingException();
}
}
public TypeException(String message, Throwable cause) {
super(message, cause);
if (message == null) {
throw new InternalTypingException();
}
}
}
| 1,313
| 27.565217
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/TypeNode.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.NullType;
import soot.PrimType;
import soot.RefType;
import soot.SootClass;
import soot.Type;
import soot.options.Options;
import soot.util.BitVector;
/**
* Each instance of this class represents one type in the class hierarchy (or basic types).
**/
class TypeNode {
private static final Logger logger = LoggerFactory.getLogger(TypeNode.class);
private static final boolean DEBUG = false;
private final int id;
private final Type type;
private final ClassHierarchy hierarchy;
private TypeNode parentClass;
private TypeNode element;
private TypeNode array;
private List<TypeNode> parents = Collections.emptyList();
private final BitVector ancestors = new BitVector(0);
private final BitVector descendants = new BitVector(0);
public TypeNode(int id, Type type, ClassHierarchy hierarchy) {
if (type == null || hierarchy == null) {
throw new InternalTypingException();
}
if (!((type instanceof PrimType) || (type instanceof RefType) || (type instanceof ArrayType)
|| (type instanceof NullType))) {
logger.debug("Unhandled type: " + type);
throw new InternalTypingException();
}
this.id = id;
this.type = type;
this.hierarchy = hierarchy;
if (DEBUG) {
logger.debug("creating node " + this);
}
}
public TypeNode(int id, RefType type, ClassHierarchy hierarchy) {
this(id, (Type) type, hierarchy);
{
SootClass sClass = type.getSootClass();
if (sClass == null) {
throw new RuntimeException("Oops, forgot to load " + type);
}
if (sClass.isPhantomClass()) {
throw new RuntimeException("Jimplification requires " + sClass + ", but it is a phantom ref.");
}
List<TypeNode> plist = new LinkedList<TypeNode>();
SootClass superclass = sClass.getSuperclassUnsafe();
if (superclass != null && !sClass.getName().equals("java.lang.Object")) {
TypeNode parent = hierarchy.typeNode(RefType.v(sClass.getSuperclass().getName()));
plist.add(parent);
parentClass = parent;
}
for (Iterator<SootClass> i = sClass.getInterfaces().iterator(); i.hasNext();) {
TypeNode parent = hierarchy.typeNode(RefType.v((i.next()).getName()));
plist.add(parent);
}
parents = Collections.unmodifiableList(plist);
}
descendants.set(hierarchy.NULL.id);
hierarchy.NULL.ancestors.set(id);
for (Iterator<TypeNode> parentIt = parents.iterator(); parentIt.hasNext();) {
final TypeNode parent = parentIt.next();
ancestors.set(parent.id);
ancestors.or(parent.ancestors);
parent.fixDescendants(id);
}
}
public TypeNode(int id, ArrayType type, ClassHierarchy hierarchy) {
this(id, (Type) type, hierarchy);
if (type.numDimensions < 1) {
throw new InternalTypingException();
}
if (type.numDimensions == 1) {
element = hierarchy.typeNode(type.baseType);
} else {
element = hierarchy.typeNode(ArrayType.v(type.baseType, type.numDimensions - 1));
}
if (element != hierarchy.INT) {
if (element.array != null) {
throw new InternalTypingException();
}
element.array = this;
}
{
List<TypeNode> plist = new LinkedList<TypeNode>();
if (type.baseType instanceof RefType) {
RefType baseType = (RefType) type.baseType;
SootClass sClass = baseType.getSootClass();
SootClass superClass = sClass.getSuperclassUnsafe();
if (superClass != null && !superClass.getName().equals("java.lang.Object")) {
TypeNode parent = hierarchy.typeNode(ArrayType.v(RefType.v(sClass.getSuperclass().getName()), type.numDimensions));
plist.add(parent);
parentClass = parent;
} else if (type.numDimensions == 1) {
plist.add(hierarchy.OBJECT);
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
plist.add(hierarchy.CLONEABLE);
plist.add(hierarchy.SERIALIZABLE);
}
parentClass = hierarchy.OBJECT;
} else {
plist.add(hierarchy.typeNode(ArrayType.v(hierarchy.OBJECT.type(), type.numDimensions - 1)));
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
plist.add(hierarchy.typeNode(ArrayType.v(hierarchy.CLONEABLE.type(), type.numDimensions - 1)));
plist.add(hierarchy.typeNode(ArrayType.v(hierarchy.SERIALIZABLE.type(), type.numDimensions - 1)));
}
parentClass = hierarchy.typeNode(ArrayType.v(hierarchy.OBJECT.type(), type.numDimensions - 1));
}
for (Iterator<SootClass> i = sClass.getInterfaces().iterator(); i.hasNext();) {
TypeNode parent = hierarchy.typeNode(ArrayType.v(RefType.v((i.next()).getName()), type.numDimensions));
plist.add(parent);
}
} else if (type.numDimensions == 1) {
plist.add(hierarchy.OBJECT);
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
plist.add(hierarchy.CLONEABLE);
plist.add(hierarchy.SERIALIZABLE);
}
parentClass = hierarchy.OBJECT;
} else {
plist.add(hierarchy.typeNode(ArrayType.v(hierarchy.OBJECT.type(), type.numDimensions - 1)));
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
plist.add(hierarchy.typeNode(ArrayType.v(hierarchy.CLONEABLE.type(), type.numDimensions - 1)));
plist.add(hierarchy.typeNode(ArrayType.v(hierarchy.SERIALIZABLE.type(), type.numDimensions - 1)));
}
parentClass = hierarchy.typeNode(ArrayType.v(hierarchy.OBJECT.type(), type.numDimensions - 1));
}
parents = Collections.unmodifiableList(plist);
}
descendants.set(hierarchy.NULL.id);
hierarchy.NULL.ancestors.set(id);
for (Iterator<TypeNode> parentIt = parents.iterator(); parentIt.hasNext();) {
final TypeNode parent = parentIt.next();
ancestors.set(parent.id);
ancestors.or(parent.ancestors);
parent.fixDescendants(id);
}
}
/** Adds the given node to the list of descendants of this node and its ancestors. **/
private void fixDescendants(int id) {
if (descendants.get(id)) {
return;
}
for (Iterator<TypeNode> parentIt = parents.iterator(); parentIt.hasNext();) {
final TypeNode parent = parentIt.next();
parent.fixDescendants(id);
}
descendants.set(id);
}
/** Returns the unique id of this type node. **/
public int id() {
return id;
}
/** Returns the type represented by this type node. **/
public Type type() {
return type;
}
public boolean hasAncestor(TypeNode typeNode) {
return ancestors.get(typeNode.id);
}
public boolean hasAncestorOrSelf(TypeNode typeNode) {
if (typeNode == this) {
return true;
}
return ancestors.get(typeNode.id);
}
public boolean hasDescendant(TypeNode typeNode) {
return descendants.get(typeNode.id);
}
public boolean hasDescendantOrSelf(TypeNode typeNode) {
if (typeNode == this) {
return true;
}
return descendants.get(typeNode.id);
}
public List<TypeNode> parents() {
return parents;
}
public TypeNode parentClass() {
return parentClass;
}
@Override
public String toString() {
return type.toString() + "(" + id + ")";
}
public TypeNode lca(TypeNode type) throws TypeException {
if (type == null) {
throw new InternalTypingException();
}
if (type == this) {
return this;
}
if (hasAncestor(type)) {
return type;
}
if (hasDescendant(type)) {
return this;
}
do {
type = type.parentClass;
if (type == null) {
try {
TypeVariable.error("Type Error(12)");
} catch (TypeException e) {
if (DEBUG) {
logger.error(e.getMessage(), e);
}
throw e;
}
}
} while (!hasAncestor(type));
return type;
}
public TypeNode lcaIfUnique(TypeNode type) throws TypeException {
TypeNode initial = type;
if (type == null) {
throw new InternalTypingException();
}
if (type == this) {
return this;
}
if (hasAncestor(type)) {
return type;
}
if (hasDescendant(type)) {
return this;
}
do {
if (type.parents.size() == 1) {
type = type.parents.get(0);
} else {
if (DEBUG) {
logger.debug("lca " + initial + " (" + type + ") & " + this + " =");
for (Iterator<TypeNode> i = type.parents.iterator(); i.hasNext();) {
logger.debug(" " + i.next());
}
}
return null;
}
} while (!hasAncestor(type));
return type;
}
public boolean hasElement() {
return element != null;
}
public TypeNode element() {
if (element == null) {
throw new InternalTypingException();
}
return element;
}
public TypeNode array() {
if (array != null) {
return array;
}
if (type instanceof ArrayType) {
ArrayType atype = (ArrayType) type;
array = hierarchy.typeNode(ArrayType.v(atype.baseType, atype.numDimensions + 1));
return array;
}
if (type instanceof PrimType || type instanceof RefType) {
array = hierarchy.typeNode(ArrayType.v(type, 1));
return array;
}
throw new InternalTypingException();
}
public boolean isNull() {
if (type instanceof NullType) {
return true;
}
return false;
}
public boolean isClass() {
if (type instanceof ArrayType || type instanceof NullType
|| (type instanceof RefType && !((RefType) type).getSootClass().isInterface())) {
return true;
}
return false;
}
public boolean isClassOrInterface() {
if (type instanceof ArrayType || type instanceof NullType || type instanceof RefType) {
return true;
}
return false;
}
public boolean isArray() {
if (type instanceof ArrayType || type instanceof NullType) {
return true;
}
return false;
}
}
| 11,220
| 26.301703
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/TypeResolver.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.DoubleType;
import soot.FloatType;
import soot.G;
import soot.IntType;
import soot.Local;
import soot.LocalGenerator;
import soot.LongType;
import soot.NullType;
import soot.PatchingChain;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.jimple.AssignStmt;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.NewExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.toolkits.scalar.LocalDefs;
/**
* This class resolves the type of local variables.
*
* <b>NOTE:</b> This class has been superseded by {@link soot.jimple.toolkits.typing.fast.TypeResolver}.
**/
public class TypeResolver {
private static final Logger logger = LoggerFactory.getLogger(TypeResolver.class);
/** Reference to the class hierarchy **/
private final ClassHierarchy hierarchy;
/** All type variable instances **/
private final List<TypeVariable> typeVariableList = new ArrayList<TypeVariable>();
/** Hashtable: [TypeNode or Local] -> TypeVariable **/
private final Map<Object, TypeVariable> typeVariableMap = new HashMap<Object, TypeVariable>();
private final JimpleBody stmtBody;
private final LocalGenerator localGenerator;
final TypeNode NULL;
private final TypeNode OBJECT;
private static final boolean DEBUG = false;
private static final boolean IMPERFORMANT_TYPE_CHECK = false;
// categories for type variables (solved = hard, unsolved = soft)
private Collection<TypeVariable> unsolved;
private Collection<TypeVariable> solved;
// parent categories for unsolved type variables
private List<TypeVariable> single_soft_parent;
private List<TypeVariable> single_hard_parent;
private List<TypeVariable> multiple_parents;
// child categories for unsolved type variables
private List<TypeVariable> single_child_not_null;
private List<TypeVariable> single_null_child;
private List<TypeVariable> multiple_children;
public ClassHierarchy hierarchy() {
return hierarchy;
}
public TypeNode typeNode(Type type) {
return hierarchy.typeNode(type);
}
/** Get type variable for the given local. **/
TypeVariable typeVariable(Local local) {
TypeVariable result = typeVariableMap.get(local);
if (result == null) {
int id = typeVariableList.size();
typeVariableList.add(null);
result = new TypeVariable(id, this);
typeVariableList.set(id, result);
typeVariableMap.put(local, result);
if (DEBUG) {
logger.debug("[LOCAL VARIABLE \"" + local + "\" -> " + id + "]");
}
}
return result;
}
/** Get type variable for the given type node. **/
public TypeVariable typeVariable(TypeNode typeNode) {
TypeVariable result = typeVariableMap.get(typeNode);
if (result == null) {
int id = typeVariableList.size();
typeVariableList.add(null);
result = new TypeVariable(id, this, typeNode);
typeVariableList.set(id, result);
typeVariableMap.put(typeNode, result);
}
return result;
}
/** Get type variable for the given soot class. **/
public TypeVariable typeVariable(SootClass sootClass) {
return typeVariable(hierarchy.typeNode(sootClass.getType()));
}
/** Get type variable for the given type. **/
public TypeVariable typeVariable(Type type) {
return typeVariable(hierarchy.typeNode(type));
}
/** Get new type variable **/
public TypeVariable typeVariable() {
int id = typeVariableList.size();
typeVariableList.add(null);
TypeVariable result = new TypeVariable(id, this);
typeVariableList.set(id, result);
return result;
}
private TypeResolver(JimpleBody stmtBody, Scene scene) {
this.stmtBody = stmtBody;
this.localGenerator = Scene.v().createLocalGenerator(stmtBody);
hierarchy = ClassHierarchy.classHierarchy(scene);
OBJECT = hierarchy.OBJECT;
NULL = hierarchy.NULL;
typeVariable(OBJECT);
typeVariable(NULL);
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
typeVariable(hierarchy.CLONEABLE);
typeVariable(hierarchy.SERIALIZABLE);
}
}
public static void resolve(JimpleBody stmtBody, Scene scene) {
if (DEBUG) {
logger.debug("" + stmtBody.getMethod());
}
try {
TypeResolver resolver = new TypeResolver(stmtBody, scene);
resolver.resolve_step_1();
} catch (TypeException e1) {
if (DEBUG) {
logger.error(e1.getMessage(), e1);
logger.debug("Step 1 Exception-->" + e1.getMessage());
}
try {
TypeResolver resolver = new TypeResolver(stmtBody, scene);
resolver.resolve_step_2();
} catch (TypeException e2) {
if (DEBUG) {
logger.error(e2.getMessage(), e2);
logger.debug("Step 2 Exception-->" + e2.getMessage());
}
try {
TypeResolver resolver = new TypeResolver(stmtBody, scene);
resolver.resolve_step_3();
} catch (TypeException e3) {
StringWriter st = new StringWriter();
PrintWriter pw = new PrintWriter(st);
logger.error(e3.getMessage(), e3);
pw.close();
throw new RuntimeException(st.toString());
}
}
}
soot.jimple.toolkits.typing.integer.TypeResolver.resolve(stmtBody);
}
private void debug_vars(String message) {
if (DEBUG) {
int count = 0;
logger.debug("**** START:" + message);
for (TypeVariable var : typeVariableList) {
logger.debug("" + count++ + " " + var);
}
logger.debug("**** END:" + message);
}
}
private void debug_body() {
if (DEBUG) {
logger.debug("-- Body Start --");
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
logger.debug("" + stmt);
}
logger.debug("-- Body End --");
}
}
private void resolve_step_1() throws TypeException {
// remove_spurious_locals();
collect_constraints_1_2();
debug_vars("constraints");
compute_array_depth();
propagate_array_constraints();
debug_vars("arrays");
merge_primitive_types();
debug_vars("primitive");
merge_connected_components();
debug_vars("components");
remove_transitive_constraints();
debug_vars("transitive");
merge_single_constraints();
debug_vars("single");
assign_types_1_2();
debug_vars("assign");
check_constraints();
}
private void resolve_step_2() throws TypeException {
debug_body();
split_new();
debug_body();
collect_constraints_1_2();
debug_vars("constraints");
compute_array_depth();
propagate_array_constraints();
debug_vars("arrays");
merge_primitive_types();
debug_vars("primitive");
merge_connected_components();
debug_vars("components");
remove_transitive_constraints();
debug_vars("transitive");
merge_single_constraints();
debug_vars("single");
assign_types_1_2();
debug_vars("assign");
check_constraints();
}
private void resolve_step_3() throws TypeException {
collect_constraints_3();
compute_approximate_types();
assign_types_3();
check_and_fix_constraints();
}
private void collect_constraints_1_2() {
ConstraintCollector collector = new ConstraintCollector(this, true);
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
if (DEBUG) {
logger.debug("stmt: ");
}
collector.collect(stmt, stmtBody);
if (DEBUG) {
logger.debug("" + stmt);
}
}
}
private void collect_constraints_3() {
ConstraintCollector collector = new ConstraintCollector(this, false);
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
if (DEBUG) {
logger.debug("stmt: ");
}
collector.collect(stmt, stmtBody);
if (DEBUG) {
logger.debug("" + stmt);
}
}
}
private void compute_array_depth() throws TypeException {
compute_approximate_types();
TypeVariable[] vars = new TypeVariable[typeVariableList.size()];
vars = typeVariableList.toArray(vars);
for (TypeVariable element : vars) {
element.fixDepth();
}
}
private void propagate_array_constraints() {
// find max depth
int max = 0;
for (TypeVariable var : typeVariableList) {
int depth = var.depth();
if (depth > max) {
max = depth;
}
}
// hack for J2ME library, reported by Stephen Cheng
if (max > 1) {
if (!Options.v().j2me()) {
typeVariable(ArrayType.v(RefType.v("java.lang.Cloneable"), max - 1));
typeVariable(ArrayType.v(RefType.v("java.io.Serializable"), max - 1));
}
}
// propagate constraints, starting with highest depth
for (int i = max; i >= 0; i--) {
for (TypeVariable var : typeVariableList) {
var.propagate();
}
}
}
private void merge_primitive_types() throws TypeException {
// merge primitive types with all parents/children
compute_solved();
Iterator<TypeVariable> varIt = solved.iterator();
while (varIt.hasNext()) {
TypeVariable var = varIt.next();
if (var.type().type() instanceof IntType || var.type().type() instanceof LongType
|| var.type().type() instanceof FloatType || var.type().type() instanceof DoubleType) {
List<TypeVariable> parents;
List<TypeVariable> children;
boolean finished;
do {
finished = true;
parents = var.parents();
if (parents.size() != 0) {
finished = false;
for (TypeVariable parent : parents) {
if (DEBUG) {
logger.debug(".");
}
var = var.union(parent);
}
}
children = var.children();
if (children.size() != 0) {
finished = false;
for (TypeVariable child : children) {
if (DEBUG) {
logger.debug(".");
}
var = var.union(child);
}
}
} while (!finished);
}
}
}
private void merge_connected_components() throws TypeException {
refresh_solved();
if (IMPERFORMANT_TYPE_CHECK) {
List<TypeVariable> list = new ArrayList<TypeVariable>(solved.size() + unsolved.size());
list.addAll(solved);
list.addAll(unsolved);
// MMI: This method does not perform any changing effect
// on the list, just a bit error checking, if
// I see this correctly.
StronglyConnectedComponents.merge(list);
}
}
private void remove_transitive_constraints() throws TypeException {
refresh_solved();
for (TypeVariable var : solved) {
var.removeIndirectRelations();
}
for (TypeVariable var : unsolved) {
var.removeIndirectRelations();
}
}
private void merge_single_constraints() throws TypeException {
boolean finished = false;
boolean modified = false;
while (true) {
categorize();
if (single_child_not_null.size() != 0) {
finished = false;
modified = true;
Iterator<TypeVariable> i = single_child_not_null.iterator();
while (i.hasNext()) {
TypeVariable var = i.next();
if (single_child_not_null.contains(var)) {
TypeVariable child = var.children().get(0);
var = var.union(child);
}
}
}
if (finished) {
if (single_soft_parent.size() != 0) {
finished = false;
modified = true;
Iterator<TypeVariable> i = single_soft_parent.iterator();
while (i.hasNext()) {
TypeVariable var = i.next();
if (single_soft_parent.contains(var)) {
TypeVariable parent = var.parents().get(0);
var = var.union(parent);
}
}
}
if (single_hard_parent.size() != 0) {
finished = false;
modified = true;
Iterator<TypeVariable> i = single_hard_parent.iterator();
while (i.hasNext()) {
TypeVariable var = i.next();
if (single_hard_parent.contains(var)) {
TypeVariable parent = var.parents().get(0);
debug_vars("union single parent\n " + var + "\n " + parent);
var = var.union(parent);
}
}
}
if (single_null_child.size() != 0) {
finished = false;
modified = true;
Iterator<TypeVariable> i = single_null_child.iterator();
while (i.hasNext()) {
TypeVariable var = i.next();
if (single_null_child.contains(var)) {
TypeVariable child = var.children().get(0);
var = var.union(child);
}
}
}
if (finished) {
break;
}
continue;
}
if (modified) {
modified = false;
continue;
}
finished = true;
multiple_children: for (TypeVariable var : multiple_children) {
TypeNode lca = null;
List<TypeVariable> children_to_remove = new LinkedList<TypeVariable>();
var.fixChildren();
for (TypeVariable child : var.children()) {
TypeNode type = child.type();
if (type != null && type.isNull()) {
var.removeChild(child);
} else if (type != null && type.isClass()) {
children_to_remove.add(child);
if (lca == null) {
lca = type;
} else {
lca = lca.lcaIfUnique(type);
if (lca == null) {
if (DEBUG) {
logger.debug(
"==++==" + stmtBody.getMethod().getDeclaringClass().getName() + "." + stmtBody.getMethod().getName());
}
continue multiple_children;
}
}
}
}
if (lca != null) {
for (TypeVariable child : children_to_remove) {
var.removeChild(child);
}
var.addChild(typeVariable(lca));
}
}
for (TypeVariable var : multiple_parents) {
List<TypeVariable> hp = new ArrayList<TypeVariable>(); // hard parents
var.fixParents();
for (TypeVariable parent : var.parents()) {
TypeNode type = parent.type();
if (type != null) {
Iterator<TypeVariable> k = hp.iterator();
while (k.hasNext()) {
TypeVariable otherparent = k.next();
TypeNode othertype = otherparent.type();
if (type.hasDescendant(othertype)) {
var.removeParent(parent);
type = null;
break;
}
if (type.hasAncestor(othertype)) {
var.removeParent(otherparent);
k.remove();
}
}
if (type != null) {
hp.add(parent);
}
}
}
}
}
}
private void assign_types_1_2() throws TypeException {
for (Iterator<Local> localIt = stmtBody.getLocals().iterator(); localIt.hasNext();) {
final Local local = localIt.next();
TypeVariable var = typeVariable(local);
if (var == null) {
local.setType(RefType.v("java.lang.Object"));
} else if (var.depth() == 0) {
if (var.type() == null) {
TypeVariable.error("Type Error(5): Variable without type");
} else {
local.setType(var.type().type());
}
} else {
TypeVariable element = var.element();
for (int j = 1; j < var.depth(); j++) {
element = element.element();
}
if (element.type() == null) {
TypeVariable.error("Type Error(6): Array variable without base type");
} else if (element.type().type() instanceof NullType) {
local.setType(NullType.v());
} else {
Type t = element.type().type();
if (t instanceof IntType) {
local.setType(var.approx().type());
} else {
local.setType(ArrayType.v(t, var.depth()));
}
}
}
if (DEBUG) {
if ((var != null) && (var.approx() != null) && (var.approx().type() != null) && (local != null)
&& (local.getType() != null) && !local.getType().equals(var.approx().type())) {
logger.debug("local: " + local + ", type: " + local.getType() + ", approx: " + var.approx().type());
}
}
}
}
private void assign_types_3() throws TypeException {
for (Iterator<Local> localIt = stmtBody.getLocals().iterator(); localIt.hasNext();) {
final Local local = localIt.next();
TypeVariable var = typeVariable(local);
if (var == null || var.approx() == null || var.approx().type() == null) {
local.setType(RefType.v("java.lang.Object"));
} else {
local.setType(var.approx().type());
}
}
}
private void check_constraints() throws TypeException {
ConstraintChecker checker = new ConstraintChecker(this, false);
StringBuffer s = null;
if (DEBUG) {
s = new StringBuffer("Checking:\n");
}
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
if (DEBUG) {
s.append(" " + stmt + "\n");
}
try {
checker.check(stmt, stmtBody);
} catch (TypeException e) {
if (DEBUG) {
logger.debug("" + s);
}
throw e;
}
}
}
private void check_and_fix_constraints() throws TypeException {
ConstraintChecker checker = new ConstraintChecker(this, true);
StringBuffer s = null;
PatchingChain<Unit> units = stmtBody.getUnits();
Stmt[] stmts = new Stmt[units.size()];
units.toArray(stmts);
if (DEBUG) {
s = new StringBuffer("Checking:\n");
}
for (Stmt stmt : stmts) {
if (DEBUG) {
s.append(" " + stmt + "\n");
}
try {
checker.check(stmt, stmtBody);
} catch (TypeException e) {
if (DEBUG) {
logger.debug("" + s);
}
throw e;
}
}
}
private void compute_approximate_types() throws TypeException {
TreeSet<TypeVariable> workList = new TreeSet<TypeVariable>();
for (TypeVariable var : typeVariableList) {
if (var.type() != null) {
workList.add(var);
}
}
TypeVariable.computeApprox(workList);
for (TypeVariable var : typeVariableList) {
if (var.approx() == NULL) {
var.union(typeVariable(NULL));
} else if (var.approx() == null) {
var.union(typeVariable(NULL));
}
}
}
private void compute_solved() {
Set<TypeVariable> unsolved_set = new TreeSet<TypeVariable>();
Set<TypeVariable> solved_set = new TreeSet<TypeVariable>();
for (TypeVariable var : typeVariableList) {
if (var.depth() == 0) {
if (var.type() == null) {
unsolved_set.add(var);
} else {
solved_set.add(var);
}
}
}
solved = solved_set;
unsolved = unsolved_set;
}
private void refresh_solved() throws TypeException {
Set<TypeVariable> unsolved_set = new TreeSet<TypeVariable>();
Set<TypeVariable> solved_set = new TreeSet<TypeVariable>(solved);
for (TypeVariable var : unsolved) {
if (var.depth() == 0) {
if (var.type() == null) {
unsolved_set.add(var);
} else {
solved_set.add(var);
}
}
}
solved = solved_set;
unsolved = unsolved_set;
// validate();
}
private void categorize() throws TypeException {
refresh_solved();
single_soft_parent = new LinkedList<TypeVariable>();
single_hard_parent = new LinkedList<TypeVariable>();
multiple_parents = new LinkedList<TypeVariable>();
single_child_not_null = new LinkedList<TypeVariable>();
single_null_child = new LinkedList<TypeVariable>();
multiple_children = new LinkedList<TypeVariable>();
for (TypeVariable var : unsolved) {
// parent category
{
List<TypeVariable> parents = var.parents();
int size = parents.size();
if (size == 0) {
var.addParent(typeVariable(OBJECT));
single_soft_parent.add(var);
} else if (size == 1) {
TypeVariable parent = parents.get(0);
if (parent.type() == null) {
single_soft_parent.add(var);
} else {
single_hard_parent.add(var);
}
} else {
multiple_parents.add(var);
}
}
// child category
{
List<TypeVariable> children = var.children();
int size = children.size();
if (size == 0) {
var.addChild(typeVariable(NULL));
single_null_child.add(var);
} else if (size == 1) {
TypeVariable child = children.get(0);
if (child.type() == NULL) {
single_null_child.add(var);
} else {
single_child_not_null.add(var);
}
} else {
multiple_children.add(var);
}
}
}
}
private void split_new() {
LocalDefs defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(stmtBody);
PatchingChain<Unit> units = stmtBody.getUnits();
Stmt[] stmts = new Stmt[units.size()];
units.toArray(stmts);
for (Stmt stmt : stmts) {
if (stmt instanceof InvokeStmt) {
InvokeStmt invoke = (InvokeStmt) stmt;
if (invoke.getInvokeExpr() instanceof SpecialInvokeExpr) {
SpecialInvokeExpr special = (SpecialInvokeExpr) invoke.getInvokeExpr();
if ("<init>".equals(special.getMethodRef().name())) {
List<Unit> deflist = defs.getDefsOfAt((Local) special.getBase(), invoke);
while (deflist.size() == 1) {
Stmt stmt2 = (Stmt) deflist.get(0);
if (stmt2 instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) stmt2;
if (assign.getRightOp() instanceof Local) {
deflist = defs.getDefsOfAt((Local) assign.getRightOp(), assign);
continue;
} else if (assign.getRightOp() instanceof NewExpr) {
// We split the local.
// logger.debug("split: [" + assign + "] and [" + stmt + "]");
Local newlocal = localGenerator.generateLocal(UnknownType.v());
special.setBase(newlocal);
units.insertAfter(Jimple.v().newAssignStmt(assign.getLeftOp(), newlocal), assign);
assign.setLeftOp(newlocal);
}
}
break;
}
}
}
}
}
}
}
| 24,383
| 26.521445
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/TypeResolverBV.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.DoubleType;
import soot.FloatType;
import soot.G;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.PatchingChain;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.Type;
import soot.Unit;
import soot.jimple.AssignStmt;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.NewExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.toolkits.scalar.LocalDefs;
import soot.util.BitSetIterator;
import soot.util.BitVector;
/**
* This class resolves the type of local variables.
*
* @deprecated use {@link soot.jimple.toolkits.typing.fast.TypeResolver} instead
**/
@Deprecated
public class TypeResolverBV {
private static final Logger logger = LoggerFactory.getLogger(TypeResolverBV.class);
/** Reference to the class hierarchy **/
private final ClassHierarchy hierarchy;
/** All type variable instances **/
private final List<TypeVariableBV> typeVariableList = new ArrayList<TypeVariableBV>();
private final BitVector invalidIds = new BitVector();
/** Hashtable: [TypeNode or Local] -> TypeVariableBV **/
private final Map<Object, TypeVariableBV> typeVariableMap = new HashMap<Object, TypeVariableBV>();
private final JimpleBody stmtBody;
final TypeNode NULL;
private final TypeNode OBJECT;
private static final boolean DEBUG = false;
// categories for type variables (solved = hard, unsolved = soft)
private BitVector unsolved;
private BitVector solved;
// parent categories for unsolved type variables
private BitVector single_soft_parent;
private BitVector single_hard_parent;
private BitVector multiple_parents;
// child categories for unsolved type variables
private BitVector single_child_not_null;
private BitVector single_null_child;
private BitVector multiple_children;
public ClassHierarchy hierarchy() {
return hierarchy;
}
public TypeNode typeNode(Type type) {
return hierarchy.typeNode(type);
}
/** Get type variable for the given local. **/
TypeVariableBV typeVariable(Local local) {
TypeVariableBV result = typeVariableMap.get(local);
if (result == null) {
int id = typeVariableList.size();
typeVariableList.add(null);
result = new TypeVariableBV(id, this);
typeVariableList.set(id, result);
typeVariableMap.put(local, result);
if (DEBUG) {
logger.debug("[LOCAL VARIABLE \"" + local + "\" -> " + id + "]");
}
}
return result;
}
/** Get type variable for the given type node. **/
public TypeVariableBV typeVariable(TypeNode typeNode) {
TypeVariableBV result = typeVariableMap.get(typeNode);
if (result == null) {
int id = typeVariableList.size();
typeVariableList.add(null);
result = new TypeVariableBV(id, this, typeNode);
typeVariableList.set(id, result);
typeVariableMap.put(typeNode, result);
}
return result;
}
/** Get type variable for the given soot class. **/
public TypeVariableBV typeVariable(SootClass sootClass) {
return typeVariable(hierarchy.typeNode(sootClass.getType()));
}
/** Get type variable for the given type. **/
public TypeVariableBV typeVariable(Type type) {
return typeVariable(hierarchy.typeNode(type));
}
/** Get new type variable **/
public TypeVariableBV typeVariable() {
int id = typeVariableList.size();
typeVariableList.add(null);
TypeVariableBV result = new TypeVariableBV(id, this);
typeVariableList.set(id, result);
return result;
}
private TypeResolverBV(JimpleBody stmtBody, Scene scene) {
this.stmtBody = stmtBody;
hierarchy = ClassHierarchy.classHierarchy(scene);
OBJECT = hierarchy.OBJECT;
NULL = hierarchy.NULL;
typeVariable(OBJECT);
typeVariable(NULL);
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
typeVariable(hierarchy.CLONEABLE);
typeVariable(hierarchy.SERIALIZABLE);
}
}
public static void resolve(JimpleBody stmtBody, Scene scene) {
if (DEBUG) {
logger.debug("" + stmtBody.getMethod());
}
try {
TypeResolverBV resolver = new TypeResolverBV(stmtBody, scene);
resolver.resolve_step_1();
} catch (TypeException e1) {
if (DEBUG) {
logger.error(e1.getMessage(), e1);
logger.debug("Step 1 Exception-->" + e1.getMessage());
}
try {
TypeResolverBV resolver = new TypeResolverBV(stmtBody, scene);
resolver.resolve_step_2();
} catch (TypeException e2) {
if (DEBUG) {
logger.error(e2.getMessage(), e2);
logger.debug("Step 2 Exception-->" + e2.getMessage());
}
try {
TypeResolverBV resolver = new TypeResolverBV(stmtBody, scene);
resolver.resolve_step_3();
} catch (TypeException e3) {
StringWriter st = new StringWriter();
PrintWriter pw = new PrintWriter(st);
logger.error(e3.getMessage(), e3);
pw.close();
throw new RuntimeException(st.toString());
}
}
}
soot.jimple.toolkits.typing.integer.TypeResolver.resolve(stmtBody);
}
private void debug_vars(String message) {
if (DEBUG) {
int count = 0;
logger.debug("**** START:" + message);
for (TypeVariableBV var : typeVariableList) {
logger.debug("" + count++ + " " + var);
}
logger.debug("**** END:" + message);
}
}
private void debug_body() {
if (DEBUG) {
logger.debug("-- Body Start --");
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
logger.debug("" + stmt);
}
logger.debug("-- Body End --");
}
}
private void resolve_step_1() throws TypeException {
// remove_spurious_locals();
collect_constraints_1_2();
debug_vars("constraints");
compute_array_depth();
propagate_array_constraints();
debug_vars("arrays");
merge_primitive_types();
debug_vars("primitive");
merge_connected_components();
debug_vars("components");
remove_transitive_constraints();
debug_vars("transitive");
merge_single_constraints();
debug_vars("single");
assign_types_1_2();
debug_vars("assign");
check_constraints();
}
private void resolve_step_2() throws TypeException {
debug_body();
split_new();
debug_body();
collect_constraints_1_2();
debug_vars("constraints");
compute_array_depth();
propagate_array_constraints();
debug_vars("arrays");
merge_primitive_types();
debug_vars("primitive");
merge_connected_components();
debug_vars("components");
remove_transitive_constraints();
debug_vars("transitive");
merge_single_constraints();
debug_vars("single");
assign_types_1_2();
debug_vars("assign");
check_constraints();
}
private void resolve_step_3() throws TypeException {
collect_constraints_3();
compute_approximate_types();
assign_types_3();
check_and_fix_constraints();
}
private void collect_constraints_1_2() {
ConstraintCollectorBV collector = new ConstraintCollectorBV(this, true);
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
if (DEBUG) {
logger.debug("stmt: ");
}
collector.collect(stmt, stmtBody);
if (DEBUG) {
logger.debug("" + stmt);
}
}
}
private void collect_constraints_3() {
ConstraintCollectorBV collector = new ConstraintCollectorBV(this, false);
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
if (DEBUG) {
logger.debug("stmt: ");
}
collector.collect(stmt, stmtBody);
if (DEBUG) {
logger.debug("" + stmt);
}
}
}
private void compute_array_depth() throws TypeException {
compute_approximate_types();
TypeVariableBV[] vars = new TypeVariableBV[typeVariableList.size()];
vars = typeVariableList.toArray(vars);
for (TypeVariableBV element : vars) {
element.fixDepth();
}
}
private void propagate_array_constraints() {
// find max depth
int max = 0;
for (TypeVariableBV var : typeVariableList) {
int depth = var.depth();
if (depth > max) {
max = depth;
}
}
if (max > 1) {
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
typeVariable(ArrayType.v(RefType.v("java.lang.Cloneable"), max - 1));
typeVariable(ArrayType.v(RefType.v("java.io.Serializable"), max - 1));
}
}
// create lists for each array depth
@SuppressWarnings("unchecked")
LinkedList<TypeVariableBV>[] lists = new LinkedList[max + 1];
for (int i = 0; i <= max; i++) {
lists[i] = new LinkedList<TypeVariableBV>();
}
for (TypeVariableBV var : typeVariableList) {
int depth = var.depth();
lists[depth].add(var);
}
// propagate constraints, starting with highest depth
for (int i = max; i >= 0; i--) {
for (TypeVariableBV var : typeVariableList) {
var.propagate();
}
}
}
private void merge_primitive_types() throws TypeException {
// merge primitive types with all parents/children
compute_solved();
BitSetIterator varIt = solved.iterator();
while (varIt.hasNext()) {
TypeVariableBV var = typeVariableForId(varIt.next());
if (var.type().type() instanceof IntType || var.type().type() instanceof LongType
|| var.type().type() instanceof FloatType || var.type().type() instanceof DoubleType) {
BitVector parents;
BitVector children;
boolean finished;
do {
finished = true;
parents = var.parents();
if (parents.length() != 0) {
finished = false;
for (BitSetIterator j = parents.iterator(); j.hasNext();) {
if (DEBUG) {
logger.debug(".");
}
TypeVariableBV parent = typeVariableForId(j.next());
var = var.union(parent);
}
}
children = var.children();
if (children.length() != 0) {
finished = false;
for (BitSetIterator j = children.iterator(); j.hasNext();) {
if (DEBUG) {
logger.debug(".");
}
TypeVariableBV child = typeVariableForId(j.next());
var = var.union(child);
}
}
} while (!finished);
}
}
}
private void merge_connected_components() throws TypeException {
refresh_solved();
BitVector list = new BitVector();
list.or(solved);
list.or(unsolved);
new StronglyConnectedComponentsBV(list, this);
}
private void remove_transitive_constraints() throws TypeException {
refresh_solved();
BitVector list = new BitVector();
list.or(solved);
list.or(unsolved);
for (BitSetIterator varIt = list.iterator(); varIt.hasNext();) {
final TypeVariableBV var = typeVariableForId(varIt.next());
var.removeIndirectRelations();
}
}
private void merge_single_constraints() throws TypeException {
boolean finished = false;
boolean modified = false;
while (true) {
categorize();
if (single_child_not_null.length() != 0) {
finished = false;
modified = true;
BitSetIterator i = single_child_not_null.iterator();
while (i.hasNext()) {
TypeVariableBV var = typeVariableForId(i.next());
if (single_child_not_null.get(var.id())) {
// PA: Potential difference to old algorithm - using the smallest element
// in the list rather than children().get(0);
TypeVariableBV child = typeVariableForId(var.children().iterator().next());
var = var.union(child);
}
}
}
if (finished) {
if (single_soft_parent.length() != 0) {
finished = false;
modified = true;
BitSetIterator i = single_soft_parent.iterator();
while (i.hasNext()) {
TypeVariableBV var = typeVariableForId(i.next());
if (single_soft_parent.get(var.id())) {
// PA: See above.
TypeVariableBV parent = typeVariableForId(var.parents().iterator().next());
var = var.union(parent);
}
}
}
if (single_hard_parent.length() != 0) {
finished = false;
modified = true;
BitSetIterator i = single_hard_parent.iterator();
while (i.hasNext()) {
TypeVariableBV var = typeVariableForId(i.next());
if (single_hard_parent.get(var.id())) {
// PA: See above
TypeVariableBV parent = typeVariableForId(var.parents().iterator().next());
debug_vars("union single parent\n " + var + "\n " + parent);
var = var.union(parent);
}
}
}
if (single_null_child.length() != 0) {
finished = false;
modified = true;
BitSetIterator i = single_null_child.iterator();
while (i.hasNext()) {
TypeVariableBV var = typeVariableForId(i.next());
if (single_null_child.get(var.id())) {
// PA: See above
TypeVariableBV child = typeVariableForId(var.children().iterator().next());
var = var.union(child);
}
}
}
if (finished) {
break;
}
continue;
}
if (modified) {
modified = false;
continue;
}
finished = true;
multiple_children: for (BitSetIterator varIt = multiple_children.iterator(); varIt.hasNext();) {
final TypeVariableBV var = typeVariableForId(varIt.next());
TypeNode lca = null;
BitVector children_to_remove = new BitVector();
for (BitSetIterator childIt = var.children().iterator(); childIt.hasNext();) {
final TypeVariableBV child = typeVariableForId(childIt.next());
TypeNode type = child.type();
if (type != null && type.isNull()) {
var.removeChild(child);
} else if (type != null && type.isClass()) {
children_to_remove.set(child.id());
if (lca == null) {
lca = type;
} else {
lca = lca.lcaIfUnique(type);
if (lca == null) {
if (DEBUG) {
logger.debug(
"==++==" + stmtBody.getMethod().getDeclaringClass().getName() + "." + stmtBody.getMethod().getName());
}
continue multiple_children;
}
}
}
}
if (lca != null) {
for (BitSetIterator childIt = children_to_remove.iterator(); childIt.hasNext();) {
final TypeVariableBV child = typeVariableForId(childIt.next());
var.removeChild(child);
}
var.addChild(typeVariable(lca));
}
}
for (BitSetIterator varIt = multiple_parents.iterator(); varIt.hasNext();) {
final TypeVariableBV var = typeVariableForId(varIt.next());
LinkedList<TypeVariableBV> hp = new LinkedList<TypeVariableBV>(); // hard parents
for (BitSetIterator parentIt = var.parents().iterator(); parentIt.hasNext();) {
final TypeVariableBV parent = typeVariableForId(parentIt.next());
TypeNode type = parent.type();
if (type != null) {
Iterator<TypeVariableBV> k = hp.iterator();
while (k.hasNext()) {
TypeVariableBV otherparent = k.next();
TypeNode othertype = otherparent.type();
if (type.hasDescendant(othertype)) {
var.removeParent(parent);
type = null;
break;
}
if (type.hasAncestor(othertype)) {
var.removeParent(otherparent);
k.remove();
}
}
if (type != null) {
hp.add(parent);
}
}
}
}
}
}
private void assign_types_1_2() throws TypeException {
for (Iterator<Local> localIt = stmtBody.getLocals().iterator(); localIt.hasNext();) {
final Local local = localIt.next();
TypeVariableBV var = typeVariable(local);
if (var == null) {
local.setType(RefType.v("java.lang.Object"));
} else if (var.depth() == 0) {
if (var.type() == null) {
TypeVariableBV.error("Type Error(5): Variable without type");
} else {
local.setType(var.type().type());
}
} else {
TypeVariableBV element = var.element();
for (int j = 1; j < var.depth(); j++) {
element = element.element();
}
if (element.type() == null) {
TypeVariableBV.error("Type Error(6): Array variable without base type");
} else if (element.type().type() instanceof NullType) {
local.setType(NullType.v());
} else {
Type t = element.type().type();
if (t instanceof IntType) {
local.setType(var.approx().type());
} else {
local.setType(ArrayType.v(t, var.depth()));
}
}
}
if (DEBUG) {
if ((var != null) && (var.approx() != null) && (var.approx().type() != null) && (local != null)
&& (local.getType() != null) && !local.getType().equals(var.approx().type())) {
logger.debug("local: " + local + ", type: " + local.getType() + ", approx: " + var.approx().type());
}
}
}
}
private void assign_types_3() throws TypeException {
for (Iterator<Local> localIt = stmtBody.getLocals().iterator(); localIt.hasNext();) {
final Local local = localIt.next();
TypeVariableBV var = typeVariable(local);
if (var == null || var.approx() == null || var.approx().type() == null) {
local.setType(RefType.v("java.lang.Object"));
} else {
local.setType(var.approx().type());
}
}
}
private void check_constraints() throws TypeException {
ConstraintCheckerBV checker = new ConstraintCheckerBV(this, false);
StringBuffer s = null;
if (DEBUG) {
s = new StringBuffer("Checking:\n");
}
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
if (DEBUG) {
s.append(" " + stmt + "\n");
}
try {
checker.check(stmt, stmtBody);
} catch (TypeException e) {
if (DEBUG) {
logger.debug("" + s);
}
throw e;
}
}
}
private void check_and_fix_constraints() throws TypeException {
ConstraintCheckerBV checker = new ConstraintCheckerBV(this, true);
StringBuffer s = null;
PatchingChain<Unit> units = stmtBody.getUnits();
Stmt[] stmts = new Stmt[units.size()];
units.toArray(stmts);
if (DEBUG) {
s = new StringBuffer("Checking:\n");
}
for (Stmt stmt : stmts) {
if (DEBUG) {
s.append(" " + stmt + "\n");
}
try {
checker.check(stmt, stmtBody);
} catch (TypeException e) {
if (DEBUG) {
logger.debug("" + s);
}
throw e;
}
}
}
private void compute_approximate_types() throws TypeException {
TreeSet<TypeVariableBV> workList = new TreeSet<TypeVariableBV>();
for (TypeVariableBV var : typeVariableList) {
if (var.type() != null) {
workList.add(var);
}
}
TypeVariableBV.computeApprox(workList);
for (TypeVariableBV var : typeVariableList) {
if (var.approx() == NULL) {
var.union(typeVariable(NULL));
} else if (var.approx() == null) {
var.union(typeVariable(NULL));
}
}
}
private void compute_solved() {
unsolved = new BitVector();
solved = new BitVector();
for (TypeVariableBV var : typeVariableList) {
if (var.depth() == 0) {
if (var.type() == null) {
unsolved.set(var.id());
} else {
solved.set(var.id());
}
}
}
}
private void refresh_solved() throws TypeException {
unsolved = new BitVector();
// solved stays the same
for (BitSetIterator varIt = unsolved.iterator(); varIt.hasNext();) {
final TypeVariableBV var = typeVariableForId(varIt.next());
if (var.depth() == 0) {
if (var.type() == null) {
unsolved.set(var.id());
} else {
solved.set(var.id());
}
}
}
// validate();
}
private void categorize() throws TypeException {
refresh_solved();
single_soft_parent = new BitVector();
single_hard_parent = new BitVector();
multiple_parents = new BitVector();
single_child_not_null = new BitVector();
single_null_child = new BitVector();
multiple_children = new BitVector();
for (BitSetIterator i = unsolved.iterator(); i.hasNext();) {
TypeVariableBV var = typeVariableForId(i.next());
// parent category
{
BitVector parents = var.parents();
int size = parents.length();
if (size == 0) {
var.addParent(typeVariable(OBJECT));
single_soft_parent.set(var.id());
} else if (size == 1) {
TypeVariableBV parent = typeVariableForId(parents.iterator().next());
if (parent.type() == null) {
single_soft_parent.set(var.id());
} else {
single_hard_parent.set(var.id());
}
} else {
multiple_parents.set(var.id());
}
}
// child category
{
BitVector children = var.children();
int size = children.size();
if (size == 0) {
var.addChild(typeVariable(NULL));
single_null_child.set(var.id());
} else if (size == 1) {
TypeVariableBV child = typeVariableForId(children.iterator().next());
if (child.type() == NULL) {
single_null_child.set(var.id());
} else {
single_child_not_null.set(var.id());
}
} else {
multiple_children.set(var.id());
}
}
}
}
private void split_new() {
LocalDefs defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(stmtBody);
PatchingChain<Unit> units = stmtBody.getUnits();
Stmt[] stmts = new Stmt[units.size()];
units.toArray(stmts);
for (Stmt stmt : stmts) {
if (stmt instanceof InvokeStmt) {
InvokeStmt invoke = (InvokeStmt) stmt;
if (invoke.getInvokeExpr() instanceof SpecialInvokeExpr) {
SpecialInvokeExpr special = (SpecialInvokeExpr) invoke.getInvokeExpr();
if (special.getMethodRef().name().equals("<init>")) {
List<Unit> deflist = defs.getDefsOfAt((Local) special.getBase(), invoke);
while (deflist.size() == 1) {
Stmt stmt2 = (Stmt) deflist.get(0);
if (stmt2 instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) stmt2;
if (assign.getRightOp() instanceof Local) {
deflist = defs.getDefsOfAt((Local) assign.getRightOp(), assign);
continue;
} else if (assign.getRightOp() instanceof NewExpr) {
// We split the local.
// logger.debug("split: [" + assign + "] and [" + stmt + "]");
Local newlocal = Jimple.v().newLocal("tmp", null);
stmtBody.getLocals().add(newlocal);
special.setBase(newlocal);
units.insertAfter(Jimple.v().newAssignStmt(assign.getLeftOp(), newlocal), assign);
assign.setLeftOp(newlocal);
}
}
break;
}
}
}
}
}
}
public TypeVariableBV typeVariableForId(int idx) {
return typeVariableList.get(idx);
}
public BitVector invalidIds() {
return invalidIds;
}
public void invalidateId(int id) {
invalidIds.set(id);
}
}
| 25,703
| 27.030534
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/TypeVariable.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.RefType;
import soot.options.Options;
import soot.util.BitVector;
/** Represents a type variable. **/
class TypeVariable implements Comparable<Object> {
private static final Logger logger = LoggerFactory.getLogger(TypeVariable.class);
private static final boolean DEBUG = false;
private final int id;
private final TypeResolver resolver;
private TypeVariable rep = this;
private int rank = 0;
private TypeNode approx;
private TypeNode type;
private TypeVariable array;
private TypeVariable element;
private int depth;
private List<TypeVariable> parents = Collections.emptyList();
private List<TypeVariable> children = Collections.emptyList();
private BitVector ancestors;
private BitVector indirectAncestors;
public TypeVariable(int id, TypeResolver resolver) {
this.id = id;
this.resolver = resolver;
}
public TypeVariable(int id, TypeResolver resolver, TypeNode type) {
this.id = id;
this.resolver = resolver;
this.type = type;
this.approx = type;
for (TypeNode parent : type.parents()) {
addParent(resolver.typeVariable(parent));
}
if (type.hasElement()) {
this.element = resolver.typeVariable(type.element());
this.element.array = this;
}
}
@Override
public int hashCode() {
return (rep != this) ? ecr().hashCode() : id;
}
@Override
public boolean equals(Object obj) {
if (rep != this) {
return ecr().equals(obj);
}
if (obj == null) {
return false;
}
if (!obj.getClass().equals(this.getClass())) {
return false;
}
return ((TypeVariable) obj).ecr() == this;
}
@Override
public int compareTo(Object o) {
if (rep != this) {
return ecr().compareTo(o);
} else {
return id - ((TypeVariable) o).ecr().id;
}
}
private TypeVariable ecr() {
if (rep != this) {
rep = rep.ecr();
}
return rep;
}
public TypeVariable union(TypeVariable var) throws TypeException {
if (this.rep != this) {
return ecr().union(var);
}
TypeVariable y = var.ecr();
if (this == y) {
return this;
}
if (this.rank > y.rank) {
y.rep = this;
merge(y);
y.clear();
return this;
} else {
this.rep = y;
if (this.rank == y.rank) {
y.rank++;
}
y.merge(this);
clear();
return y;
}
}
private void clear() {
this.approx = null;
this.type = null;
this.element = null;
this.array = null;
this.parents = null;
this.children = null;
this.ancestors = null;
this.indirectAncestors = null;
}
private void merge(TypeVariable var) throws TypeException {
if (this.depth != 0 || var.depth != 0) {
throw new InternalTypingException();
}
// Merge types
if (this.type == null) {
this.type = var.type;
} else if (var.type != null) {
error("Type Error(1): Attempt to merge two types.");
}
// Merge parents
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.parents);
set.addAll(var.parents);
set.remove(this);
this.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
// Merge children
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.children);
set.addAll(var.children);
set.remove(this);
this.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
void validate() throws TypeException {
if (this.rep != this) {
ecr().validate();
return;
}
// Validate relations.
final TypeNode thisType = this.type;
if (thisType != null) {
for (TypeVariable typeVariable : this.parents) {
TypeNode parentType = typeVariable.ecr().type;
if (parentType != null) {
if (!thisType.hasAncestor(parentType)) {
if (DEBUG) {
logger.debug(parentType + " is not a parent of " + thisType);
}
error("Type Error(2): Parent type is not a valid ancestor.");
}
}
}
for (TypeVariable typeVariable : this.children) {
TypeVariable child = typeVariable.ecr();
TypeNode childType = child.type;
if (childType != null) {
if (!thisType.hasDescendant(childType)) {
if (DEBUG) {
logger.debug(childType + "(" + child + ") is not a child of " + thisType + "(" + this + ")");
}
error("Type Error(3): Child type is not a valid descendant.");
}
}
}
}
}
public void removeIndirectRelations() {
if (this.rep != this) {
ecr().removeIndirectRelations();
return;
}
if (this.indirectAncestors == null) {
fixAncestors();
}
List<TypeVariable> parentsToRemove = new LinkedList<TypeVariable>();
for (TypeVariable parent : this.parents) {
if (this.indirectAncestors.get(parent.id())) {
parentsToRemove.add(parent);
}
}
for (TypeVariable parent : parentsToRemove) {
removeParent(parent);
}
}
private void fixAncestors() {
BitVector ancestors = new BitVector(0);
BitVector indirectAncestors = new BitVector(0);
for (TypeVariable typeVariable : this.parents) {
TypeVariable parent = typeVariable.ecr();
if (parent.ancestors == null) {
parent.fixAncestors();
}
ancestors.set(parent.id);
ancestors.or(parent.ancestors);
indirectAncestors.or(parent.ancestors);
}
this.ancestors = ancestors;
this.indirectAncestors = indirectAncestors;
}
public int id() {
return (rep != this) ? ecr().id() : id;
}
public void addParent(TypeVariable variable) {
if (this.rep != this) {
ecr().addParent(variable);
return;
}
TypeVariable var = variable.ecr();
if (var == this) {
return;
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.parents);
set.add(var);
this.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(var.children);
set.add(this);
var.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public void removeParent(TypeVariable variable) {
if (this.rep != this) {
ecr().removeParent(variable);
return;
}
TypeVariable var = variable.ecr();
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.parents);
set.remove(var);
this.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(var.children);
set.remove(this);
var.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public void addChild(TypeVariable variable) {
if (this.rep != this) {
ecr().addChild(variable);
return;
}
TypeVariable var = variable.ecr();
if (var == this) {
return;
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.children);
set.add(var);
this.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(var.parents);
set.add(this);
var.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public void removeChild(TypeVariable variable) {
if (this.rep != this) {
ecr().removeChild(variable);
return;
}
TypeVariable var = variable.ecr();
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.children);
set.remove(var);
this.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(var.parents);
set.remove(this);
var.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public int depth() {
return (rep != this) ? ecr().depth() : depth;
}
public void makeElement() {
if (rep != this) {
ecr().makeElement();
return;
}
if (element == null) {
element = resolver.typeVariable();
element.array = this;
}
}
public TypeVariable element() {
if (rep != this) {
return ecr().element();
} else {
return (element == null) ? null : element.ecr();
}
}
public TypeVariable array() {
if (rep != this) {
return ecr().array();
} else {
return (array == null) ? null : array.ecr();
}
}
public List<TypeVariable> parents() {
return (rep != this) ? ecr().parents() : parents;
}
public List<TypeVariable> children() {
return (rep != this) ? ecr().children() : children;
}
public TypeNode approx() {
return (rep != this) ? ecr().approx() : approx;
}
public TypeNode type() {
return (rep != this) ? ecr().type() : type;
}
static void error(String message) throws TypeException {
TypeException e = new TypeException(message);
if (DEBUG) {
logger.error(e.getMessage(), e);
}
throw e;
}
/**
* Computes approximative types. The work list must be initialized with all constant type variables.
*/
public static void computeApprox(TreeSet<TypeVariable> workList) throws TypeException {
while (workList.size() > 0) {
TypeVariable var = workList.first();
workList.remove(var);
var.fixApprox(workList);
}
}
private void fixApprox(TreeSet<TypeVariable> workList) throws TypeException {
if (rep != this) {
ecr().fixApprox(workList);
return;
}
if (type == null && approx != resolver.hierarchy().NULL) {
TypeVariable element = element();
if (element != null) {
if (!approx.hasElement()) {
logger.debug("*** " + this + " ***");
error("Type Error(4)");
}
TypeNode temp = approx.element();
if (element.approx == null) {
element.approx = temp;
workList.add(element);
} else {
TypeNode type = element.approx.lca(temp);
if (type != element.approx) {
element.approx = type;
workList.add(element);
} else if (element.approx != resolver.hierarchy().INT) {
type = approx.lca(element.approx.array());
if (type != approx) {
approx = type;
workList.add(this);
}
}
}
}
TypeVariable array = array();
if (array != null && approx != resolver.hierarchy().NULL && approx != resolver.hierarchy().INT) {
TypeNode temp = approx.array();
if (array.approx == null) {
array.approx = temp;
workList.add(array);
} else {
TypeNode type = array.approx.lca(temp);
if (type != array.approx) {
array.approx = type;
workList.add(array);
} else {
type = approx.lca(array.approx.element());
if (type != approx) {
approx = type;
workList.add(this);
}
}
}
}
}
for (TypeVariable typeVariable : parents) {
TypeVariable parent = typeVariable.ecr();
if (parent.approx == null) {
parent.approx = approx;
workList.add(parent);
} else {
TypeNode type = parent.approx.lca(approx);
if (type != parent.approx) {
parent.approx = type;
workList.add(parent);
}
}
}
if (type != null) {
approx = type;
}
}
public void fixDepth() throws TypeException {
if (rep != this) {
ecr().fixDepth();
return;
}
if (type != null) {
if (type.type() instanceof ArrayType) {
ArrayType at = (ArrayType) type.type();
depth = at.numDimensions;
} else {
depth = 0;
}
} else {
if (approx.type() instanceof ArrayType) {
ArrayType at = (ArrayType) approx.type();
depth = at.numDimensions;
} else {
depth = 0;
}
}
// make sure array types have element type
if (depth == 0 && element() != null) {
error("Type Error(11)");
} else if (depth > 0 && element() == null) {
makeElement();
TypeVariable element = element();
element.depth = depth - 1;
while (element.depth != 0) {
element.makeElement();
element.element().depth = element.depth - 1;
element = element.element();
}
}
}
public void propagate() {
if (rep != this) {
ecr().propagate();
}
if (depth == 0) {
return;
}
for (TypeVariable typeVariable : parents) {
TypeVariable var = typeVariable.ecr();
int varDepth = var.depth();
if (varDepth == depth) {
element().addParent(var.element());
} else if (varDepth == 0) {
if (var.type() == null) {
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
var.addChild(resolver.typeVariable(resolver.hierarchy().CLONEABLE));
var.addChild(resolver.typeVariable(resolver.hierarchy().SERIALIZABLE));
}
}
} else {
if (var.type() == null) {
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
var.addChild(resolver.typeVariable(ArrayType.v(RefType.v("java.lang.Cloneable"), varDepth)));
var.addChild(resolver.typeVariable(ArrayType.v(RefType.v("java.io.Serializable"), varDepth)));
}
}
}
}
for (TypeVariable var : parents) {
removeParent(var);
}
}
@Override
public String toString() {
if (rep != this) {
return ecr().toString();
}
StringBuilder s = new StringBuilder();
s.append("[id:").append(id).append(",depth:").append(depth);
if (type != null) {
s.append(",type:").append(type);
}
s.append(",approx:").append(approx);
s.append(",[parents:");
{
boolean comma = false;
for (TypeVariable typeVariable : parents) {
if (comma) {
s.append(',');
} else {
comma = true;
}
s.append(typeVariable.id());
}
}
s.append("],[children:");
{
boolean comma = false;
for (TypeVariable typeVariable : children) {
if (comma) {
s.append(',');
} else {
comma = true;
}
s.append(typeVariable.id());
}
}
s.append(']');
if (element != null) {
s.append(",arrayof:").append(element.id());
}
s.append(']');
return s.toString();
}
public void fixParents() {
if (rep != this) {
ecr().fixParents();
return;
}
parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(new TreeSet<TypeVariable>(parents)));
}
public void fixChildren() {
if (rep != this) {
ecr().fixChildren();
return;
}
children = Collections.unmodifiableList(new LinkedList<TypeVariable>(new TreeSet<TypeVariable>(children)));
}
}
| 16,266
| 24.377535
| 111
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/TypeVariableBV.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.RefType;
import soot.options.Options;
import soot.util.BitSetIterator;
import soot.util.BitVector;
/**
* Represents a type variable.
*
* @deprecated use {@link soot.jimple.toolkits.typing.fast.TypeResolver} instead
**/
@Deprecated
class TypeVariableBV implements Comparable<Object> {
private static final Logger logger = LoggerFactory.getLogger(TypeVariableBV.class);
private static final boolean DEBUG = false;
private final int id;
private final TypeResolverBV resolver;
private TypeVariableBV rep = this;
private int rank = 0;
private TypeNode approx;
private TypeNode type;
private TypeVariableBV array;
private TypeVariableBV element;
private int depth;
private BitVector parents = new BitVector();
private BitVector children = new BitVector();
private BitVector ancestors;
private BitVector indirectAncestors;
public TypeVariableBV(int id, TypeResolverBV resolver) {
this.id = id;
this.resolver = resolver;
}
public TypeVariableBV(int id, TypeResolverBV resolver, TypeNode type) {
this.id = id;
this.resolver = resolver;
this.type = type;
approx = type;
for (Iterator<TypeNode> parentIt = type.parents().iterator(); parentIt.hasNext();) {
final TypeNode parent = parentIt.next();
addParent(resolver.typeVariable(parent));
}
if (type.hasElement()) {
element = resolver.typeVariable(type.element());
element.array = this;
}
}
public int hashCode() {
if (rep != this) {
return ecr().hashCode();
}
return id;
}
public boolean equals(Object obj) {
if (rep != this) {
return ecr().equals(obj);
}
if (obj == null) {
return false;
}
if (!obj.getClass().equals(getClass())) {
return false;
}
TypeVariableBV ecr = ((TypeVariableBV) obj).ecr();
if (ecr != this) {
return false;
}
return true;
}
public int compareTo(Object o) {
if (rep != this) {
return ecr().compareTo(o);
}
return id - ((TypeVariableBV) o).ecr().id;
}
private TypeVariableBV ecr() {
if (rep != this) {
rep = rep.ecr();
}
return rep;
}
public TypeVariableBV union(TypeVariableBV var) throws TypeException {
if (rep != this) {
return ecr().union(var);
}
TypeVariableBV y = var.ecr();
if (this == y) {
parents.clear(var.ownId());
children.clear(var.ownId());
return this;
}
if (rank > y.rank) {
resolver.invalidateId(y.id());
y.rep = this;
merge(y);
y.clear();
return this;
}
resolver.invalidateId(this.id());
rep = y;
if (rank == y.rank) {
y.rank++;
}
y.merge(this);
clear();
return y;
}
private void clear() {
approx = null;
type = null;
element = null;
array = null;
parents = null;
children = null;
ancestors = null;
indirectAncestors = null;
}
private void merge(TypeVariableBV var) throws TypeException {
if (depth != 0 || var.depth != 0) {
throw new InternalTypingException();
}
// Merge types
if (type == null) {
type = var.type;
} else if (var.type != null) {
error("Type Error(1): Attempt to merge two types.");
}
parents.or(var.parents);
parents.clear(var.ownId());
parents.clear(this.ownId());
children.or(var.children);
children.clear(var.ownId());
children.clear(this.ownId());
}
void validate() throws TypeException {
if (rep != this) {
ecr().validate();
return;
}
// Validate relations.
if (type != null) {
for (BitSetIterator i = parents.iterator(); i.hasNext();) {
TypeVariableBV parent = resolver.typeVariableForId(i.next()).ecr();
if (parent.type != null) {
if (!type.hasAncestor(parent.type)) {
if (DEBUG) {
logger.debug("" + parent.type + " is not a parent of " + type);
}
error("Type Error(2): Parent type is not a valid ancestor.");
}
}
}
for (BitSetIterator i = children.iterator(); i.hasNext();) {
TypeVariableBV child = resolver.typeVariableForId(i.next()).ecr();
if (child.type != null) {
if (!type.hasDescendant(child.type)) {
if (DEBUG) {
logger.debug("" + child.type + "(" + child + ") is not a child of " + type + "(" + this + ")");
}
error("Type Error(3): Child type is not a valid descendant.");
}
}
}
}
}
public void removeIndirectRelations() {
if (rep != this) {
ecr().removeIndirectRelations();
return;
}
if (indirectAncestors == null) {
fixAncestors();
}
BitVector parentsToRemove = new BitVector();
for (BitSetIterator parentIt = parents.iterator(); parentIt.hasNext();) {
final int parent = parentIt.next();
if (indirectAncestors.get(parent)) {
parentsToRemove.set(parent);
}
}
for (BitSetIterator i = parentsToRemove.iterator(); i.hasNext();) {
removeParent(resolver.typeVariableForId(i.next()));
}
}
private void fixAncestors() {
BitVector ancestors = new BitVector(0);
BitVector indirectAncestors = new BitVector(0);
fixParents();
for (BitSetIterator i = parents.iterator(); i.hasNext();) {
TypeVariableBV parent = resolver.typeVariableForId(i.next()).ecr();
if (parent.ancestors == null) {
parent.fixAncestors();
}
ancestors.set(parent.id);
ancestors.or(parent.ancestors);
indirectAncestors.or(parent.ancestors);
}
this.ancestors = ancestors;
this.indirectAncestors = indirectAncestors;
}
private void fixParents() {
if (rep != this) {
ecr().fixParents();
}
BitVector invalid = new BitVector();
invalid.or(parents);
invalid.and(resolver.invalidIds());
for (BitSetIterator i = invalid.iterator(); i.hasNext();) {
parents.set(resolver.typeVariableForId(i.next()).id());
}
parents.clear(this.id);
parents.clear(this.id());
parents.andNot(invalid);
}
public int id() {
if (rep != this) {
return ecr().id();
}
return id;
}
public int ownId() {
return id;
}
public void addParent(TypeVariableBV variable) {
if (rep != this) {
ecr().addParent(variable);
return;
}
TypeVariableBV var = variable.ecr();
if (var == this) {
return;
}
parents.set(var.id);
var.children.set(this.id);
}
public void removeParent(TypeVariableBV variable) {
if (rep != this) {
ecr().removeParent(variable);
return;
}
parents.clear(variable.id());
parents.clear(variable.ownId());
variable.children().clear(this.id);
}
public void addChild(TypeVariableBV variable) {
if (rep != this) {
ecr().addChild(variable);
return;
}
TypeVariableBV var = variable.ecr();
if (var == this) {
return;
}
children.set(var.id);
parents.set(var.id);
}
public void removeChild(TypeVariableBV variable) {
if (rep != this) {
ecr().removeChild(variable);
return;
}
TypeVariableBV var = variable.ecr();
children.clear(var.id);
var.parents.clear(var.id);
}
public int depth() {
if (rep != this) {
return ecr().depth();
}
return depth;
}
public void makeElement() {
if (rep != this) {
ecr().makeElement();
return;
}
if (element == null) {
element = resolver.typeVariable();
element.array = this;
}
}
public TypeVariableBV element() {
if (rep != this) {
return ecr().element();
}
return (element == null) ? null : element.ecr();
}
public TypeVariableBV array() {
if (rep != this) {
return ecr().array();
}
return (array == null) ? null : array.ecr();
}
public BitVector parents() {
if (rep != this) {
return ecr().parents();
}
return parents;
}
public BitVector children() {
if (rep != this) {
return ecr().children();
}
return children;
}
public TypeNode approx() {
if (rep != this) {
return ecr().approx();
}
return approx;
}
public TypeNode type() {
if (rep != this) {
return ecr().type();
}
return type;
}
static void error(String message) throws TypeException {
try {
throw new TypeException(message);
} catch (TypeException e) {
if (DEBUG) {
logger.error(e.getMessage(), e);
}
throw e;
}
}
/**
* Computes approximative types. The work list must be initialized with all constant type variables.
*/
public static void computeApprox(TreeSet<TypeVariableBV> workList) throws TypeException {
while (workList.size() > 0) {
TypeVariableBV var = workList.first();
workList.remove(var);
var.fixApprox(workList);
}
}
private void fixApprox(TreeSet<TypeVariableBV> workList) throws TypeException {
if (rep != this) {
ecr().fixApprox(workList);
return;
}
if (type == null && approx != resolver.hierarchy().NULL) {
TypeVariableBV element = element();
if (element != null) {
if (!approx.hasElement()) {
logger.debug("*** " + this + " ***");
error("Type Error(4)");
}
TypeNode temp = approx.element();
if (element.approx == null) {
element.approx = temp;
workList.add(element);
} else {
TypeNode type = element.approx.lca(temp);
if (type != element.approx) {
element.approx = type;
workList.add(element);
} else if (element.approx != resolver.hierarchy().INT) {
type = approx.lca(element.approx.array());
if (type != approx) {
approx = type;
workList.add(this);
}
}
}
}
TypeVariableBV array = array();
if (array != null && approx != resolver.hierarchy().NULL && approx != resolver.hierarchy().INT) {
TypeNode temp = approx.array();
if (array.approx == null) {
array.approx = temp;
workList.add(array);
} else {
TypeNode type = array.approx.lca(temp);
if (type != array.approx) {
array.approx = type;
workList.add(array);
} else {
type = approx.lca(array.approx.element());
if (type != approx) {
approx = type;
workList.add(this);
}
}
}
}
}
for (BitSetIterator i = parents.iterator(); i.hasNext();) {
TypeVariableBV parent = resolver.typeVariableForId(i.next()).ecr();
if (parent.approx == null) {
parent.approx = approx;
workList.add(parent);
} else {
TypeNode type = parent.approx.lca(approx);
if (type != parent.approx) {
parent.approx = type;
workList.add(parent);
}
}
}
if (type != null) {
approx = type;
}
}
public void fixDepth() throws TypeException {
if (rep != this) {
ecr().fixDepth();
return;
}
if (type != null) {
if (type.type() instanceof ArrayType) {
ArrayType at = (ArrayType) type.type();
depth = at.numDimensions;
} else {
depth = 0;
}
} else {
if (approx.type() instanceof ArrayType) {
ArrayType at = (ArrayType) approx.type();
depth = at.numDimensions;
} else {
depth = 0;
}
}
// make sure array types have element type
if (depth == 0 && element() != null) {
error("Type Error(11)");
} else if (depth > 0 && element() == null) {
makeElement();
TypeVariableBV element = element();
element.depth = depth - 1;
while (element.depth != 0) {
element.makeElement();
element.element().depth = element.depth - 1;
element = element.element();
}
}
}
public void propagate() {
if (rep != this) {
ecr().propagate();
}
if (depth == 0) {
return;
}
for (BitSetIterator i = parents.iterator(); i.hasNext();) {
TypeVariableBV var = resolver.typeVariableForId(i.next()).ecr();
if (var.depth() == depth) {
element().addParent(var.element());
} else if (var.depth() == 0) {
if (var.type() == null) {
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
var.addChild(resolver.typeVariable(resolver.hierarchy().CLONEABLE));
var.addChild(resolver.typeVariable(resolver.hierarchy().SERIALIZABLE));
}
}
} else {
if (var.type() == null) {
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
var.addChild(resolver.typeVariable(ArrayType.v(RefType.v("java.lang.Cloneable"), var.depth())));
var.addChild(resolver.typeVariable(ArrayType.v(RefType.v("java.io.Serializable"), var.depth())));
}
}
}
}
for (BitSetIterator varIt = parents.iterator(); varIt.hasNext();) {
final TypeVariableBV var = resolver.typeVariableForId(varIt.next());
removeParent(var);
}
}
public String toString() {
if (rep != this) {
return ecr().toString();
}
StringBuffer s = new StringBuffer();
s.append(",[parents:");
{
boolean comma = false;
for (BitSetIterator i = parents.iterator(); i.hasNext();) {
if (comma) {
s.append(",");
} else {
comma = true;
}
s.append(i.next());
}
}
s.append("],[children:");
{
boolean comma = false;
for (BitSetIterator i = children.iterator(); i.hasNext();) {
if (comma) {
s.append(",");
} else {
comma = true;
}
s.append(i.next());
}
}
s.append("]");
return "[id:" + id + ",depth:" + depth + ((type != null) ? (",type:" + type) : "") + ",approx:" + approx + s
+ (element == null ? "" : ",arrayof:" + element.id()) + "]";
}
}
| 15,280
| 22.013554
| 112
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/Util.java
|
package soot.jimple.toolkits.typing;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Body;
import soot.Unit;
import soot.jimple.IdentityStmt;
import soot.jimple.Stmt;
import soot.util.Chain;
public class Util {
/**
* A new "normal" statement cannot be inserted in the middle of special "identity statements" (a = @parameter or b = @this
* in Jimple).
*
* This method returns the last "identity statement" of the method.
*
* @param b
* @param s
* @return
*/
public static Unit findLastIdentityUnit(Body b, Stmt s) {
final Chain<Unit> units = b.getUnits();
Unit u2 = s;
for (Unit u1 = u2; u1 instanceof IdentityStmt;) {
u2 = u1;
u1 = units.getSuccOf(u1);
}
return u2;
}
/**
* Returns the first statement after all the "identity statements".
*
* @param b
* @param s
* @return
*/
public static Unit findFirstNonIdentityUnit(Body b, Stmt s) {
final Chain<Unit> units = b.getUnits();
Unit u1 = s;
while (u1 instanceof IdentityStmt) {
u1 = units.getSuccOf(u1);
}
return u1;
}
private Util() {
}
}
| 1,896
| 25.347222
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/AugEvalFunction.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.Collections;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.IntegerType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.RefLikeType;
import soot.RefType;
import soot.Scene;
import soot.ShortType;
import soot.TrapManager;
import soot.Type;
import soot.Value;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.EqExpr;
import soot.jimple.FieldRef;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GtExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LtExpr;
import soot.jimple.MethodHandle;
import soot.jimple.MethodType;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.ParameterRef;
import soot.jimple.RemExpr;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.ThisRef;
import soot.jimple.UshrExpr;
import soot.jimple.XorExpr;
/**
* @author Ben Bellamy
*/
public class AugEvalFunction implements IEvalFunction {
private final JimpleBody jb;
public AugEvalFunction(JimpleBody jb) {
this.jb = jb;
}
public static Type eval_(Typing tg, Value expr, Stmt stmt, JimpleBody jb) {
if (expr instanceof ThisRef) {
return ((ThisRef) expr).getType();
} else if (expr instanceof ParameterRef) {
return ((ParameterRef) expr).getType();
} else if (expr instanceof Local) {
// Changed to prevent null pointer exception in case of phantom classes where a null typing is
// encountered. -syed
return (tg == null) ? null : tg.get((Local) expr);
} else if (expr instanceof BinopExpr) {
BinopExpr be = (BinopExpr) expr;
Type tl = eval_(tg, be.getOp1(), stmt, jb), tr = eval_(tg, be.getOp2(), stmt, jb);
if (expr instanceof CmpExpr || expr instanceof CmpgExpr || expr instanceof CmplExpr) {
return ByteType.v();
} else if (expr instanceof GeExpr || expr instanceof GtExpr || expr instanceof LeExpr || expr instanceof LtExpr
|| expr instanceof EqExpr || expr instanceof NeExpr) {
return BooleanType.v();
} else if (expr instanceof ShlExpr || expr instanceof ShrExpr || expr instanceof UshrExpr) {
// In the JVM, there are op codes for integer and long only. In Java, the code
// {@code short s = 2; s = s << s;} does not compile, since s << s is an integer.
return (tl instanceof IntegerType) ? IntType.v() : tl;
} else if (expr instanceof AddExpr || expr instanceof SubExpr || expr instanceof MulExpr || expr instanceof DivExpr
|| expr instanceof RemExpr) {
return (tl instanceof IntegerType) ? IntType.v() : tl;
} else if (expr instanceof AndExpr || expr instanceof OrExpr || expr instanceof XorExpr) {
if (tl instanceof IntegerType && tr instanceof IntegerType) {
if (tl instanceof BooleanType) {
return (tr instanceof BooleanType) ? BooleanType.v() : tr;
} else if (tr instanceof BooleanType) {
return tl;
} else {
Collection<Type> rs = AugHierarchy.lcas_(tl, tr, false);
if (rs.isEmpty()) {
throw new RuntimeException();
} else {
// AugHierarchy.lcas_ is single-valued
assert (rs.size() == 1);
return rs.iterator().next();
}
}
} else {
return (tl instanceof RefLikeType) ? tr : tl;
}
} else {
throw new RuntimeException("Unhandled binary expression: " + expr);
}
} else if (expr instanceof NegExpr) {
Type t = eval_(tg, ((NegExpr) expr).getOp(), stmt, jb);
if (t instanceof IntegerType) {
//The "ineg" bytecode causes and implicit widening to int type and produces an int type.
return IntType.v();
} else {
return t;
}
} else if (expr instanceof CaughtExceptionRef) {
RefType throwableType = Scene.v().getRefType("java.lang.Throwable");
RefType r = null;
for (RefType t : TrapManager.getExceptionTypesOf(stmt, jb)) {
if (t.getSootClass().isPhantom()) {
r = throwableType;
} else if (r == null) {
r = t;
} else {
/*
* In theory, we could have multiple exception types pointing here. The JLS requires the exception parameter be a
* *subclass* of Throwable, so we do not need to worry about multiple inheritance.
*/
r = BytecodeHierarchy.lcsc(r, t, throwableType);
}
}
if (r == null) {
throw new RuntimeException("Exception reference used other than as the first statement of an exception handler.");
}
return r;
} else if (expr instanceof ArrayRef) {
Type at = tg.get((Local) ((ArrayRef) expr).getBase());
if (at instanceof ArrayType) {
return ((ArrayType) at).getElementType();
} else if (at instanceof WeakObjectType) {
return at;
} else if (at instanceof RefType) {
String name = ((RefType) at).getSootClass().getName();
switch (name) {
case "java.lang.Cloneable":
case "java.lang.Object":
case "java.io.Serializable":
return new WeakObjectType(name);
default:
return BottomType.v();
}
} else {
return BottomType.v();
}
} else if (expr instanceof NewArrayExpr) {
return ((NewArrayExpr) expr).getBaseType().makeArrayType();
} else if (expr instanceof NewMultiArrayExpr) {
return ((NewMultiArrayExpr) expr).getBaseType();
} else if (expr instanceof CastExpr) {
return ((CastExpr) expr).getCastType();
} else if (expr instanceof InstanceOfExpr) {
return BooleanType.v();
} else if (expr instanceof LengthExpr) {
return IntType.v();
} else if (expr instanceof InvokeExpr) {
return ((InvokeExpr) expr).getMethodRef().getReturnType();
} else if (expr instanceof NewExpr) {
return ((NewExpr) expr).getBaseType();
} else if (expr instanceof FieldRef) {
return ((FieldRef) expr).getType();
} else if (expr instanceof DoubleConstant) {
return DoubleType.v();
} else if (expr instanceof FloatConstant) {
return FloatType.v();
} else if (expr instanceof IntConstant) {
int value = ((IntConstant) expr).value;
if (value >= 0 && value < 2) {
return Integer1Type.v();
} else if (value >= 2 && value < 128) {
return Integer127Type.v();
} else if (value >= -128 && value < 0) {
return ByteType.v();
} else if (value >= 128 && value < 32768) {
return Integer32767Type.v();
} else if (value >= -32768 && value < -128) {
return ShortType.v();
} else if (value >= 32768 && value < 65536) {
return CharType.v();
} else {
return IntType.v();
}
} else if (expr instanceof LongConstant) {
return LongType.v();
} else if (expr instanceof NullConstant) {
return NullType.v();
} else if (expr instanceof StringConstant) {
return RefType.v("java.lang.String");
} else if (expr instanceof ClassConstant) {
return RefType.v("java.lang.Class");
} else if (expr instanceof MethodHandle) {
return RefType.v("java.lang.invoke.MethodHandle");
} else if (expr instanceof MethodType) {
return RefType.v("java.lang.invoke.MethodType");
} else {
throw new RuntimeException("Unhandled expression: " + expr);
}
}
@Override
public Collection<Type> eval(Typing tg, Value expr, Stmt stmt) {
return Collections.<Type>singletonList(eval_(tg, expr, stmt, this.jb));
}
}
| 9,415
| 35.355212
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/AugHierarchy.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.Collections;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.IntType;
import soot.IntegerType;
import soot.ShortType;
import soot.Type;
/**
* @author Ben Bellamy
*/
public class AugHierarchy implements IHierarchy {
public static Collection<Type> lcas_(Type a, Type b, boolean useWeakObjectType) {
if (TypeResolver.typesEqual(a, b)) {
return Collections.<Type>singletonList(a);
} else if (a instanceof BottomType) {
return Collections.<Type>singletonList(b);
} else if (b instanceof BottomType) {
return Collections.<Type>singletonList(a);
} else if (a instanceof WeakObjectType) {
return Collections.<Type>singletonList(b);
} else if (b instanceof WeakObjectType) {
return Collections.<Type>singletonList(a);
} else if (a instanceof IntegerType && b instanceof IntegerType) {
if (a instanceof Integer1Type) {
return Collections.<Type>singletonList(b);
} else if (b instanceof Integer1Type) {
return Collections.<Type>singletonList(a);
} else if (a instanceof BooleanType || b instanceof BooleanType) {
return Collections.<Type>emptyList();
} else if ((a instanceof ByteType && b instanceof Integer32767Type)
|| (b instanceof ByteType && a instanceof Integer32767Type)) {
return Collections.<Type>singletonList(ShortType.v());
} else if ((a instanceof CharType && (b instanceof ShortType || b instanceof ByteType))
|| (b instanceof CharType && (a instanceof ShortType || a instanceof ByteType))) {
return Collections.<Type>singletonList(IntType.v());
} else if (ancestor_(a, b)) {
return Collections.<Type>singletonList(a);
} else {
return Collections.<Type>singletonList(b);
}
} else if (a instanceof IntegerType || b instanceof IntegerType) {
return Collections.<Type>emptyList();
} else {
return BytecodeHierarchy.lcas_(a, b, useWeakObjectType);
}
}
public static boolean ancestor_(Type ancestor, Type child) {
if (TypeResolver.typesEqual(ancestor, child)) {
return true;
} else if (ancestor instanceof ArrayType && child instanceof ArrayType) {
// Arrays are not covariant. However, we may have intermediate types that will later be replaced with actual types. In
// that case, we consider the temporary type as compatible with a final type of sufficient size. Note that these checks
// are more strict than the non-arrays checks on Integer types below.
Type at = ((ArrayType) ancestor).getElementType();
Type ct = ((ArrayType) child).getElementType();
if (at instanceof Integer1Type) {
return ct instanceof BottomType;
} else if (at instanceof BooleanType) {
return ct instanceof BottomType || ct instanceof Integer1Type;
} else if (at instanceof Integer127Type) {
return ct instanceof BottomType || ct instanceof Integer1Type;
} else if (at instanceof ByteType || at instanceof Integer32767Type) {
return ct instanceof BottomType || ct instanceof Integer1Type || ct instanceof Integer127Type;
} else if (at instanceof CharType) {
return ct instanceof BottomType || ct instanceof Integer1Type || ct instanceof Integer127Type
|| ct instanceof Integer32767Type;
} else if (ancestor instanceof ShortType) {
return ct instanceof BottomType || ct instanceof Integer1Type || ct instanceof Integer127Type
|| ct instanceof Integer32767Type;
} else if (at instanceof IntType) {
return ct instanceof BottomType || ct instanceof Integer1Type || ct instanceof Integer127Type
|| ct instanceof Integer32767Type;
} else if (ct instanceof IntegerType) {
return false;
} else {
return BytecodeHierarchy.ancestor_(ancestor, child);
}
} else if (ancestor instanceof IntegerType && child instanceof IntegerType) {
return IntUtils.getMaxValue((IntegerType) ancestor) >= IntUtils.getMaxValue((IntegerType) child);
} else if (ancestor instanceof Integer1Type) {
return child instanceof BottomType;
} else if (ancestor instanceof BooleanType) {
return child instanceof BottomType || child instanceof Integer1Type;
} else if (ancestor instanceof Integer127Type) {
return child instanceof BottomType || child instanceof Integer1Type;
} else if (ancestor instanceof ByteType || ancestor instanceof Integer32767Type) {
return child instanceof BottomType || child instanceof Integer1Type || child instanceof Integer127Type;
} else if (ancestor instanceof CharType) {
return child instanceof BottomType || child instanceof Integer1Type || child instanceof Integer127Type
|| child instanceof Integer32767Type;
} else if (ancestor instanceof ShortType) {
return child instanceof BottomType || child instanceof Integer1Type || child instanceof Integer127Type
|| child instanceof Integer32767Type || child instanceof ByteType;
} else if (ancestor instanceof IntType) {
return child instanceof BottomType || child instanceof Integer1Type || child instanceof Integer127Type
|| child instanceof Integer32767Type || child instanceof ByteType || child instanceof CharType
|| child instanceof ShortType;
} else if (child instanceof IntegerType) {
return false;
} else {
return BytecodeHierarchy.ancestor_(ancestor, child);
}
}
@Override
public Collection<Type> lcas(Type a, Type b, boolean useWeakObjectType) {
return lcas_(a, b, useWeakObjectType);
}
@Override
public boolean ancestor(Type ancestor, Type child) {
return ancestor_(ancestor, child);
}
}
| 6,680
| 44.141892
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/BottomType.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.G;
import soot.Singletons;
import soot.Type;
/**
* @author Ben Bellamy
*/
public class BottomType extends Type {
public static BottomType v() {
return G.v().soot_jimple_toolkits_typing_fast_BottomType();
}
public BottomType(Singletons.Global g) {
}
@Override
public String toString() {
return "bottom_type";
}
@Override
public boolean equals(Object t) {
return this == t;
}
}
| 1,295
| 23.45283
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/BytecodeHierarchy.java
|
package soot.jimple.toolkits.typing.fast;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.ListIterator;
import soot.ArrayType;
import soot.FloatType;
import soot.IntegerType;
import soot.NullType;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.Type;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* @author Ben Bellamy
*/
public class BytecodeHierarchy implements IHierarchy {
/*
* Returns a collection of nodes, each with type Object, each at the leaf end of a different path from root to Object.
*/
private static Collection<AncestryTreeNode> buildAncestryTree(RefType root) {
if (root.getSootClass().isPhantom()) {
return Collections.emptyList();
}
LinkedList<AncestryTreeNode> leafs = new LinkedList<AncestryTreeNode>();
leafs.add(new AncestryTreeNode(null, root));
LinkedList<AncestryTreeNode> r = new LinkedList<AncestryTreeNode>();
final RefType objectType = RefType.v("java.lang.Object");
while (!leafs.isEmpty()) {
AncestryTreeNode node = leafs.remove();
if (TypeResolver.typesEqual(node.type, objectType)) {
r.add(node);
} else {
SootClass sc = node.type.getSootClass();
for (SootClass i : sc.getInterfaces()) {
leafs.add(new AncestryTreeNode(node, (i).getType()));
}
// The superclass of all interfaces is Object
// -- try to discard phantom interfaces.
if ((!sc.isInterface() || sc.getInterfaceCount() == 0) && !sc.isPhantom() && sc.hasSuperclass()) {
leafs.add(new AncestryTreeNode(node, sc.getSuperclass().getType()));
}
}
}
return r;
}
private static RefType leastCommonNode(AncestryTreeNode a, AncestryTreeNode b) {
RefType r = null;
while (a != null && b != null && TypeResolver.typesEqual(a.type, b.type)) {
r = a.type;
a = a.next;
b = b.next;
}
return r;
}
public static Collection<Type> lcas_(Type a, Type b) {
return lcas_(a, b, false);
}
public static Collection<Type> lcas_(Type a, Type b, boolean useWeakObjectType) {
if (TypeResolver.typesEqual(a, b)) {
return Collections.<Type>singletonList(a);
} else if (a instanceof BottomType) {
return Collections.<Type>singletonList(b);
} else if (b instanceof BottomType) {
return Collections.<Type>singletonList(a);
} else if (a instanceof WeakObjectType && b instanceof RefType) {
return Collections.<Type>singletonList(b);
} else if (b instanceof WeakObjectType && a instanceof RefType) {
return Collections.<Type>singletonList(a);
} else if (a instanceof IntegerType && b instanceof IntegerType) {
int m = Math.max(IntUtils.getMaxValue((IntegerType) a), IntUtils.getMaxValue((IntegerType) b));
return Collections.<Type>singletonList((Type) IntUtils.getTypeByWidth(m));
} else if (a instanceof IntegerType && b instanceof FloatType) {
return Collections.<Type>singletonList(FloatType.v());
} else if (b instanceof IntegerType && a instanceof FloatType) {
return Collections.<Type>singletonList(FloatType.v());
} else if (a instanceof PrimType || b instanceof PrimType) {
return Collections.<Type>emptyList();
} else if (a instanceof NullType) {
return Collections.<Type>singletonList(b);
} else if (b instanceof NullType) {
return Collections.<Type>singletonList(a);
} else if (a instanceof ArrayType && b instanceof ArrayType) {
Type eta = ((ArrayType) a).getElementType(), etb = ((ArrayType) b).getElementType();
Collection<Type> ts;
// Primitive arrays are not covariant but all other arrays are
if (eta instanceof PrimType || etb instanceof PrimType) {
ts = Collections.<Type>emptyList();
} else {
ts = lcas_(eta, etb);
}
LinkedList<Type> r = new LinkedList<Type>();
if (ts.isEmpty()) {
if (useWeakObjectType) {
r.add(new WeakObjectType("java.lang.Object"));
} else {
// From Java Language Spec 2nd ed., Chapter 10, Arrays
r.add(RefType.v("java.lang.Object"));
r.add(RefType.v("java.io.Serializable"));
r.add(RefType.v("java.lang.Cloneable"));
}
} else {
for (Type t : ts) {
r.add(t.makeArrayType());
}
}
return r;
} else if (a instanceof ArrayType || b instanceof ArrayType) {
Type rt = (a instanceof ArrayType) ? b : a;
/*
* If the reference type implements Serializable or Cloneable then these are the least common supertypes, otherwise the
* only one is Object.
*/
LinkedList<Type> r = new LinkedList<Type>();
/*
* Do not consider Object to be a subtype of Serializable or Cloneable (it can appear this way if phantom-refs is
* enabled and rt.jar is not available) otherwise an infinite loop can result.
*/
if (!TypeResolver.typesEqual(RefType.v("java.lang.Object"), rt)) {
RefType refSerializable = RefType.v("java.io.Serializable");
if (ancestor_(refSerializable, rt)) {
r.add(refSerializable);
}
RefType refCloneable = RefType.v("java.lang.Cloneable");
if (ancestor_(refCloneable, rt)) {
r.add(refCloneable);
}
}
if (r.isEmpty()) {
r.add(RefType.v("java.lang.Object"));
}
return r;
} else {
// a and b are both RefType
Collection<AncestryTreeNode> treea = buildAncestryTree((RefType) a), treeb = buildAncestryTree((RefType) b);
LinkedList<Type> r = new LinkedList<Type>();
for (AncestryTreeNode nodea : treea) {
for (AncestryTreeNode nodeb : treeb) {
RefType t = leastCommonNode(nodea, nodeb);
boolean least = true;
for (ListIterator<Type> i = r.listIterator(); i.hasNext();) {
Type t_ = i.next();
if (ancestor_(t, t_)) {
least = false;
break;
}
if (ancestor_(t_, t)) {
i.remove();
}
}
if (least) {
r.add(t);
}
}
}
// in case of phantom classes that screw up type resolution here,
// default to only possible common reftype, java.lang.Object
// kludge on a kludge on a kludge...
// syed - 05/06/2009
if (r.isEmpty()) {
r.add(RefType.v("java.lang.Object"));
}
return r;
}
}
public static boolean ancestor_(Type ancestor, Type child) {
if (TypeResolver.typesEqual(ancestor, child)) {
return true;
} else if (child instanceof BottomType) {
return true;
} else if (ancestor instanceof BottomType) {
return false;
} else if (ancestor instanceof IntegerType && child instanceof IntegerType) {
return true;
} else if (ancestor instanceof PrimType || child instanceof PrimType) {
return false;
} else if (child instanceof NullType) {
return true;
} else if (ancestor instanceof NullType) {
return false;
} else {
return Scene.v().getOrMakeFastHierarchy().canStoreType(child, ancestor);
}
}
/**
* Returns a list of the super classes of a given type in which the anchor will always be the first element even when the
* types class is phantom. Note anchor should always be type {@link Throwable} as this is the root of all exception types.
*/
private static Deque<RefType> superclassPath(RefType t, RefType anchor) {
Deque<RefType> r = new ArrayDeque<RefType>();
r.addFirst(t);
if (TypeResolver.typesEqual(t, anchor)) {
return r;
}
for (SootClass sc = t.getSootClass(); sc.hasSuperclass();) {
sc = sc.getSuperclass();
RefType cur = sc.getType();
r.addFirst(cur);
if (TypeResolver.typesEqual(cur, anchor)) {
break;
}
}
if (!TypeResolver.typesEqual(r.getFirst(), anchor)) {
r.addFirst(anchor);
}
return r;
}
public static RefType lcsc(RefType a, RefType b) {
return lcsc(a, b, null);
}
public static RefType lcsc(RefType a, RefType b, RefType anchor) {
if (a == b) {
return a;
}
Deque<RefType> pathA = superclassPath(a, anchor);
Deque<RefType> pathB = superclassPath(b, anchor);
RefType r = null;
while (!(pathA.isEmpty() || pathB.isEmpty()) && TypeResolver.typesEqual(pathA.getFirst(), pathB.getFirst())) {
r = pathA.removeFirst();
pathB.removeFirst();
}
return r;
}
@Override
public Collection<Type> lcas(Type a, Type b, boolean useWeakObjectType) {
return lcas_(a, b, useWeakObjectType);
}
@Override
public boolean ancestor(Type ancestor, Type child) {
return ancestor_(ancestor, child);
}
private static class AncestryTreeNode {
public final AncestryTreeNode next;
public final RefType type;
public AncestryTreeNode(AncestryTreeNode next, RefType type) {
this.next = next;
this.type = type;
}
}
}
| 9,913
| 31.936877
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/DefaultTypingStrategy.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import soot.Local;
import soot.RefType;
import soot.Scene;
import soot.Type;
import soot.util.Chain;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
/**
* The default typing strategy
*/
public class DefaultTypingStrategy implements ITypingStrategy {
public static final ITypingStrategy INSTANCE = new DefaultTypingStrategy();
@Override
public Typing createTyping(Chain<Local> locals) {
return new Typing(locals);
}
@Override
public Typing createTyping(Typing tg) {
return new Typing(tg);
}
public static MultiMap<Local, Type> getFlatTyping(List<Typing> tgs) {
MultiMap<Local, Type> map = new HashMultiMap<>();
for (Typing tg : tgs) {
map.putMap(tg.map);
}
return map;
}
public static Set<Local> getObjectLikeTypings(List<Typing> tgs) {
Set<Type> objectLikeTypeSet = new HashSet<>();
objectLikeTypeSet.add(Scene.v().getObjectType());
objectLikeTypeSet.add(RefType.v("java.io.Serializable"));
objectLikeTypeSet.add(RefType.v("java.lang.Cloneable"));
Set<Local> objectLikeVars = new HashSet<>();
MultiMap<Local, Type> ft = getFlatTyping(tgs);
for (Local l : ft.keySet()) {
if (objectLikeTypeSet.equals(ft.get(l))) {
objectLikeVars.add(l);
}
}
return objectLikeVars;
}
@Override
public void minimize(List<Typing> tgs, IHierarchy h) {
Set<Local> objectVars = getObjectLikeTypings(tgs);
OUTER: for (ListIterator<Typing> i = tgs.listIterator(); i.hasNext();) {
Typing tgi = i.next();
// Throw out duplicate typings
for (Typing tgj : tgs) {
// if compare = 1, then tgi is the more general typing
// We shouldn't pick that one as we would then end up
// with lots of locals typed to Serializable etc.
if (tgi != tgj && compare(tgi, tgj, h, objectVars) == 1) {
i.remove();
continue OUTER;
}
}
}
}
public int compare(Typing a, Typing b, IHierarchy h, Collection<Local> localsToIgnore) {
int r = 0;
for (Local v : a.map.keySet()) {
if (!localsToIgnore.contains(v)) {
Type ta = a.get(v), tb = b.get(v);
int cmp;
if (TypeResolver.typesEqual(ta, tb)) {
cmp = 0;
} else if (h.ancestor(ta, tb)) {
cmp = 1;
} else if (h.ancestor(tb, ta)) {
cmp = -1;
} else {
return -2;
}
if ((cmp == 1 && r == -1) || (cmp == -1 && r == 1)) {
return 2;
}
if (r == 0) {
r = cmp;
}
}
}
return r;
}
@Override
public void finalizeTypes(Typing tp) {
for (Local l : tp.getAllLocals()) {
Type t = tp.get(l);
if (!t.isAllowedInFinalCode()) {
tp.set(l, t.getDefaultFinalType());
}
}
}
}
| 3,799
| 26.142857
| 90
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/EmptyList.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.AbstractList;
/**
* @author Ben Bellamy
*/
@Deprecated
public class EmptyList<E> extends AbstractList<E> {
@Override
public E get(int index) {
throw new IndexOutOfBoundsException();
}
@Override
public int size() {
return 0;
}
}
| 1,137
| 24.863636
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/IEvalFunction.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import soot.Type;
import soot.Value;
import soot.jimple.Stmt;
/**
* @author Ben Bellamy
*/
public interface IEvalFunction {
Collection<Type> eval(Typing tg, Value expr, Stmt stmt);
}
| 1,085
| 27.578947
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/IHierarchy.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import soot.Type;
/**
* @author Ben Bellamy
*/
public interface IHierarchy {
Collection<Type> lcas(Type a, Type b, boolean useWeakObjectType);
boolean ancestor(Type ancestor, Type child);
}
| 1,095
| 27.842105
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/ITypingStrategy.java
|
package soot.jimple.toolkits.typing.fast;
import java.util.List;
import soot.Local;
import soot.util.Chain;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Provides a way to use different was to create and minimize {@link Typing}s.
*
* @author Marc Miltenberger
*/
public interface ITypingStrategy {
/**
* Creates a new {@link Typing} class instance with initialized bottom types for the given locals
*
* @param locals
* the locals
* @return the {@link Typing}
*/
public Typing createTyping(Chain<Local> locals);
/**
* Creates a new typing class as a copy from a given class
*
* @param tg
* the existing {@link Typing}
* @return the new {@link Typing}
*/
public Typing createTyping(Typing tg);
/**
* Minimize the given typing list using the hierarchy
*
* @param tgs
* the {@link Typing} list
* @param h
* the hierarchy
*/
public void minimize(List<Typing> tgs, IHierarchy h);
/**
* Finalizes the given types, i.e., converts intermediate types such as [0..1] to final types such as <code>boolean</code>.
*
* @param tp
* The typing to finalize
*/
public void finalizeTypes(Typing tp);
}
| 2,018
| 25.565789
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/IUseVisitor.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Type;
import soot.Value;
import soot.jimple.Stmt;
/**
* @author Ben Bellamy
*/
public interface IUseVisitor {
Value visit(Value op, Type useType, Stmt stmt, boolean checkOnly);
default Value visit(Value op, Type useType, Stmt stmt) {
return visit(op, useType, stmt, false);
}
boolean finish();
}
| 1,193
| 26.767442
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/IntUtils.java
|
package soot.jimple.toolkits.typing.fast;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.IntType;
import soot.IntegerType;
import soot.ShortType;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Contains several utilities for integer typing.
*
* @author Marc Miltenberger
*/
public class IntUtils {
/**
* Returns an appropriate integer for a given maximum element.
*
* Throws an exception in case of an unsupported size.
*
* @param maxValue
* the max value
* @return the integer
*/
public static IntegerType getTypeByWidth(int maxValue) {
switch (maxValue) {
case 1:
return Integer1Type.v();
case 127:
return Integer127Type.v();
case 32767:
return Integer32767Type.v();
case Integer.MAX_VALUE:
return IntType.v();
default:
throw new RuntimeException("Unsupported width: " + maxValue);
}
}
/**
* Returns the maximum value an integer type can have.
*
* @param t
* the integer type
* @return the maximum value
*/
public static int getMaxValue(IntegerType t) {
if (t instanceof Integer1Type || t instanceof BooleanType) {
return 1;
}
if (t instanceof Integer127Type || t instanceof ByteType) {
return 127;
}
if (t instanceof Integer32767Type || t instanceof ShortType || t instanceof CharType) {
return 32767;
}
if (t instanceof IntType) {
return Integer.MAX_VALUE;
}
throw new RuntimeException("Unsupported type: " + t);
}
}
| 2,357
| 25.494382
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/Integer127Type.java
|
package soot.jimple.toolkits.typing.fast;
import soot.ByteType;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.G;
import soot.IntegerType;
import soot.PrimType;
import soot.RefType;
import soot.Singletons;
import soot.Type;
/**
* @author Ben Bellamy
*/
public class Integer127Type extends PrimType implements IntegerType {
public static Integer127Type v() {
return G.v().soot_jimple_toolkits_typing_fast_Integer127Type();
}
public Integer127Type(Singletons.Global g) {
}
@Override
public String toString() {
return "[0..127]";
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public RefType boxedType() {
return RefType.v("java.lang.Integer");
}
@Override
public boolean isAllowedInFinalCode() {
return false;
}
@Override
public Type getDefaultFinalType() {
return ByteType.v();
}
@Override
public Class<?> getJavaBoxedType() {
return Integer.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return int.class;
}
}
| 1,839
| 20.904762
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/Integer1Type.java
|
package soot.jimple.toolkits.typing.fast;
import soot.BooleanType;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.G;
import soot.IntegerType;
import soot.PrimType;
import soot.RefType;
import soot.Singletons;
import soot.Type;
/**
* @author Ben Bellamy
*/
public class Integer1Type extends PrimType implements IntegerType {
public static Integer1Type v() {
return G.v().soot_jimple_toolkits_typing_fast_Integer1Type();
}
public Integer1Type(Singletons.Global g) {
}
@Override
public String toString() {
return "[0..1]";
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public RefType boxedType() {
return RefType.v("java.lang.Integer");
}
@Override
public boolean isAllowedInFinalCode() {
return false;
}
@Override
public Type getDefaultFinalType() {
return BooleanType.v();
}
@Override
public Class<?> getJavaBoxedType() {
return Integer.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return int.class;
}
}
| 1,835
| 20.857143
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/Integer32767Type.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.G;
import soot.IntegerType;
import soot.PrimType;
import soot.RefType;
import soot.ShortType;
import soot.Singletons;
import soot.Type;
/**
* @author Ben Bellamy
*/
public class Integer32767Type extends PrimType implements IntegerType {
public static Integer32767Type v() {
return G.v().soot_jimple_toolkits_typing_fast_Integer32767Type();
}
public Integer32767Type(Singletons.Global g) {
}
@Override
public String toString() {
return "[0..32767]";
}
@Override
public boolean equals(Object t) {
return this == t;
}
@Override
public RefType boxedType() {
return RefType.v("java.lang.Integer");
}
@Override
public boolean isAllowedInFinalCode() {
return false;
}
@Override
public Type getDefaultFinalType() {
return ShortType.v();
}
@Override
public Class<?> getJavaBoxedType() {
return Integer.class;
}
@Override
public Class<?> getJavaPrimitiveType() {
return int.class;
}
}
| 1,850
| 21.301205
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/QueuedSet.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* @author Ben Bellamy
*/
public class QueuedSet<E> {
private final Set<E> hs;
private final LinkedList<E> ll;
public QueuedSet() {
this.hs = new HashSet<E>();
this.ll = new LinkedList<E>();
}
public QueuedSet(List<E> os) {
this();
for (E o : os) {
this.ll.addLast(o);
this.hs.add(o);
}
}
public QueuedSet(QueuedSet<E> qs) {
this(qs.ll);
}
public boolean isEmpty() {
return this.ll.isEmpty();
}
public boolean addLast(E o) {
boolean r = this.hs.contains(o);
if (!r) {
this.ll.addLast(o);
this.hs.add(o);
}
return r;
}
public int addLast(List<E> os) {
int r = 0;
for (E o : os) {
if (this.addLast(o)) {
r++;
}
}
return r;
}
public E removeFirst() {
E r = this.ll.removeFirst();
this.hs.remove(r);
return r;
}
}
| 1,843
| 20.694118
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/SingletonList.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.AbstractList;
/**
* @author Ben Bellamy
*/
@Deprecated
public class SingletonList<E> extends AbstractList<E> {
private final E e;
public SingletonList(E e) {
this.e = e;
}
@Override
public E get(int index) {
if (index != 0) {
throw new IndexOutOfBoundsException();
} else {
return this.e;
}
}
@Override
public int size() {
return 1;
}
}
| 1,278
| 22.685185
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/TypePromotionUseVisitor.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Phong Co
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.IntType;
import soot.Local;
import soot.ShortType;
import soot.Type;
import soot.Value;
import soot.jimple.JimpleBody;
import soot.jimple.Stmt;
public class TypePromotionUseVisitor implements IUseVisitor {
private static final Logger logger = LoggerFactory.getLogger(TypePromotionUseVisitor.class);
private final ByteType byteType = ByteType.v();
private final Integer32767Type integer32767Type = Integer32767Type.v();
private final Integer127Type integer127Type = Integer127Type.v();
private final JimpleBody jb;
private final Typing tg;
public boolean fail;
public boolean typingChanged;
public TypePromotionUseVisitor(JimpleBody jb, Typing tg) {
this.jb = jb;
this.tg = tg;
this.fail = false;
this.typingChanged = false;
}
private Type promote(Type tlow, Type thigh) {
if (tlow instanceof Integer1Type) {
if (thigh instanceof IntType) {
return Integer127Type.v();
} else if (thigh instanceof ShortType) {
return byteType;
} else if (thigh instanceof BooleanType || thigh instanceof ByteType || thigh instanceof CharType
|| thigh instanceof Integer127Type || thigh instanceof Integer32767Type) {
return thigh;
} else {
throw new RuntimeException();
}
} else if (tlow instanceof Integer127Type) {
if (thigh instanceof ShortType) {
return byteType;
} else if (thigh instanceof IntType) {
return integer127Type;
} else if (thigh instanceof ByteType || thigh instanceof CharType || thigh instanceof Integer32767Type) {
return thigh;
} else {
throw new RuntimeException();
}
} else if (tlow instanceof Integer32767Type) {
if (thigh instanceof IntType) {
return integer32767Type;
} else if (thigh instanceof ShortType || thigh instanceof CharType) {
return thigh;
} else {
throw new RuntimeException();
}
} else {
throw new RuntimeException();
}
}
@Override
public Value visit(Value op, Type useType, Stmt stmt, boolean checkOnly) {
if (this.finish()) {
return op;
}
Type t = AugEvalFunction.eval_(this.tg, op, stmt, this.jb);
if (!AugHierarchy.ancestor_(useType, t)) {
logger.error(String.format("Failed Typing in %s at statement %s: Is not cast compatible: %s <-- %s",
jb.getMethod().getSignature(), stmt, useType, t));
this.fail = true;
} else if (!checkOnly && op instanceof Local && (t instanceof Integer1Type || t instanceof Integer127Type
|| t instanceof Integer32767Type || t instanceof WeakObjectType)) {
Local v = (Local) op;
if (!TypeResolver.typesEqual(t, useType)) {
Type t_ = this.promote(t, useType);
if (!TypeResolver.typesEqual(t, t_)) {
this.tg.set(v, t_);
this.typingChanged = true;
}
}
}
return op;
}
@Override
public boolean finish() {
return this.typingChanged || this.fail;
}
}
| 3,973
| 30.539683
| 111
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/TypeResolver.java
|
package soot.jimple.toolkits.typing.fast;
import java.util.ArrayDeque;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.G;
import soot.IntegerType;
import soot.Local;
import soot.LocalGenerator;
import soot.PatchingChain;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.ShortType;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.DefinitionStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.NegExpr;
import soot.jimple.NewExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.toolkits.typing.Util;
import soot.toolkits.scalar.LocalDefs;
/**
* New Type Resolver by Ben Bellamy (see 'Efficient Local Type Inference' at OOPSLA 08).
*
* Ben has tested this code, and verified that it provides a typing that is at least as tight as the original algorithm
* (tighter in 2914 methods out of 295598) on a number of benchmarks. These are: abc-complete.jar, BlueJ, CSO (Scala code),
* Gant, Groovy, havoc.jar, Java 3D, jEdit, Java Grande Forum, Jigsaw, Jython, Kawa, rt.jar, Kawa, Scala and tools.jar. The
* mean execution time improvement is around 10 times, but for the longest methods (abc parser methods and havoc with >9000
* statements) the improvement is between 200 and 500 times.
*
* @author Ben Bellamy
*/
public class TypeResolver {
protected final JimpleBody jb;
private final List<DefinitionStmt> assignments;
private final HashMap<Local, BitSet> depends;
private final LocalGenerator localGenerator;
public TypeResolver(JimpleBody jb) {
this.jb = jb;
this.assignments = new ArrayList<DefinitionStmt>();
this.depends = new HashMap<Local, BitSet>(jb.getLocalCount());
this.localGenerator = Scene.v().createLocalGenerator(jb);
this.initAssignments();
}
private void initAssignments() {
for (Unit stmt : this.jb.getUnits()) {
if (stmt instanceof DefinitionStmt) {
this.initAssignment((DefinitionStmt) stmt);
}
}
}
private void initAssignment(DefinitionStmt ds) {
Value lhs = ds.getLeftOp();
if (lhs instanceof Local || lhs instanceof ArrayRef) {
int assignmentIdx = this.assignments.size();
this.assignments.add(ds);
Value rhs = ds.getRightOp();
if (rhs instanceof Local) {
this.addDepend((Local) rhs, assignmentIdx);
} else if (rhs instanceof BinopExpr) {
BinopExpr be = (BinopExpr) rhs;
Value lop = be.getOp1(), rop = be.getOp2();
if (lop instanceof Local) {
this.addDepend((Local) lop, assignmentIdx);
}
if (rop instanceof Local) {
this.addDepend((Local) rop, assignmentIdx);
}
} else if (rhs instanceof NegExpr) {
Value op = ((NegExpr) rhs).getOp();
if (op instanceof Local) {
this.addDepend((Local) op, assignmentIdx);
}
} else if (rhs instanceof CastExpr) {
Value op = ((CastExpr) rhs).getOp();
if (op instanceof Local) {
this.addDepend((Local) op, assignmentIdx);
}
} else if (rhs instanceof ArrayRef) {
this.addDepend((Local) ((ArrayRef) rhs).getBase(), assignmentIdx);
}
}
}
private void addDepend(Local v, int stmtIndex) {
BitSet d = this.depends.get(v);
if (d == null) {
d = new BitSet();
this.depends.put(v, d);
}
d.set(stmtIndex);
}
public void inferTypes() {
ITypingStrategy typingStrategy = getTypingStrategy();
AugEvalFunction ef = new AugEvalFunction(this.jb);
BytecodeHierarchy bh = new BytecodeHierarchy();
Collection<Typing> sigma = this.applyAssignmentConstraints(typingStrategy.createTyping(this.jb.getLocals()), ef, bh);
// If there is nothing to type, we can quit
if (sigma.isEmpty()) {
return;
}
int[] castCount = new int[1];
Typing tg = this.minCasts(sigma, bh, castCount);
if (castCount[0] != 0) {
this.split_new();
sigma = this.applyAssignmentConstraints(typingStrategy.createTyping(this.jb.getLocals()), ef, bh);
tg = this.minCasts(sigma, bh, castCount);
}
this.insertCasts(tg, bh, false);
final BottomType bottom = BottomType.v();
for (Local v : this.jb.getLocals()) {
Type t = tg.get(v);
if (t instanceof IntegerType) {
// t = inttype;
tg.set(v, bottom);
}
v.setType(t);
}
tg = this.typePromotion(tg);
if (tg == null) {
// Use original soot algorithm for inserting casts
soot.jimple.toolkits.typing.integer.TypeResolver.resolve(this.jb);
} else {
for (Local v : this.jb.getLocals()) {
Type type = tg.get(v);
v.setType(type);
}
}
}
protected ITypingStrategy getTypingStrategy() {
return DefaultTypingStrategy.INSTANCE;
}
public class CastInsertionUseVisitor implements IUseVisitor {
protected JimpleBody jb;
protected Typing tg;
protected IHierarchy h;
private final boolean countOnly;
private int count;
public CastInsertionUseVisitor(boolean countOnly, JimpleBody jb, Typing tg, IHierarchy h) {
this.jb = jb;
this.tg = tg;
this.h = h;
this.countOnly = countOnly;
this.count = 0;
}
@Override
public Value visit(Value op, Type useType, Stmt stmt, boolean checkOnly) {
Type t = AugEvalFunction.eval_(this.tg, op, stmt, this.jb);
if (useType == t) {
return op;
}
boolean needCast = false;
if (useType instanceof PrimType && t instanceof PrimType) {
if (t.isAllowedInFinalCode() && useType.isAllowedInFinalCode()) {
needCast = true;
}
}
if (!needCast && this.h.ancestor(useType, t)) {
return op;
}
this.count++;
if (countOnly) {
return op;
} else {
// If we're referencing an array of the base type java.lang.Object,
// we also need to fix the type of the assignment's target variable.
if (stmt.containsArrayRef() && stmt.getArrayRef().getBase() == op && stmt instanceof DefinitionStmt) {
Value leftOp = ((DefinitionStmt) stmt).getLeftOp();
if (leftOp instanceof Local) {
Type baseType = tg.get((Local) op);
if (baseType instanceof RefType && isObjectLikeType((RefType) baseType)) {
tg.set((Local) leftOp, ((ArrayType) useType).getElementType());
}
}
}
Local vold;
if (op instanceof Local) {
vold = (Local) op;
} else {
/*
* By the time we have countOnly == false, all variables must by typed with concrete Jimple types, and never
* [0..1], [0..127] or [0..32767].
*/
vold = localGenerator.generateLocal(t);
this.tg.set(vold, t);
this.jb.getUnits().insertBefore(Jimple.v().newAssignStmt(vold, op), Util.findFirstNonIdentityUnit(this.jb, stmt));
}
// Cast from the original type to the type that we use in the code
return createCast(useType, stmt, vold, false);
}
}
private boolean isObjectLikeType(RefType rt) {
if (rt instanceof WeakObjectType) {
return true;
} else {
final String name = rt.getSootClass().getName();
return "java.lang.Object".equals(name) || "java.io.Serializable".equals(name) || "java.lang.Cloneable".equals(name);
}
}
/**
* Creates a cast at stmt of vold to the given type.
*
* @param useType
* the new type
* @param stmt
* stmt
* @param old
* the old local
* @param after
* True to insert the cast after the statement, false to insert it before
* @return the new local
*/
protected Local createCast(Type useType, Stmt stmt, Local old, boolean after) {
Local vnew = localGenerator.generateLocal(useType);
this.tg.set(vnew, useType);
Jimple jimple = Jimple.v();
AssignStmt newStmt = jimple.newAssignStmt(vnew, jimple.newCastExpr(old, useType));
Unit u = Util.findFirstNonIdentityUnit(this.jb, stmt);
if (after) {
this.jb.getUnits().insertAfter(newStmt, u);
} else {
this.jb.getUnits().insertBefore(newStmt, u);
}
return vnew;
}
public int getCount() {
return this.count;
}
@Override
public boolean finish() {
return false;
}
}
final BooleanType booleanType = BooleanType.v();
final ByteType byteType = ByteType.v();
final ShortType shortType = ShortType.v();
private Typing typePromotion(Typing tg) {
boolean conversionsPending;
do {
AugEvalFunction ef = new AugEvalFunction(this.jb);
AugHierarchy h = new AugHierarchy();
UseChecker uc = new UseChecker(this.jb);
TypePromotionUseVisitor uv = new TypePromotionUseVisitor(jb, tg);
do {
Collection<Typing> sigma = this.applyAssignmentConstraints(tg, ef, h);
if (sigma.isEmpty()) {
return null;
}
tg = sigma.iterator().next();
uv.typingChanged = false;
uc.check(tg, uv);
if (uv.fail) {
return null;
}
} while (uv.typingChanged);
conversionsPending = false;
for (Local v : this.jb.getLocals()) {
Type t = tg.get(v);
Type r = convert(t);
if (r != null) {
tg.set(v, r);
conversionsPending = true;
}
}
} while (conversionsPending);
return tg;
}
protected Type convert(Type t) {
if (t instanceof Integer1Type) {
return booleanType;
} else if (t instanceof Integer127Type) {
return byteType;
} else if (t instanceof Integer32767Type) {
return shortType;
} else if (t instanceof WeakObjectType) {
return RefType.v(((WeakObjectType) t).getClassName());
} else if (t instanceof ArrayType) {
ArrayType r = (ArrayType) t;
Type cv = convert(r.getElementType());
if (cv != null) {
return ArrayType.v(cv, r.numDimensions);
}
}
return null;
}
private int insertCasts(Typing tg, IHierarchy h, boolean countOnly) {
UseChecker uc = new UseChecker(this.jb);
CastInsertionUseVisitor uv = createCastInsertionUseVisitor(tg, h, countOnly);
uc.check(tg, uv);
return uv.getCount();
}
/**
* Allows clients to provide an own visitor for cast insertion
*
* @param tg
* the typing
* @param h
* the hierarchy
* @param countOnly
* whether to count only (no actual changes)
* @return the visitor
*/
protected CastInsertionUseVisitor createCastInsertionUseVisitor(Typing tg, IHierarchy h, boolean countOnly) {
return new CastInsertionUseVisitor(countOnly, this.jb, tg, h);
}
private Typing minCasts(Collection<Typing> sigma, IHierarchy h, int[] count) {
count[0] = -1;
Typing r = null;
for (Typing tg : sigma) {
int n = this.insertCasts(tg, h, true);
if (count[0] == -1 || n < count[0]) {
count[0] = n;
r = tg;
}
}
return r;
}
static class WorklistElement {
Typing typing;
BitSet worklist;
public WorklistElement(Typing tg, BitSet wl) {
this.typing = tg;
this.worklist = wl;
}
@Override
public String toString() {
return "Left in worklist: " + worklist.size() + ", typing: " + typing;
}
}
protected Collection<Typing> applyAssignmentConstraints(Typing tg, IEvalFunction ef, IHierarchy h) {
final int numAssignments = this.assignments.size();
if (numAssignments == 0) {
return Collections.emptyList();
}
ArrayDeque<WorklistElement> sigma = createSigmaQueue();
List<Typing> r = createResultList();
final ITypingStrategy typingStrategy = getTypingStrategy();
BitSet wl = new BitSet(numAssignments);
wl.set(0, numAssignments);
sigma.add(new WorklistElement(tg, wl));
Set<Type> throwable = null;
while (!sigma.isEmpty()) {
WorklistElement element = sigma.element();
tg = element.typing;
wl = element.worklist;
int defIdx = wl.nextSetBit(0);
if (defIdx == -1) {
// worklist is empty
r.add(tg);
sigma.remove();
} else {
// Get the next definition statement
wl.clear(defIdx);
final DefinitionStmt stmt = this.assignments.get(defIdx);
Value lhs = stmt.getLeftOp();
Local v = (lhs instanceof Local) ? (Local) lhs : (Local) ((ArrayRef) lhs).getBase();
Type told = tg.get(v);
boolean isFirstType = true;
for (Type t_ : ef.eval(tg, stmt.getRightOp(), stmt)) {
if (lhs instanceof ArrayRef) {
/*
* We only need to consider array references on the LHS of assignments where there is supertyping between array
* types, which is only for arrays of reference types and multidimensional arrays.
*/
if (!(t_ instanceof RefType || t_ instanceof ArrayType || t_ instanceof WeakObjectType)) {
continue;
}
t_ = t_.makeArrayType();
}
// Special handling for exception objects with phantom types
final Collection<Type> lcas;
if (!typesEqual(told, t_) && told instanceof RefType && t_ instanceof RefType
&& (((RefType) told).getSootClass().isPhantom() || ((RefType) t_).getSootClass().isPhantom())
&& (stmt.getRightOp() instanceof CaughtExceptionRef)) {
if (throwable == null) {
throwable = Collections.<Type>singleton(RefType.v("java.lang.Throwable"));
}
lcas = throwable;
} else {
lcas = h.lcas(told, t_, true);
}
for (Type t : lcas) {
if (!typesEqual(t, told)) {
BitSet dependsV = this.depends.get(v);
Typing tg_;
BitSet wl_;
if (/* (eval.size() == 1 && lcas.size() == 1) || */isFirstType) {
// The types agree, we have a type we can directly use
tg_ = tg;
wl_ = wl;
} else {
// The types do not agree, add all supertype candidates
tg_ = typingStrategy.createTyping(tg);
wl_ = (BitSet) wl.clone();
WorklistElement e = new WorklistElement(tg_, wl_);
sigma.add(e);
}
tg_.set(v, t);
if (dependsV != null) {
wl_.or(dependsV);
}
}
isFirstType = false;
}
} // end for
}
}
typingStrategy.minimize(r, h);
return r;
}
protected ArrayDeque<WorklistElement> createSigmaQueue() {
return new ArrayDeque<>();
}
protected List<Typing> createResultList() {
return new ArrayList<Typing>();
}
// The ArrayType.equals method seems odd in Soot 2.2.5
public static boolean typesEqual(Type a, Type b) {
if (a instanceof ArrayType && b instanceof ArrayType) {
ArrayType a_ = (ArrayType) a, b_ = (ArrayType) b;
return a_.numDimensions == b_.numDimensions && a_.baseType.equals(b_.baseType);
} else {
return a.equals(b);
}
}
/*
* Taken from the soot.jimple.toolkits.typing.TypeResolver class of Soot version 2.2.5.
*/
private void split_new() {
final Jimple jimp = Jimple.v();
final JimpleBody body = this.jb;
final LocalDefs defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(body);
PatchingChain<Unit> units = body.getUnits();
for (Iterator<Unit> it = units.snapshotIterator(); it.hasNext();) {
Unit stmt = it.next();
if (stmt instanceof InvokeStmt) {
InvokeExpr invokeExpr = ((InvokeStmt) stmt).getInvokeExpr();
if ((invokeExpr instanceof SpecialInvokeExpr) && ("<init>".equals(invokeExpr.getMethodRef().getName()))) {
SpecialInvokeExpr special = (SpecialInvokeExpr) invokeExpr;
for (List<Unit> deflist = defs.getDefsOfAt((Local) special.getBase(), stmt); deflist.size() == 1;) {
Stmt stmt2 = (Stmt) deflist.get(0);
if (stmt2 instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) stmt2;
Value rightOp = assign.getRightOp();
if (rightOp instanceof Local) {
deflist = defs.getDefsOfAt((Local) rightOp, assign);
continue;
} else if (rightOp instanceof NewExpr) {
Local newlocal = localGenerator.generateLocal(assign.getLeftOp().getType());
special.setBase(newlocal);
DefinitionStmt assignStmt = jimp.newAssignStmt(assign.getLeftOp(), newlocal);
units.insertAfter(assignStmt, Util.findLastIdentityUnit(body, assign));
assign.setLeftOp(newlocal);
this.initAssignment(assignStmt);
}
}
break;
} // end for(List<Unit>)
}
}
}
}
}
| 18,337
| 31.115587
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/TypeUtils.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.BooleanType;
import soot.ByteType;
import soot.DoubleType;
import soot.FloatType;
import soot.IntType;
import soot.LongType;
import soot.ShortType;
import soot.Type;
public class TypeUtils {
/**
* Returns the bit size of a given primitive type. Note that it returns 1 for boolean albeit not being possible on a real
* machine.
*
* @param type
* @return the size
*/
public static int getValueBitSize(Type type) {
if (type instanceof BooleanType) {
return 1;
}
if (type instanceof ByteType) {
return 8;
}
if (type instanceof ShortType) {
return 16;
}
if (type instanceof IntType) {
return 32;
}
if (type instanceof LongType) {
return 64;
}
if (type instanceof FloatType) {
return 32;
}
if (type instanceof DoubleType) {
return 64;
}
if (type instanceof Integer127Type) {
return 8;
}
if (type instanceof Integer32767Type) {
return 16;
}
if (type instanceof Integer1Type) {
return 1;
}
throw new IllegalArgumentException(type + " not supported.");
}
}
| 1,998
| 23.9875
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/Typing.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import soot.Local;
import soot.Type;
/**
* @author Ben Bellamy
*/
public class Typing {
protected HashMap<Local, Type> map;
public Typing(Collection<Local> vs) {
this.map = new HashMap<Local, Type>(vs.size());
}
public Typing(Typing tg) {
this.map = new HashMap<Local, Type>(tg.map);
}
public Map<Local, Type> getMap() {
return map;
}
public Type get(Local v) {
Type t = this.map.get(v);
return (t == null) ? BottomType.v() : t;
}
public Type set(Local v, Type t) {
return (t instanceof BottomType) ? null : this.map.put(v, t);
}
public Collection<Local> getAllLocals() {
return map.keySet();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('{');
for (Map.Entry<Local, Type> e : this.map.entrySet()) {
sb.append(e.getKey());
sb.append(':');
sb.append(e.getValue());
sb.append(',');
}
sb.append('}');
return sb.toString();
}
}
| 1,931
| 23.455696
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/UseChecker.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Ben Bellamy
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.solver.Pair;
import java.util.ArrayDeque;
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.BooleanType;
import soot.G;
import soot.IntType;
import soot.IntegerType;
import soot.Local;
import soot.NullType;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.Constant;
import soot.jimple.DivExpr;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FieldRef;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.Stmt;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.XorExpr;
import soot.toolkits.scalar.LocalDefs;
import soot.toolkits.scalar.LocalUses;
import soot.toolkits.scalar.UnitValueBoxPair;
/**
* This checks all uses against the rules in Jimple, except some uses are not checked where the bytecode verifier guarantees
* use validity.
*
* @author Ben Bellamy
*/
public class UseChecker extends AbstractStmtSwitch {
private final JimpleBody jb;
private Typing tg;
private IUseVisitor uv;
private LocalDefs defs = null;
private LocalUses uses = null;
private static final Logger logger = LoggerFactory.getLogger(UseChecker.class);
public UseChecker(JimpleBody jb) {
this.jb = jb;
}
public void check(Typing tg, IUseVisitor uv) {
if (tg == null) {
throw new RuntimeException("null typing passed to useChecker");
}
this.tg = tg;
this.uv = uv;
for (Iterator<Unit> i = this.jb.getUnits().snapshotIterator(); i.hasNext();) {
if (uv.finish()) {
return;
}
i.next().apply(this);
}
}
private void handleInvokeExpr(InvokeExpr ie, Stmt stmt) {
SootMethodRef m = ie.getMethodRef();
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
iie.setBase(this.uv.visit(iie.getBase(), m.getDeclaringClass().getType(), stmt));
}
for (int i = 0, e = ie.getArgCount(); i < e; i++) {
ie.setArg(i, this.uv.visit(ie.getArg(i), m.getParameterType(i), stmt));
}
}
private void handleBinopExpr(BinopExpr be, Stmt stmt, Type tlhs) {
Value opl = be.getOp1(), opr = be.getOp2();
Type tl = AugEvalFunction.eval_(this.tg, opl, stmt, this.jb);
Type tr = AugEvalFunction.eval_(this.tg, opr, stmt, this.jb);
if (be instanceof AddExpr || be instanceof SubExpr || be instanceof MulExpr || be instanceof DivExpr
|| be instanceof RemExpr || be instanceof GeExpr || be instanceof GtExpr || be instanceof LeExpr
|| be instanceof LtExpr || be instanceof ShlExpr || be instanceof ShrExpr || be instanceof UshrExpr) {
if (tlhs instanceof IntegerType) {
be.setOp1(this.uv.visit(opl, IntType.v(), stmt, true));
be.setOp2(this.uv.visit(opr, IntType.v(), stmt, true));
}
} else if (be instanceof CmpExpr || be instanceof CmpgExpr || be instanceof CmplExpr) {
// No checks in the original assigner
} else if (be instanceof AndExpr || be instanceof OrExpr || be instanceof XorExpr) {
be.setOp1(this.uv.visit(opl, tlhs, stmt, true));
be.setOp2(this.uv.visit(opr, tlhs, stmt, true));
} else if (be instanceof EqExpr || be instanceof NeExpr) {
if (tl instanceof BooleanType && tr instanceof BooleanType) {
} else if (tl instanceof Integer1Type || tr instanceof Integer1Type) {
} else if (tl instanceof IntegerType) {
be.setOp1(this.uv.visit(opl, IntType.v(), stmt, true));
be.setOp2(this.uv.visit(opr, IntType.v(), stmt, true));
}
}
}
private void handleArrayRef(ArrayRef ar, Stmt stmt) {
ar.setIndex(this.uv.visit(ar.getIndex(), IntType.v(), stmt));
}
private void handleInstanceFieldRef(InstanceFieldRef ifr, Stmt stmt) {
ifr.setBase(this.uv.visit(ifr.getBase(), ifr.getFieldRef().declaringClass().getType(), stmt));
}
@Override
public void caseBreakpointStmt(BreakpointStmt stmt) {
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
this.handleInvokeExpr(stmt.getInvokeExpr(), stmt);
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
Value lhs = stmt.getLeftOp();
Value rhs = stmt.getRightOp();
Type tlhs = null;
if (lhs instanceof Local) {
tlhs = this.tg.get((Local) lhs);
} else if (lhs instanceof ArrayRef) {
ArrayRef aref = (ArrayRef) lhs;
Local base = (Local) aref.getBase();
// Try to force Type integrity. The left side must agree on the
// element type of the right side array reference.
ArrayType at = null;
Type tgType = this.tg.get(base);
if (tgType instanceof ArrayType) {
at = (ArrayType) tgType;
} else {
// If the right-hand side is a primitive and the left-side type
// is java.lang.Object
if (rhs instanceof Local) {
Type rhsType = this.tg.get((Local) rhs);
if ((tgType == Scene.v().getObjectType() && rhsType instanceof PrimType) || tgType instanceof WeakObjectType) {
if (defs == null) {
defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(jb);
uses = LocalUses.Factory.newLocalUses(jb, defs);
}
// Check the original type of the array from the alloc site
boolean hasDefs = false;
for (Unit defU : defs.getDefsOfAt(base, stmt)) {
if (defU instanceof AssignStmt) {
AssignStmt defUas = (AssignStmt) defU;
if (defUas.getRightOp() instanceof NewArrayExpr) {
at = (ArrayType) defUas.getRightOp().getType();
hasDefs = true;
break;
}
}
}
if (!hasDefs) {
at = ArrayType.v(rhsType, 1);
}
}
}
if (at == null) {
at = tgType.makeArrayType();
}
}
tlhs = ((ArrayType) at).getElementType();
this.handleArrayRef(aref, stmt);
aref.setBase((Local) this.uv.visit(aref.getBase(), at, stmt));
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
stmt.setLeftOp(this.uv.visit(lhs, tlhs, stmt));
} else if (lhs instanceof FieldRef) {
tlhs = ((FieldRef) lhs).getFieldRef().type();
if (lhs instanceof InstanceFieldRef) {
this.handleInstanceFieldRef((InstanceFieldRef) lhs, stmt);
}
}
// They may have been changed above
lhs = stmt.getLeftOp();
rhs = stmt.getRightOp();
if (rhs instanceof Local) {
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
} else if (rhs instanceof ArrayRef) {
ArrayRef aref = (ArrayRef) rhs;
Local base = (Local) aref.getBase();
// try to force Type integrity
final ArrayType at;
final Type bt = this.tg.get(base);
if (bt instanceof ArrayType) {
at = (ArrayType) bt;
} else {
Type et = null;
// If we have a type of java.lang.Object and access it like an object,
// this could lead to any kind of object, so we have to look at the uses.
// For some fixed type T, we assume that we can fix the array to T[].
if (bt instanceof RefType || bt instanceof NullType) {
String btName = bt instanceof NullType ? null : ((RefType) bt).getSootClass().getName();
if (btName == null || "java.lang.Object".equals(btName) || "java.io.Serializable".equals(btName)
|| "java.lang.Cloneable".equals(btName)) {
if (defs == null) {
defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(jb);
uses = LocalUses.Factory.newLocalUses(jb, defs);
}
// First, we check the definitions. If we can see the definitions and know the array type
// that way, we are safe.
ArrayDeque<Pair<Unit, Local>> worklist = new ArrayDeque<Pair<Unit, Local>>();
Set<Pair<Unit, Local>> seen = new HashSet<>();
worklist.add(new Pair<>(stmt, (Local) ((ArrayRef) rhs).getBase()));
while (!worklist.isEmpty()) {
Pair<Unit, Local> r = worklist.removeFirst();
if (!seen.add(r)) {
// Make sure we only process each entry once
continue;
}
List<Unit> d = defs.getDefsOfAt(r.getO2(), r.getO1());
if (d.isEmpty()) {
// In this case, probably we are asking for some variable which got casted. Since the local defs and uses are
// cached
// they might not reflect this.
defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(jb);
uses = LocalUses.Factory.newLocalUses(jb, defs);
d = defs.getDefsOfAt(r.getO2(), r.getO1());
}
for (Unit u : d) {
if (u instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) u;
Value rop = assign.getRightOp();
if (rop instanceof NewArrayExpr) {
et = merge(stmt, et, ((NewArrayExpr) assign.getRightOp()).getBaseType());
} else if (rop instanceof Local) {
worklist.add(new Pair<>(u, (Local) rop));
} else if (rop instanceof CastExpr) {
worklist.add(new Pair<>(u, (Local) ((CastExpr) rop).getOp()));
}
}
}
}
// Take a look at uses if the definitions didn't give any intel.
if (et == null) {
OUTER: for (UnitValueBoxPair usePair : uses.getUsesOf(stmt)) {
Stmt useStmt = (Stmt) usePair.getUnit();
// Is the array element used in an invocation for which we have a type
// from the callee's signature=
if (useStmt.containsInvokeExpr()) {
InvokeExpr invokeExpr = useStmt.getInvokeExpr();
for (int i = 0, e = invokeExpr.getArgCount(); i < e; i++) {
if (invokeExpr.getArg(i) == usePair.getValueBox().getValue()) {
et = merge(stmt, et, invokeExpr.getMethod().getParameterType(i));
break OUTER;
}
}
} else if (useStmt instanceof IfStmt) {
// If we have a comparison, we look at the other value. Using
// the type of the value is at least closer to the truth than
// java.lang.Object if the other value is a primitive.
Value condition = ((IfStmt) useStmt).getCondition();
if (condition instanceof EqExpr) {
EqExpr expr = (EqExpr) condition;
final Value other;
if (expr.getOp1() == usePair.getValueBox().getValue()) {
other = expr.getOp2();
} else {
other = expr.getOp1();
}
Type newEt = getTargetType(other);
if (newEt != null) {
et = merge(stmt, et, newEt);
}
}
} else if (useStmt instanceof AssignStmt) {
// For binary expressions, we can look for type information
// in the other operands.
AssignStmt useAssignStmt = (AssignStmt) useStmt;
Value rop = useAssignStmt.getRightOp();
if (rop instanceof BinopExpr) {
BinopExpr binOp = (BinopExpr) rop;
final Value other;
if (binOp.getOp1() == usePair.getValueBox().getValue()) {
other = binOp.getOp2();
} else {
other = binOp.getOp1();
}
Type newEt = getTargetType(other);
if (newEt != null) {
et = merge(stmt, et, newEt);
}
} else if (rop instanceof CastExpr) {
et = merge(stmt, et, ((CastExpr) rop).getCastType());
}
} else if (useStmt instanceof ReturnStmt) {
et = merge(stmt, et, jb.getMethod().getReturnType());
}
}
}
}
}
if (et == null) {
// At the very least, the the type for this array should be whatever its
// base type is
et = bt;
logger.warn("Could not find any indication on the array type of " + stmt + " in " + jb.getMethod().getSignature(),
", assuming its base type is " + bt);
}
at = et.makeArrayType();
}
Type trhs = ((ArrayType) at).getElementType();
this.handleArrayRef(aref, stmt);
aref.setBase((Local) this.uv.visit(aref.getBase(), at, stmt));
stmt.setRightOp(this.uv.visit(rhs, trhs, stmt));
} else if (rhs instanceof InstanceFieldRef) {
this.handleInstanceFieldRef((InstanceFieldRef) rhs, stmt);
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
} else if (rhs instanceof BinopExpr) {
this.handleBinopExpr((BinopExpr) rhs, stmt, tlhs);
} else if (rhs instanceof InvokeExpr) {
this.handleInvokeExpr((InvokeExpr) rhs, stmt);
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
} else if (rhs instanceof CastExpr) {
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
} else if (rhs instanceof InstanceOfExpr) {
InstanceOfExpr ioe = (InstanceOfExpr) rhs;
ioe.setOp(this.uv.visit(ioe.getOp(), RefType.v("java.lang.Object"), stmt));
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
} else if (rhs instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) rhs;
nae.setSize(this.uv.visit(nae.getSize(), IntType.v(), stmt));
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
} else if (rhs instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) rhs;
for (int i = 0, e = nmae.getSizeCount(); i < e; i++) {
nmae.setSize(i, this.uv.visit(nmae.getSize(i), IntType.v(), stmt));
}
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
} else if (rhs instanceof LengthExpr) {
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
} else if (rhs instanceof NegExpr) {
((NegExpr) rhs).setOp(this.uv.visit(((NegExpr) rhs).getOp(), tlhs, stmt));
} else if (rhs instanceof Constant) {
if (!(rhs instanceof NullConstant)) {
stmt.setRightOp(this.uv.visit(rhs, tlhs, stmt));
}
}
}
protected Type merge(Stmt stmt, Type previousType, Type newType) {
if (previousType == null) {
return newType;
}
if (newType == previousType) {
return previousType;
}
Type choose;
// we choose the wider one. Note that this probably still results in code which cannot be executed!
if (TypeUtils.getValueBitSize(previousType) > TypeUtils.getValueBitSize(newType)) {
choose = previousType;
} else {
choose = newType;
}
logger.warn("Conflicting array types at " + stmt + " in " + jb.getMethod().getSignature(),
", its base type may be " + previousType + " or " + newType + ". Choosing " + choose + ".");
return newType;
}
private Type getTargetType(final Value other) {
if (other instanceof Constant) {
if (other.getType() != NullType.v()) {
return other.getType();
}
} else if (other instanceof Local) {
Type tgTp = tg.get((Local) other);
if (tgTp instanceof PrimType) {
return tgTp;
}
}
return null;
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
stmt.setOp(this.uv.visit(stmt.getOp(), RefType.v("java.lang.Object"), stmt));
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
stmt.setOp(this.uv.visit(stmt.getOp(), RefType.v("java.lang.Object"), stmt));
}
@Override
public void caseGotoStmt(GotoStmt stmt) {
}
@Override
public void caseIfStmt(IfStmt stmt) {
this.handleBinopExpr((BinopExpr) stmt.getCondition(), stmt, BooleanType.v());
}
@Override
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
stmt.setKey(this.uv.visit(stmt.getKey(), IntType.v(), stmt));
}
@Override
public void caseNopStmt(NopStmt stmt) {
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
stmt.setOp(this.uv.visit(stmt.getOp(), this.jb.getMethod().getReturnType(), stmt));
}
@Override
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
@Override
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
stmt.setKey(this.uv.visit(stmt.getKey(), IntType.v(), stmt));
}
@Override
public void caseThrowStmt(ThrowStmt stmt) {
stmt.setOp(this.uv.visit(stmt.getOp(), RefType.v("java.lang.Throwable"), stmt));
}
@Override
public void defaultCase(Object stmt) {
throw new RuntimeException("Unhandled type: " + stmt.getClass());
}
}
| 19,424
| 35.376404
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/fast/WeakObjectType.java
|
package soot.jimple.toolkits.typing.fast;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2020 Steven Arzt
*
* All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.RefType;
import soot.Singletons.Global;
/**
* A weak variant of an object type (Object, Serializable, Cloneable). The "java.lang.Object" type can be used as a
* placeholder for all reference and array types. Assume the following code (without the casts, because they don't need to be
* explicit in Dalvik):
*
* <pre>
* java.lang.Object a;
* int[] b;
*
* b = ((Object[]) a)[42];
* b[0] = 42;
* </pre>
*
* If we reconstruct types for this code, the array element from "a" is of type "java.lang.Object", because the array was of
* type "java.lang.Object[]". Still, this typing is not required, we rather take it, because we have no better guess as to
* what the original type was. Later on, when we learn that we write an "int" into "b", we can conclude, that "b" should have
* been of type "int[]". In other words, we need to drop the requirement of "b" being of type "java.lang.Object", which was
* our initial assumption.
*
* @author Steven Arzt
*/
public class WeakObjectType extends RefType {
public WeakObjectType(Global g) {
super(g);
}
public WeakObjectType(String className) {
super(className);
}
}
| 2,027
| 31.709677
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/ClassHierarchy.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.G;
import soot.IntType;
import soot.ShortType;
import soot.Singletons.Global;
import soot.Type;
/**
* This class encapsulates the integer type hierarchy.
*
* <P>
* This class is primarily used by the TypeResolver class, to optimize its computation.
**/
public class ClassHierarchy {
public ClassHierarchy(Global g) {
}
public static ClassHierarchy v() {
return G.v().soot_jimple_toolkits_typing_integer_ClassHierarchy();
}
public final TypeNode BOOLEAN = new TypeNode(0, BooleanType.v());
public final TypeNode BYTE = new TypeNode(1, ByteType.v());
public final TypeNode SHORT = new TypeNode(2, ShortType.v());
public final TypeNode CHAR = new TypeNode(3, CharType.v());
public final TypeNode INT = new TypeNode(4, IntType.v());
public final TypeNode TOP = new TypeNode(5, null);
public final TypeNode R0_1 = new TypeNode(6, null); // eventually becomes boolean
public final TypeNode R0_127 = new TypeNode(7, null); // eventually becomes byte
public final TypeNode R0_32767 = new TypeNode(8, null); // eventually becomes short
private final boolean[][] ancestors_1 = { { false, false, false, false, false, true, false, false, false, },
{ false, false, true, false, true, true, false, false, false, },
{ false, false, false, false, true, true, false, false, false, },
{ false, false, false, false, true, true, false, false, false, },
{ false, false, false, false, false, true, false, false, false, },
{ false, false, false, false, false, false, false, false, false, },
{ true, true, true, true, true, true, false, true, true, },
{ false, true, true, true, true, true, false, false, true, },
{ false, false, true, true, true, true, false, false, false, }, };
private final boolean[][] ancestors_2 = { { false, true, true, true, true, false, false, true, true, },
{ false, false, true, false, true, false, false, false, false, },
{ false, false, false, false, true, false, false, false, false, },
{ false, false, false, false, true, false, false, false, false, },
{ false, false, false, false, false, false, false, false, false, }, {}, {},
{ false, true, true, true, true, false, false, false, true, },
{ false, false, true, true, true, false, false, false, false, }, };
private final boolean[][] descendants_1 = { { false, false, false, false, false, false, true, false, false, },
{ false, false, false, false, false, false, true, true, false, },
{ false, true, false, false, false, false, true, true, true, },
{ false, false, false, false, false, false, true, true, true, },
{ false, true, true, true, false, false, true, true, true, },
{ true, true, true, true, true, false, true, true, true, },
{ false, false, false, false, false, false, false, false, false, },
{ false, false, false, false, false, false, true, false, false, },
{ false, false, false, false, false, false, true, true, false, }, };
private final boolean[][] descendants_2 = { { false, false, false, false, false, false, false, false, false, },
{ true, false, false, false, false, false, false, true, false, },
{ true, true, false, false, false, false, false, true, true, },
{ true, false, false, false, false, false, false, true, true, },
{ true, true, true, true, false, false, false, true, true, }, {}, {},
{ true, false, false, false, false, false, false, false, false, },
{ true, false, false, false, false, false, false, true, false, }, };
private final TypeNode[][] lca_1 = { { BOOLEAN, TOP, TOP, TOP, TOP, TOP, BOOLEAN, TOP, TOP, },
{ TOP, BYTE, SHORT, INT, INT, TOP, BYTE, BYTE, SHORT, }, { TOP, SHORT, SHORT, INT, INT, TOP, SHORT, SHORT, SHORT, },
{ TOP, INT, INT, CHAR, INT, TOP, CHAR, CHAR, CHAR, }, { TOP, INT, INT, INT, INT, TOP, INT, INT, INT, },
{ TOP, TOP, TOP, TOP, TOP, TOP, TOP, TOP, TOP, }, { BOOLEAN, BYTE, SHORT, CHAR, INT, TOP, R0_1, R0_127, R0_32767, },
{ TOP, BYTE, SHORT, CHAR, INT, TOP, R0_127, R0_127, R0_32767, },
{ TOP, SHORT, SHORT, CHAR, INT, TOP, R0_32767, R0_32767, R0_32767, }, };
private final TypeNode[][] lca_2 = { { BOOLEAN, BYTE, SHORT, CHAR, INT, null, null, R0_127, R0_32767, },
{ BYTE, BYTE, SHORT, INT, INT, null, null, BYTE, SHORT, },
{ SHORT, SHORT, SHORT, INT, INT, null, null, SHORT, SHORT, }, { CHAR, INT, INT, CHAR, INT, null, null, CHAR, CHAR, },
{ INT, INT, INT, INT, INT, null, null, INT, INT, }, {}, {},
{ R0_127, BYTE, SHORT, CHAR, INT, null, null, R0_127, R0_32767, },
{ R0_32767, SHORT, SHORT, CHAR, INT, null, null, R0_32767, R0_32767, }, };
private final TypeNode[][] gcd_1 = { { BOOLEAN, R0_1, R0_1, R0_1, R0_1, BOOLEAN, R0_1, R0_1, R0_1, },
{ R0_1, BYTE, BYTE, R0_127, BYTE, BYTE, R0_1, R0_127, R0_127, },
{ R0_1, BYTE, SHORT, R0_32767, SHORT, SHORT, R0_1, R0_127, R0_32767, },
{ R0_1, R0_127, R0_32767, CHAR, CHAR, CHAR, R0_1, R0_127, R0_32767, },
{ R0_1, BYTE, SHORT, CHAR, INT, INT, R0_1, R0_127, R0_32767, },
{ BOOLEAN, BYTE, SHORT, CHAR, INT, TOP, R0_1, R0_127, R0_32767, },
{ R0_1, R0_1, R0_1, R0_1, R0_1, R0_1, R0_1, R0_1, R0_1, },
{ R0_1, R0_127, R0_127, R0_127, R0_127, R0_127, R0_1, R0_127, R0_127, },
{ R0_1, R0_127, R0_32767, R0_32767, R0_32767, R0_32767, R0_1, R0_127, R0_32767, }, };
private final TypeNode[][] gcd_2 = { { BOOLEAN, BOOLEAN, BOOLEAN, BOOLEAN, BOOLEAN, null, null, BOOLEAN, BOOLEAN, },
{ BOOLEAN, BYTE, BYTE, R0_127, BYTE, null, null, R0_127, R0_127, },
{ BOOLEAN, BYTE, SHORT, R0_32767, SHORT, null, null, R0_127, R0_32767, },
{ BOOLEAN, R0_127, R0_32767, CHAR, CHAR, null, null, R0_127, R0_32767, },
{ BOOLEAN, BYTE, SHORT, CHAR, INT, null, null, R0_127, R0_32767, }, {}, {},
{ BOOLEAN, R0_127, R0_127, R0_127, R0_127, null, null, R0_127, R0_127, },
{ BOOLEAN, R0_127, R0_32767, R0_32767, R0_32767, null, null, R0_127, R0_32767, }, };
/** Get the type node for the given type. **/
public TypeNode typeNode(Type type) {
if (type instanceof IntType) {
return INT;
} else if (type instanceof BooleanType) {
return BOOLEAN;
} else if (type instanceof ByteType) {
return BYTE;
} else if (type instanceof ShortType) {
return SHORT;
} else if (type instanceof CharType) {
return CHAR;
} else {
throw new InternalTypingException(type);
}
}
public boolean hasAncestor_1(int t1, int t2) {
return ancestors_1[t1][t2];
}
public boolean hasAncestor_2(int t1, int t2) {
return ancestors_2[t1][t2];
}
public boolean hasDescendant_1(int t1, int t2) {
return descendants_1[t1][t2];
}
public boolean hasDescendant_2(int t1, int t2) {
return descendants_2[t1][t2];
}
public TypeNode lca_1(int t1, int t2) {
return lca_1[t1][t2];
}
private int convert(int n) {
switch (n) {
case 5:
return 4;
case 6:
return 0;
default:
return n;
}
}
public TypeNode lca_2(int t1, int t2) {
return lca_2[convert(t1)][convert(t2)];
}
public TypeNode gcd_1(int t1, int t2) {
return gcd_1[t1][t2];
}
public TypeNode gcd_2(int t1, int t2) {
return gcd_2[convert(t1)][convert(t2)];
}
}
| 8,232
| 43.026738
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/ConstraintChecker.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.BooleanType;
import soot.ByteType;
import soot.IntType;
import soot.IntegerType;
import soot.Local;
import soot.LocalGenerator;
import soot.NullType;
import soot.Scene;
import soot.ShortType;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.UnitPatchingChain;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.DynamicInvokeExpr;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.XorExpr;
import soot.jimple.toolkits.typing.Util;
class ConstraintChecker extends AbstractStmtSwitch {
private static final Logger logger = LoggerFactory.getLogger(ConstraintChecker.class);
private final TypeResolver resolver;
private final boolean fix; // if true, fix constraint violations
private JimpleBody stmtBody;
private LocalGenerator localGenerator;
public ConstraintChecker(TypeResolver resolver, boolean fix) {
this.resolver = resolver;
this.fix = fix;
}
public void check(Stmt stmt, JimpleBody stmtBody) throws TypeException {
try {
this.stmtBody = stmtBody;
this.localGenerator = Scene.v().createLocalGenerator(stmtBody);
stmt.apply(this);
} catch (RuntimeTypeException e) {
logger.error(e.getMessage(), e);
throw new TypeException(e.getMessage(), e);
}
}
@SuppressWarnings("serial")
private static class RuntimeTypeException extends RuntimeException {
RuntimeTypeException(String message) {
super(message);
}
}
static void error(String message) {
throw new RuntimeTypeException(message);
}
private void handleInvokeExpr(InvokeExpr ie, Stmt invokestmt) {
final ClassHierarchy classHierarchy = ClassHierarchy.v();
// Handle the parameters
SootMethodRef method = ie.getMethodRef();
for (int i = 0, e = ie.getArgCount(); i < e; i++) {
Value currArg = ie.getArg(i);
if (currArg instanceof Local) {
Local local = (Local) currArg;
Type localType = local.getType();
if (localType instanceof IntegerType) {
Type currParamType = method.getParameterType(i);
if (!classHierarchy.typeNode(localType).hasAncestor_1(classHierarchy.typeNode(currParamType))) {
if (fix) {
ie.setArg(i, insertCast(local, currParamType, invokestmt));
} else {
error("Type Error");
}
}
}
}
}
if (ie instanceof DynamicInvokeExpr) {
DynamicInvokeExpr die = (DynamicInvokeExpr) ie;
SootMethodRef bootstrapMethod = die.getBootstrapMethodRef();
for (int i = 0, e = die.getBootstrapArgCount(); i < e; i++) {
Value currBootstrapArg = die.getBootstrapArg(i);
if (currBootstrapArg instanceof Local) {
Local local = (Local) currBootstrapArg;
Type localType = local.getType();
if (localType instanceof IntegerType) {
Type currParamType = bootstrapMethod.getParameterType(i);
if (!classHierarchy.typeNode(localType).hasAncestor_1(classHierarchy.typeNode(currParamType))) {
if (fix) {
die.setArg(i, insertCast(local, currParamType, invokestmt));
} else {
error("Type Error");
}
}
}
}
}
}
}
@Override
public void caseBreakpointStmt(BreakpointStmt stmt) {
// Do nothing
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
handleInvokeExpr(stmt.getInvokeExpr(), stmt);
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
final ClassHierarchy classHierarchy = ClassHierarchy.v();
final Value l = stmt.getLeftOp();
final Value r = stmt.getRightOp();
TypeNode left = null;
TypeNode right = null;
// ******** LEFT ********
if (l instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) l;
Type baset = ((Local) ref.getBase()).getType();
if (baset instanceof ArrayType) {
ArrayType base = (ArrayType) baset;
Value index = ref.getIndex();
if ((base.numDimensions == 1) && (base.baseType instanceof IntegerType)) {
left = classHierarchy.typeNode(base.baseType);
}
if (index instanceof Local) {
if (!classHierarchy.typeNode(((Local) index).getType()).hasAncestor_1(classHierarchy.INT)) {
if (fix) {
ref.setIndex(insertCast((Local) index, IntType.v(), stmt));
} else {
error("Type Error(5)");
}
}
}
}
} else if (l instanceof Local) {
Type ty = ((Local) l).getType();
if (ty instanceof IntegerType) {
left = classHierarchy.typeNode(ty);
}
} else if (l instanceof InstanceFieldRef) {
Type ty = ((InstanceFieldRef) l).getFieldRef().type();
if (ty instanceof IntegerType) {
left = classHierarchy.typeNode(ty);
}
} else if (l instanceof StaticFieldRef) {
Type ty = ((StaticFieldRef) l).getFieldRef().type();
if (ty instanceof IntegerType) {
left = classHierarchy.typeNode(ty);
}
} else {
throw new RuntimeException("Unhandled assignment left hand side type: " + l.getClass());
}
// ******** RIGHT ********
if (r instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) r;
Type baset = ((Local) ref.getBase()).getType();
if (!(baset instanceof NullType)) {
ArrayType base = (ArrayType) baset;
Value index = ref.getIndex();
if ((base.numDimensions == 1) && (base.baseType instanceof IntegerType)) {
right = classHierarchy.typeNode(base.baseType);
}
if (index instanceof Local) {
if (!classHierarchy.typeNode(((Local) index).getType()).hasAncestor_1(classHierarchy.INT)) {
if (fix) {
ref.setIndex(insertCast((Local) index, IntType.v(), stmt));
} else {
error("Type Error(6)");
}
}
}
}
} else if (r instanceof DoubleConstant) {
} else if (r instanceof FloatConstant) {
} else if (r instanceof IntConstant) {
int value = ((IntConstant) r).value;
if (value < -32768) {
right = classHierarchy.INT;
} else if (value < -128) {
right = classHierarchy.SHORT;
} else if (value < 0) {
right = classHierarchy.BYTE;
} else if (value < 2) {
right = classHierarchy.R0_1;
} else if (value < 128) {
right = classHierarchy.R0_127;
} else if (value < 32768) {
right = classHierarchy.R0_32767;
} else if (value < 65536) {
right = classHierarchy.CHAR;
} else {
right = classHierarchy.INT;
}
} else if (r instanceof LongConstant) {
} else if (r instanceof NullConstant) {
} else if (r instanceof StringConstant) {
} else if (r instanceof ClassConstant) {
} else if (r instanceof BinopExpr) {
// ******** BINOP EXPR ********
BinopExpr be = (BinopExpr) r;
Value lv = be.getOp1();
Value rv = be.getOp2();
TypeNode lop = null;
TypeNode rop = null;
// ******** LEFT ********
if (lv instanceof Local) {
if (((Local) lv).getType() instanceof IntegerType) {
lop = classHierarchy.typeNode(((Local) lv).getType());
}
} else if (lv instanceof DoubleConstant) {
} else if (lv instanceof FloatConstant) {
} else if (lv instanceof IntConstant) {
int value = ((IntConstant) lv).value;
if (value < -32768) {
lop = classHierarchy.INT;
} else if (value < -128) {
lop = classHierarchy.SHORT;
} else if (value < 0) {
lop = classHierarchy.BYTE;
} else if (value < 2) {
lop = classHierarchy.R0_1;
} else if (value < 128) {
lop = classHierarchy.R0_127;
} else if (value < 32768) {
lop = classHierarchy.R0_32767;
} else if (value < 65536) {
lop = classHierarchy.CHAR;
} else {
lop = classHierarchy.INT;
}
} else if (lv instanceof LongConstant) {
} else if (lv instanceof NullConstant) {
} else if (lv instanceof StringConstant) {
} else if (lv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
if (((Local) rv).getType() instanceof IntegerType) {
rop = classHierarchy.typeNode(((Local) rv).getType());
}
} else if (rv instanceof DoubleConstant) {
} else if (rv instanceof FloatConstant) {
} else if (rv instanceof IntConstant) {
int value = ((IntConstant) rv).value;
if (value < -32768) {
rop = classHierarchy.INT;
} else if (value < -128) {
rop = classHierarchy.SHORT;
} else if (value < 0) {
rop = classHierarchy.BYTE;
} else if (value < 2) {
rop = classHierarchy.R0_1;
} else if (value < 128) {
rop = classHierarchy.R0_127;
} else if (value < 32768) {
rop = classHierarchy.R0_32767;
} else if (value < 65536) {
rop = classHierarchy.CHAR;
} else {
rop = classHierarchy.INT;
}
} else if (rv instanceof LongConstant) {
} else if (rv instanceof NullConstant) {
} else if (rv instanceof StringConstant) {
} else if (rv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if ((be instanceof AddExpr) || (be instanceof SubExpr) || (be instanceof MulExpr) || (be instanceof DivExpr)
|| (be instanceof RemExpr)) {
if (lop != null && rop != null) {
if (!lop.hasAncestor_1(classHierarchy.INT)) {
if (fix) {
be.setOp1(insertCast(be.getOp1(), getTypeForCast(lop), IntType.v(), stmt));
} else {
error("Type Error(7)");
}
}
if (!rop.hasAncestor_1(classHierarchy.INT)) {
if (fix) {
be.setOp2(insertCast(be.getOp2(), getTypeForCast(rop), IntType.v(), stmt));
} else {
error("Type Error(8)");
}
}
}
right = classHierarchy.INT;
} else if ((be instanceof AndExpr) || (be instanceof OrExpr) || (be instanceof XorExpr)) {
if (lop != null && rop != null) {
TypeNode lca = lop.lca_1(rop);
if (lca == classHierarchy.TOP) {
if (fix) {
if (!lop.hasAncestor_1(classHierarchy.INT)) {
be.setOp1(insertCast(be.getOp1(), getTypeForCast(lop), getTypeForCast(rop), stmt));
lca = rop;
}
if (!rop.hasAncestor_1(classHierarchy.INT)) {
be.setOp2(insertCast(be.getOp2(), getTypeForCast(rop), getTypeForCast(lop), stmt));
lca = lop;
}
} else {
error("Type Error(11)");
}
}
right = lca;
}
} else if (be instanceof ShlExpr) {
if (lop != null) {
if (!lop.hasAncestor_1(classHierarchy.INT)) {
if (fix) {
be.setOp1(insertCast(be.getOp1(), getTypeForCast(lop), IntType.v(), stmt));
} else {
error("Type Error(9)");
}
}
}
if (!rop.hasAncestor_1(classHierarchy.INT)) {
if (fix) {
be.setOp2(insertCast(be.getOp2(), getTypeForCast(rop), IntType.v(), stmt));
} else {
error("Type Error(10)");
}
}
right = (lop == null) ? null : classHierarchy.INT;
} else if ((be instanceof ShrExpr) || (be instanceof UshrExpr)) {
if (lop != null) {
if (!lop.hasAncestor_1(classHierarchy.INT)) {
if (fix) {
be.setOp1(insertCast(be.getOp1(), getTypeForCast(lop), ByteType.v(), stmt));
lop = classHierarchy.BYTE;
} else {
error("Type Error(9)");
}
}
}
if (!rop.hasAncestor_1(classHierarchy.INT)) {
if (fix) {
be.setOp2(insertCast(be.getOp2(), getTypeForCast(rop), IntType.v(), stmt));
} else {
error("Type Error(10)");
}
}
right = lop;
} else if ((be instanceof CmpExpr) || (be instanceof CmpgExpr) || (be instanceof CmplExpr)) {
right = classHierarchy.BYTE;
} else if ((be instanceof EqExpr) || (be instanceof GeExpr) || (be instanceof GtExpr) || (be instanceof LeExpr)
|| (be instanceof LtExpr) || (be instanceof NeExpr)) {
if (rop != null) {
TypeNode lca = lop.lca_1(rop);
if (lca == classHierarchy.TOP) {
if (fix) {
if (!lop.hasAncestor_1(classHierarchy.INT)) {
be.setOp1(insertCast(be.getOp1(), getTypeForCast(lop), getTypeForCast(rop), stmt));
}
if (!rop.hasAncestor_1(classHierarchy.INT)) {
be.setOp2(insertCast(be.getOp2(), getTypeForCast(rop), getTypeForCast(lop), stmt));
}
} else {
error("Type Error(11)");
}
}
}
right = classHierarchy.BOOLEAN;
} else {
throw new RuntimeException("Unhandled binary expression type: " + be.getClass());
}
} else if (r instanceof CastExpr) {
Type ty = ((CastExpr) r).getCastType();
if (ty instanceof IntegerType) {
right = classHierarchy.typeNode(ty);
}
} else if (r instanceof InstanceOfExpr) {
right = classHierarchy.BOOLEAN;
} else if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
handleInvokeExpr(ie, stmt);
Type retTy = ie.getMethodRef().getReturnType();
if (retTy instanceof IntegerType) {
right = classHierarchy.typeNode(retTy);
}
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
Value size = nae.getSize();
if (size instanceof Local) {
if (!classHierarchy.typeNode(((Local) size).getType()).hasAncestor_1(classHierarchy.INT)) {
if (fix) {
nae.setSize(insertCast((Local) size, IntType.v(), stmt));
} else {
error("Type Error(12)");
}
}
}
} else if (r instanceof NewExpr) {
} else if (r instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) r;
for (int i = 0; i < nmae.getSizeCount(); i++) {
Value size = nmae.getSize(i);
if (size instanceof Local) {
if (!classHierarchy.typeNode(((Local) size).getType()).hasAncestor_1(classHierarchy.INT)) {
if (fix) {
nmae.setSize(i, insertCast((Local) size, IntType.v(), stmt));
} else {
error("Type Error(13)");
}
}
}
}
} else if (r instanceof LengthExpr) {
right = classHierarchy.INT;
} else if (r instanceof NegExpr) {
NegExpr ne = (NegExpr) r;
Value op = ne.getOp();
if (op instanceof Local) {
Local local = (Local) op;
if (local.getType() instanceof IntegerType) {
TypeNode ltype = classHierarchy.typeNode(local.getType());
if (!ltype.hasAncestor_1(classHierarchy.INT)) {
if (fix) {
ne.setOp(insertCast(local, IntType.v(), stmt));
ltype = classHierarchy.BYTE;
} else {
error("Type Error(14)");
}
}
right = (ltype == classHierarchy.CHAR) ? classHierarchy.INT : ltype;
}
} else if (op instanceof DoubleConstant) {
} else if (op instanceof FloatConstant) {
} else if (op instanceof IntConstant) {
right = classHierarchy.INT;
} else if (op instanceof LongConstant) {
} else {
throw new RuntimeException("Unhandled neg expression operand type: " + op.getClass());
}
} else if (r instanceof Local) {
Type ty = ((Local) r).getType();
if (ty instanceof IntegerType) {
right = classHierarchy.typeNode(ty);
}
} else if (r instanceof InstanceFieldRef) {
Type ty = ((InstanceFieldRef) r).getFieldRef().type();
if (ty instanceof IntegerType) {
right = classHierarchy.typeNode(ty);
}
} else if (r instanceof StaticFieldRef) {
Type ty = ((StaticFieldRef) r).getFieldRef().type();
if (ty instanceof IntegerType) {
right = classHierarchy.typeNode(ty);
}
} else {
throw new RuntimeException("Unhandled assignment right hand side type: " + r.getClass());
}
if (left != null && right != null) {
if (!right.hasAncestor_1(left)) {
if (fix) {
stmt.setRightOp(insertCast(stmt.getRightOp(), getTypeForCast(right), getTypeForCast(left), stmt));
} else {
error("Type Error(15)");
}
}
}
}
// This method is a local kludge, for avoiding NullPointerExceptions
// when a R0_1, R0_127, or R0_32767 node is used in a type
// cast. A more elegant solution would work with the TypeNode
// type definition itself, but that would require a more thorough
// knowledge of the typing system than the kludger posesses.
static Type getTypeForCast(TypeNode node) {
if (node.type() == null) {
if (node == ClassHierarchy.v().R0_1) {
return BooleanType.v();
} else if (node == ClassHierarchy.v().R0_127) {
return ByteType.v();
} else if (node == ClassHierarchy.v().R0_32767) {
return ShortType.v();
}
// Perhaps we should throw an exception here, since I don't think
// there should be any other cases where node.type() is null.
// In case that supposition is incorrect, though, we'll just
// go on to return the null, and let the callers worry about it.
}
return node.type();
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
Value l = stmt.getLeftOp();
Value r = stmt.getRightOp();
if (l instanceof Local) {
Type locType = ((Local) l).getType();
if (locType instanceof IntegerType) {
TypeNode left = ClassHierarchy.v().typeNode((locType));
TypeNode right = ClassHierarchy.v().typeNode(r.getType());
if (!right.hasAncestor_1(left)) {
if (fix) {
stmt.setLeftOp(insertCastAfter((Local) l, getTypeForCast(left), getTypeForCast(right), stmt));
} else {
error("Type Error(16)");
}
}
}
}
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
}
@Override
public void caseGotoStmt(GotoStmt stmt) {
}
@Override
public void caseIfStmt(IfStmt stmt) {
ConditionExpr cond = (ConditionExpr) stmt.getCondition();
BinopExpr expr = cond;
Value lv = expr.getOp1();
Value rv = expr.getOp2();
TypeNode lop = null;
TypeNode rop = null;
// ******** LEFT ********
if (lv instanceof Local) {
Type ty = ((Local) lv).getType();
if (ty instanceof IntegerType) {
lop = ClassHierarchy.v().typeNode(ty);
}
} else if (lv instanceof DoubleConstant) {
} else if (lv instanceof FloatConstant) {
} else if (lv instanceof IntConstant) {
int value = ((IntConstant) lv).value;
if (value < -32768) {
lop = ClassHierarchy.v().INT;
} else if (value < -128) {
lop = ClassHierarchy.v().SHORT;
} else if (value < 0) {
lop = ClassHierarchy.v().BYTE;
} else if (value < 2) {
lop = ClassHierarchy.v().R0_1;
} else if (value < 128) {
lop = ClassHierarchy.v().R0_127;
} else if (value < 32768) {
lop = ClassHierarchy.v().R0_32767;
} else if (value < 65536) {
lop = ClassHierarchy.v().CHAR;
} else {
lop = ClassHierarchy.v().INT;
}
} else if (lv instanceof LongConstant) {
} else if (lv instanceof NullConstant) {
} else if (lv instanceof StringConstant) {
} else if (lv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
Type ty = ((Local) rv).getType();
if (ty instanceof IntegerType) {
rop = ClassHierarchy.v().typeNode(ty);
}
} else if (rv instanceof DoubleConstant) {
} else if (rv instanceof FloatConstant) {
} else if (rv instanceof IntConstant) {
int value = ((IntConstant) rv).value;
if (value < -32768) {
rop = ClassHierarchy.v().INT;
} else if (value < -128) {
rop = ClassHierarchy.v().SHORT;
} else if (value < 0) {
rop = ClassHierarchy.v().BYTE;
} else if (value < 2) {
rop = ClassHierarchy.v().R0_1;
} else if (value < 128) {
rop = ClassHierarchy.v().R0_127;
} else if (value < 32768) {
rop = ClassHierarchy.v().R0_32767;
} else if (value < 65536) {
rop = ClassHierarchy.v().CHAR;
} else {
rop = ClassHierarchy.v().INT;
}
} else if (rv instanceof LongConstant) {
} else if (rv instanceof NullConstant) {
} else if (rv instanceof StringConstant) {
} else if (rv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if (lop != null && rop != null) {
if (lop.lca_1(rop) == ClassHierarchy.v().TOP) {
if (fix) {
if (!lop.hasAncestor_1(ClassHierarchy.v().INT)) {
expr.setOp1(insertCast(expr.getOp1(), getTypeForCast(lop), getTypeForCast(rop), stmt));
}
if (!rop.hasAncestor_1(ClassHierarchy.v().INT)) {
expr.setOp2(insertCast(expr.getOp2(), getTypeForCast(rop), getTypeForCast(lop), stmt));
}
} else {
error("Type Error(17)");
}
}
}
}
@Override
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
Value key = stmt.getKey();
if (key instanceof Local) {
if (!ClassHierarchy.v().typeNode(((Local) key).getType()).hasAncestor_1(ClassHierarchy.v().INT)) {
if (fix) {
stmt.setKey(insertCast((Local) key, IntType.v(), stmt));
} else {
error("Type Error(18)");
}
}
}
}
@Override
public void caseNopStmt(NopStmt stmt) {
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
Value op = stmt.getOp();
if (op instanceof Local) {
Type opType = ((Local) op).getType();
if (opType instanceof IntegerType) {
Type returnType = stmtBody.getMethod().getReturnType();
if (!ClassHierarchy.v().typeNode(opType).hasAncestor_1(ClassHierarchy.v().typeNode(returnType))) {
if (fix) {
stmt.setOp(insertCast((Local) op, returnType, stmt));
} else {
error("Type Error(19)");
}
}
}
}
}
@Override
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
@Override
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
Value key = stmt.getKey();
if (key instanceof Local) {
Local keyLocal = (Local) key;
if (!ClassHierarchy.v().typeNode((keyLocal).getType()).hasAncestor_1(ClassHierarchy.v().INT)) {
if (fix) {
stmt.setKey(insertCast(keyLocal, IntType.v(), stmt));
} else {
error("Type Error(20)");
}
}
resolver.typeVariable(keyLocal).addParent(resolver.INT);
}
}
@Override
public void caseThrowStmt(ThrowStmt stmt) {
}
public void defaultCase(Stmt stmt) {
throw new RuntimeException("Unhandled statement type: " + stmt.getClass());
}
private Local insertCast(Local oldlocal, Type type, Stmt stmt) {
final Jimple jimp = Jimple.v();
Local newlocal = localGenerator.generateLocal(type);
stmtBody.getUnits().insertBefore(jimp.newAssignStmt(newlocal, jimp.newCastExpr(oldlocal, type)),
Util.findFirstNonIdentityUnit(this.stmtBody, stmt));
return newlocal;
}
private Local insertCastAfter(Local leftlocal, Type lefttype, Type righttype, Stmt stmt) {
final Jimple jimp = Jimple.v();
Local newlocal = localGenerator.generateLocal(righttype);
stmtBody.getUnits().insertAfter(jimp.newAssignStmt(leftlocal, jimp.newCastExpr(newlocal, lefttype)),
Util.findLastIdentityUnit(this.stmtBody, stmt));
return newlocal;
}
private Local insertCast(Value oldvalue, Type oldtype, Type type, Stmt stmt) {
final Jimple jimp = Jimple.v();
Local newlocal1 = localGenerator.generateLocal(oldtype);
Local newlocal2 = localGenerator.generateLocal(type);
Unit u = Util.findFirstNonIdentityUnit(this.stmtBody, stmt);
final UnitPatchingChain units = stmtBody.getUnits();
units.insertBefore(jimp.newAssignStmt(newlocal1, oldvalue), u);
units.insertBefore(jimp.newAssignStmt(newlocal2, jimp.newCastExpr(newlocal1, type)), u);
return newlocal2;
}
}
| 27,930
| 32.25119
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/ConstraintCollector.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.ArrayType;
import soot.IntegerType;
import soot.Local;
import soot.NullType;
import soot.SootMethodRef;
import soot.Type;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.DynamicInvokeExpr;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.XorExpr;
class ConstraintCollector extends AbstractStmtSwitch {
private final TypeResolver resolver;
private final boolean uses; // if true, include use contraints
private JimpleBody stmtBody;
public ConstraintCollector(TypeResolver resolver, boolean uses) {
this.resolver = resolver;
this.uses = uses;
}
public void collect(Stmt stmt, JimpleBody stmtBody) {
this.stmtBody = stmtBody;
stmt.apply(this);
}
private void handleInvokeExpr(InvokeExpr ie) {
if (!uses) {
return;
}
// Handle the parameters
SootMethodRef method = ie.getMethodRef();
for (int i = 0; i < ie.getArgCount(); i++) {
Value arg = ie.getArg(i);
if (arg instanceof Local) {
Local local = (Local) arg;
if (local.getType() instanceof IntegerType) {
TypeVariable localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
}
if (ie instanceof DynamicInvokeExpr) {
DynamicInvokeExpr die = (DynamicInvokeExpr) ie;
SootMethodRef bootstrapMethod = die.getBootstrapMethodRef();
for (int i = 0; i < die.getBootstrapArgCount(); i++) {
Value arg = die.getBootstrapArg(i);
if (arg instanceof Local) {
Local local = (Local) arg;
if (local.getType() instanceof IntegerType) {
TypeVariable localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(bootstrapMethod.parameterType(i)));
}
}
}
}
}
@Override
public void caseBreakpointStmt(BreakpointStmt stmt) {
// Do nothing
}
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
handleInvokeExpr(stmt.getInvokeExpr());
}
@Override
public void caseAssignStmt(AssignStmt stmt) {
final Value l = stmt.getLeftOp();
final Value r = stmt.getRightOp();
TypeVariable left = null;
TypeVariable right = null;
// ******** LEFT ********
if (l instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) l;
Type baset = ((Local) ref.getBase()).getType();
if (baset instanceof ArrayType) {
ArrayType base = (ArrayType) baset;
Value index = ref.getIndex();
if (uses) {
if ((base.numDimensions == 1) && (base.baseType instanceof IntegerType)) {
left = resolver.typeVariable(base.baseType);
}
if (index instanceof Local) {
resolver.typeVariable((Local) index).addParent(resolver.INT);
}
}
}
} else if (l instanceof Local) {
Local loc = (Local) l;
if (loc.getType() instanceof IntegerType) {
left = resolver.typeVariable(loc);
}
} else if (l instanceof InstanceFieldRef) {
if (uses) {
InstanceFieldRef ref = (InstanceFieldRef) l;
Type fieldType = ref.getFieldRef().type();
if (fieldType instanceof IntegerType) {
left = resolver.typeVariable(fieldType);
}
}
} else if (l instanceof StaticFieldRef) {
if (uses) {
StaticFieldRef ref = (StaticFieldRef) l;
Type fieldType = ref.getFieldRef().type();
if (fieldType instanceof IntegerType) {
left = resolver.typeVariable(fieldType);
}
}
} else {
throw new RuntimeException("Unhandled assignment left hand side type: " + l.getClass());
}
// ******** RIGHT ********
if (r instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) r;
Type baset = ((Local) ref.getBase()).getType();
if (!(baset instanceof NullType)) {
Value index = ref.getIndex();
// Be careful, dex can do some weird object/array casting
if (baset instanceof ArrayType) {
ArrayType base = (ArrayType) baset;
if ((base.numDimensions == 1) && (base.baseType instanceof IntegerType)) {
right = resolver.typeVariable(base.baseType);
}
} else if (baset instanceof IntegerType) {
right = resolver.typeVariable(baset);
}
if (uses) {
if (index instanceof Local) {
resolver.typeVariable((Local) index).addParent(resolver.INT);
}
}
}
} else if (r instanceof DoubleConstant) {
} else if (r instanceof FloatConstant) {
} else if (r instanceof IntConstant) {
int value = ((IntConstant) r).value;
if (value < -32768) {
right = resolver.INT;
} else if (value < -128) {
right = resolver.SHORT;
} else if (value < 0) {
right = resolver.BYTE;
} else if (value < 2) {
right = resolver.R0_1;
} else if (value < 128) {
right = resolver.R0_127;
} else if (value < 32768) {
right = resolver.R0_32767;
} else if (value < 65536) {
right = resolver.CHAR;
} else {
right = resolver.INT;
}
} else if (r instanceof LongConstant) {
} else if (r instanceof NullConstant) {
} else if (r instanceof StringConstant) {
} else if (r instanceof ClassConstant) {
} else if (r instanceof BinopExpr) {
// ******** BINOP EXPR ********
BinopExpr be = (BinopExpr) r;
Value lv = be.getOp1();
Value rv = be.getOp2();
TypeVariable lop = null;
TypeVariable rop = null;
// ******** LEFT ********
if (lv instanceof Local) {
Local loc = (Local) lv;
if (loc.getType() instanceof IntegerType) {
lop = resolver.typeVariable(loc);
}
} else if (lv instanceof DoubleConstant) {
} else if (lv instanceof FloatConstant) {
} else if (lv instanceof IntConstant) {
int value = ((IntConstant) lv).value;
if (value < -32768) {
lop = resolver.INT;
} else if (value < -128) {
lop = resolver.SHORT;
} else if (value < 0) {
lop = resolver.BYTE;
} else if (value < 2) {
lop = resolver.R0_1;
} else if (value < 128) {
lop = resolver.R0_127;
} else if (value < 32768) {
lop = resolver.R0_32767;
} else if (value < 65536) {
lop = resolver.CHAR;
} else {
lop = resolver.INT;
}
} else if (lv instanceof LongConstant) {
} else if (lv instanceof NullConstant) {
} else if (lv instanceof StringConstant) {
} else if (lv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
Local loc = (Local) rv;
if (loc.getType() instanceof IntegerType) {
rop = resolver.typeVariable(loc);
}
} else if (rv instanceof DoubleConstant) {
} else if (rv instanceof FloatConstant) {
} else if (rv instanceof IntConstant) {
int value = ((IntConstant) rv).value;
if (value < -32768) {
rop = resolver.INT;
} else if (value < -128) {
rop = resolver.SHORT;
} else if (value < 0) {
rop = resolver.BYTE;
} else if (value < 2) {
rop = resolver.R0_1;
} else if (value < 128) {
rop = resolver.R0_127;
} else if (value < 32768) {
rop = resolver.R0_32767;
} else if (value < 65536) {
rop = resolver.CHAR;
} else {
rop = resolver.INT;
}
} else if (rv instanceof LongConstant) {
} else if (rv instanceof NullConstant) {
} else if (rv instanceof StringConstant) {
} else if (rv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if ((be instanceof AddExpr) || (be instanceof SubExpr) || (be instanceof DivExpr) || (be instanceof RemExpr)
|| (be instanceof MulExpr)) {
if (lop != null && rop != null) {
if (uses) {
if (lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = resolver.INT;
}
} else if ((be instanceof AndExpr) || (be instanceof OrExpr) || (be instanceof XorExpr)) {
if (lop != null && rop != null) {
right = resolver.typeVariable();
rop.addParent(right);
lop.addParent(right);
}
} else if (be instanceof ShlExpr) {
if (uses) {
if (lop != null && lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = (lop == null) ? null : resolver.INT;
} else if ((be instanceof ShrExpr) || (be instanceof UshrExpr)) {
if (uses) {
if (lop != null && lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = lop;
} else if ((be instanceof CmpExpr) || (be instanceof CmpgExpr) || (be instanceof CmplExpr)) {
right = resolver.BYTE;
} else if ((be instanceof EqExpr) || (be instanceof GeExpr) || (be instanceof GtExpr) || (be instanceof LeExpr)
|| (be instanceof LtExpr) || (be instanceof NeExpr)) {
if (uses) {
TypeVariable common = resolver.typeVariable();
if (rop != null) {
rop.addParent(common);
}
if (lop != null) {
lop.addParent(common);
}
}
right = resolver.BOOLEAN;
} else {
throw new RuntimeException("Unhandled binary expression type: " + be.getClass());
}
} else if (r instanceof CastExpr) {
Type ty = ((CastExpr) r).getCastType();
if (ty instanceof IntegerType) {
right = resolver.typeVariable(ty);
}
} else if (r instanceof InstanceOfExpr) {
right = resolver.BOOLEAN;
} else if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
handleInvokeExpr(ie);
Type returnType = ie.getMethodRef().getReturnType();
if (returnType instanceof IntegerType) {
right = resolver.typeVariable(returnType);
}
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
if (uses) {
Value size = nae.getSize();
if (size instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) size);
var.addParent(resolver.INT);
}
}
} else if (r instanceof NewExpr) {
} else if (r instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) r;
if (uses) {
for (int i = 0; i < nmae.getSizeCount(); i++) {
Value size = nmae.getSize(i);
if (size instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) size);
var.addParent(resolver.INT);
}
}
}
} else if (r instanceof LengthExpr) {
right = resolver.INT;
} else if (r instanceof NegExpr) {
NegExpr ne = (NegExpr) r;
if (ne.getOp() instanceof Local) {
Local local = (Local) ne.getOp();
if (local.getType() instanceof IntegerType) {
if (uses) {
resolver.typeVariable(local).addParent(resolver.INT);
}
right = resolver.typeVariable();
right.addChild(resolver.BYTE);
right.addChild(resolver.typeVariable(local));
}
} else if (ne.getOp() instanceof DoubleConstant) {
} else if (ne.getOp() instanceof FloatConstant) {
} else if (ne.getOp() instanceof IntConstant) {
int value = ((IntConstant) ne.getOp()).value;
if (value < -32768) {
right = resolver.INT;
} else if (value < -128) {
right = resolver.SHORT;
} else if (value < 0) {
right = resolver.BYTE;
} else if (value < 2) {
right = resolver.BYTE;
} else if (value < 128) {
right = resolver.BYTE;
} else if (value < 32768) {
right = resolver.SHORT;
} else if (value < 65536) {
right = resolver.INT;
} else {
right = resolver.INT;
}
} else if (ne.getOp() instanceof LongConstant) {
} else {
throw new RuntimeException("Unhandled neg expression operand type: " + ne.getOp().getClass());
}
} else if (r instanceof Local) {
Local local = (Local) r;
if (local.getType() instanceof IntegerType) {
right = resolver.typeVariable(local);
}
} else if (r instanceof InstanceFieldRef) {
Type type = ((InstanceFieldRef) r).getFieldRef().type();
if (type instanceof IntegerType) {
right = resolver.typeVariable(type);
}
} else if (r instanceof StaticFieldRef) {
Type type = ((StaticFieldRef) r).getFieldRef().type();
if (type instanceof IntegerType) {
right = resolver.typeVariable(type);
}
} else {
throw new RuntimeException("Unhandled assignment right hand side type: " + r.getClass());
}
if (left != null && right != null && (left.type() == null || right.type() == null)) {
right.addParent(left);
}
}
@Override
public void caseIdentityStmt(IdentityStmt stmt) {
Value l = stmt.getLeftOp();
if (l instanceof Local) {
Local loc = (Local) l;
if (loc.getType() instanceof IntegerType) {
TypeVariable left = resolver.typeVariable(loc);
TypeVariable right = resolver.typeVariable(stmt.getRightOp().getType());
right.addParent(left);
}
}
}
@Override
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
}
@Override
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
}
@Override
public void caseGotoStmt(GotoStmt stmt) {
}
@Override
public void caseIfStmt(IfStmt stmt) {
if (uses) {
final ConditionExpr expr = (ConditionExpr) stmt.getCondition();
final Value lv = expr.getOp1();
final Value rv = expr.getOp2();
TypeVariable lop = null;
TypeVariable rop = null;
// ******** LEFT ********
if (lv instanceof Local) {
Local loc = (Local) lv;
if ((loc).getType() instanceof IntegerType) {
lop = resolver.typeVariable(loc);
}
} else if (lv instanceof DoubleConstant) {
} else if (lv instanceof FloatConstant) {
} else if (lv instanceof IntConstant) {
int value = ((IntConstant) lv).value;
if (value < -32768) {
lop = resolver.INT;
} else if (value < -128) {
lop = resolver.SHORT;
} else if (value < 0) {
lop = resolver.BYTE;
} else if (value < 2) {
lop = resolver.R0_1;
} else if (value < 128) {
lop = resolver.R0_127;
} else if (value < 32768) {
lop = resolver.R0_32767;
} else if (value < 65536) {
lop = resolver.CHAR;
} else {
lop = resolver.INT;
}
} else if (lv instanceof LongConstant) {
} else if (lv instanceof NullConstant) {
} else if (lv instanceof StringConstant) {
} else if (lv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
Local loc = (Local) rv;
if ((loc).getType() instanceof IntegerType) {
rop = resolver.typeVariable(loc);
}
} else if (rv instanceof DoubleConstant) {
} else if (rv instanceof FloatConstant) {
} else if (rv instanceof IntConstant) {
int value = ((IntConstant) rv).value;
if (value < -32768) {
rop = resolver.INT;
} else if (value < -128) {
rop = resolver.SHORT;
} else if (value < 0) {
rop = resolver.BYTE;
} else if (value < 2) {
rop = resolver.R0_1;
} else if (value < 128) {
rop = resolver.R0_127;
} else if (value < 32768) {
rop = resolver.R0_32767;
} else if (value < 65536) {
rop = resolver.CHAR;
} else {
rop = resolver.INT;
}
} else if (rv instanceof LongConstant) {
} else if (rv instanceof NullConstant) {
} else if (rv instanceof StringConstant) {
} else if (rv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if (rop != null && lop != null) {
TypeVariable common = resolver.typeVariable();
rop.addParent(common);
lop.addParent(common);
}
}
}
@Override
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.INT);
}
}
}
@Override
public void caseNopStmt(NopStmt stmt) {
}
@Override
public void caseReturnStmt(ReturnStmt stmt) {
if (uses) {
Value op = stmt.getOp();
if (op instanceof Local) {
Local opLocal = (Local) op;
if (opLocal.getType() instanceof IntegerType) {
resolver.typeVariable(opLocal).addParent(resolver.typeVariable(stmtBody.getMethod().getReturnType()));
}
}
}
}
@Override
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
@Override
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.INT);
}
}
}
@Override
public void caseThrowStmt(ThrowStmt stmt) {
}
public void defaultCase(Stmt stmt) {
throw new RuntimeException("Unhandled statement type: " + stmt.getClass());
}
}
| 20,898
| 30.569486
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/InternalTypingException.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Type;
class InternalTypingException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1874994601632508834L;
private final Type unexpectedType;
public InternalTypingException() {
this.unexpectedType = null;
}
public InternalTypingException(Type unexpectedType) {
this.unexpectedType = unexpectedType;
}
public Type getUnexpectedType() {
return this.unexpectedType;
}
@Override
public String getMessage() {
return String.format("Unexpected type %s (%s)", unexpectedType,
unexpectedType == null ? "-" : unexpectedType.getClass().getSimpleName());
}
}
| 1,527
| 27.830189
| 82
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/StronglyConnectedComponents.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class StronglyConnectedComponents {
private static final Logger logger = LoggerFactory.getLogger(StronglyConnectedComponents.class);
private static final boolean DEBUG = false;
private final Set<TypeVariable> black = new TreeSet<TypeVariable>();
private final List<TypeVariable> finished = new LinkedList<TypeVariable>();
private List<TypeVariable> current_tree = new LinkedList<TypeVariable>();
public static void merge(List<TypeVariable> typeVariableList) throws TypeException {
new StronglyConnectedComponents(typeVariableList);
}
private StronglyConnectedComponents(List<TypeVariable> typeVariableList) throws TypeException {
for (TypeVariable var : typeVariableList) {
if (!black.contains(var)) {
black.add(var);
dfsg_visit(var);
}
}
black.clear();
final List<List<TypeVariable>> forest = new LinkedList<List<TypeVariable>>();
for (TypeVariable var : finished) {
if (!black.contains(var)) {
current_tree = new LinkedList<TypeVariable>();
forest.add(current_tree);
black.add(var);
dfsgt_visit(var);
}
}
for (List<TypeVariable> list : forest) {
StringBuilder s = DEBUG ? new StringBuilder("scc:\n") : null;
TypeVariable previous = null;
for (TypeVariable current : list) {
if (DEBUG) {
s.append(' ').append(current).append('\n');
}
if (previous == null) {
previous = current;
} else {
try {
previous = previous.union(current);
} catch (TypeException e) {
if (DEBUG) {
logger.debug(s.toString());
}
throw e;
}
}
}
}
}
private void dfsg_visit(TypeVariable var) {
for (TypeVariable parent : var.parents()) {
if (!black.contains(parent)) {
black.add(parent);
dfsg_visit(parent);
}
}
finished.add(0, var);
}
private void dfsgt_visit(TypeVariable var) {
current_tree.add(var);
for (TypeVariable child : var.children()) {
if (!black.contains(child)) {
black.add(child);
dfsgt_visit(child);
}
}
}
}
| 3,227
| 28.614679
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/TypeException.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class TypeException extends Exception {
/**
*
*/
private static final long serialVersionUID = -602930090190087993L;
public TypeException(String message) {
super(message);
if (message == null) {
throw new InternalTypingException();
}
}
public TypeException(String message, Throwable cause) {
super(message, cause);
if (message == null) {
throw new InternalTypingException();
}
}
}
| 1,319
| 28.333333
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/TypeNode.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Type;
/**
* Each instance of this class represents one basic type.
**/
class TypeNode {
private static final Logger logger = LoggerFactory.getLogger(TypeNode.class);
public static final boolean DEBUG = false;
private final int id;
private final Type type;
public TypeNode(int id, Type type) {
this.id = id;
this.type = type;
if (DEBUG) {
logger.debug("creating node " + this);
}
}
/** Returns the unique id of this type node. **/
public int id() {
return id;
}
/** Returns the type represented by this type node. **/
public Type type() {
return type;
}
public boolean hasAncestor_1(TypeNode typeNode) {
if (typeNode == this) {
return true;
}
return ClassHierarchy.v().hasAncestor_1(id, typeNode.id);
}
public boolean hasAncestor_2(TypeNode typeNode) {
if (typeNode == this) {
return true;
}
return ClassHierarchy.v().hasAncestor_2(id, typeNode.id);
}
/*
* public boolean hasDescendant_1(TypeNode typeNode) { return ClassHierarchy.v().hasDescendant_1(id, typeNode.id); }
*
* public boolean hasDescendant_2(TypeNode typeNode) { return ClassHierarchy.v().hasDescendant_2(id, typeNode.id); }
*
* public boolean hasDescendantOrSelf_1(TypeNode typeNode) { if(typeNode == this) return true;
*
* return hasDescendant_1(typeNode); }
*
* public boolean hasDescendantOrSelf_2(TypeNode typeNode) { if(typeNode == this) return true;
*
* return hasDescendant_2(typeNode); }
*/
public TypeNode lca_1(TypeNode typeNode) {
return ClassHierarchy.v().lca_1(id, typeNode.id);
}
public TypeNode lca_2(TypeNode typeNode) {
return ClassHierarchy.v().lca_2(id, typeNode.id);
}
public TypeNode gcd_1(TypeNode typeNode) {
return ClassHierarchy.v().gcd_1(id, typeNode.id);
}
public TypeNode gcd_2(TypeNode typeNode) {
return ClassHierarchy.v().gcd_2(id, typeNode.id);
}
@Override
public String toString() {
if (type != null) {
return type + "(" + id + ")";
}
final ClassHierarchy classHierarchy = ClassHierarchy.v();
if (this == classHierarchy.TOP) {
return "TOP(" + id + ")";
} else if (this == classHierarchy.R0_1) {
return "R0_1(" + id + ")";
} else if (this == classHierarchy.R0_127) {
return "R0_127(" + id + ")";
} else if (this == classHierarchy.R0_32767) {
return "R0_32767(" + id + ")";
} else {
return "ERROR!!!!";
}
}
}
| 3,419
| 26.36
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/TypeResolver.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.BooleanType;
import soot.ByteType;
import soot.IntegerType;
import soot.Local;
import soot.ShortType;
import soot.Type;
import soot.Unit;
import soot.jimple.JimpleBody;
import soot.jimple.Stmt;
/**
* This class resolves the type of local variables.
**/
public class TypeResolver {
private static final Logger logger = LoggerFactory.getLogger(TypeResolver.class);
private static final boolean DEBUG = false;
private static final boolean IMPERFORMANT_TYPE_CHECK = false;
/** All type variable instances **/
private final List<TypeVariable> typeVariableList = new ArrayList<TypeVariable>();
/** Hashtable: [TypeNode or Local] -> TypeVariable **/
private final Map<Object, TypeVariable> typeVariableMap = new HashMap<Object, TypeVariable>();
final TypeVariable BOOLEAN = typeVariable(ClassHierarchy.v().BOOLEAN);
final TypeVariable BYTE = typeVariable(ClassHierarchy.v().BYTE);
final TypeVariable SHORT = typeVariable(ClassHierarchy.v().SHORT);
final TypeVariable CHAR = typeVariable(ClassHierarchy.v().CHAR);
final TypeVariable INT = typeVariable(ClassHierarchy.v().INT);
final TypeVariable TOP = typeVariable(ClassHierarchy.v().TOP);
final TypeVariable R0_1 = typeVariable(ClassHierarchy.v().R0_1);
final TypeVariable R0_127 = typeVariable(ClassHierarchy.v().R0_127);
final TypeVariable R0_32767 = typeVariable(ClassHierarchy.v().R0_32767);
private final JimpleBody stmtBody;
// categories for type variables (solved = hard, unsolved = soft)
private Collection<TypeVariable> unsolved;
private Collection<TypeVariable> solved;
private TypeResolver(JimpleBody stmtBody) {
this.stmtBody = stmtBody;
}
public static void resolve(JimpleBody stmtBody) {
if (DEBUG) {
logger.debug("" + stmtBody.getMethod());
}
try {
TypeResolver resolver = new TypeResolver(stmtBody);
resolver.resolve_step_1();
} catch (TypeException e1) {
if (DEBUG) {
logger.debug("[integer] Step 1 Exception-->" + e1.getMessage());
}
try {
TypeResolver resolver = new TypeResolver(stmtBody);
resolver.resolve_step_2();
} catch (TypeException e2) {
StringWriter st = new StringWriter();
PrintWriter pw = new PrintWriter(st);
logger.error(e2.getMessage(), e2);
pw.close();
throw new RuntimeException(st.toString());
}
}
}
/** Get type variable for the given local. **/
TypeVariable typeVariable(Local local) {
TypeVariable result = typeVariableMap.get(local);
if (result == null) {
int id = typeVariableList.size();
typeVariableList.add(null);
result = new TypeVariable(id, this);
typeVariableList.set(id, result);
typeVariableMap.put(local, result);
if (DEBUG) {
logger.debug("[LOCAL VARIABLE \"" + local + "\" -> " + id + "]");
}
}
return result;
}
/** Get type variable for the given type node. **/
public TypeVariable typeVariable(TypeNode typeNode) {
TypeVariable result = typeVariableMap.get(typeNode);
if (result == null) {
int id = typeVariableList.size();
typeVariableList.add(null);
result = new TypeVariable(id, this, typeNode);
typeVariableList.set(id, result);
typeVariableMap.put(typeNode, result);
}
return result;
}
/** Get type variable for the given type. **/
public TypeVariable typeVariable(Type type) {
return typeVariable(ClassHierarchy.v().typeNode(type));
}
/** Get new type variable **/
public TypeVariable typeVariable() {
int id = typeVariableList.size();
typeVariableList.add(null);
TypeVariable result = new TypeVariable(id, this);
typeVariableList.set(id, result);
return result;
}
private void debug_vars(String message) {
if (DEBUG) {
int count = 0;
logger.debug("**** START:" + message);
for (TypeVariable var : typeVariableList) {
logger.debug("" + count++ + " " + var);
}
logger.debug("**** END:" + message);
}
}
private void resolve_step_1() throws TypeException {
collect_constraints_1();
debug_vars("constraints");
compute_approximate_types();
merge_connected_components();
debug_vars("components");
merge_single_constraints();
debug_vars("single");
assign_types_1();
debug_vars("assign");
check_and_fix_constraints();
}
private void resolve_step_2() throws TypeException {
collect_constraints_2();
compute_approximate_types();
assign_types_2();
check_and_fix_constraints();
}
private void collect_constraints_1() {
ConstraintCollector collector = new ConstraintCollector(this, true);
for (Unit u : stmtBody.getUnits()) {
final Stmt stmt = (Stmt) u;
if (DEBUG) {
logger.debug("stmt: ");
}
collector.collect(stmt, stmtBody);
if (DEBUG) {
logger.debug("" + stmt);
}
}
}
private void collect_constraints_2() {
ConstraintCollector collector = new ConstraintCollector(this, false);
for (Unit u : stmtBody.getUnits()) {
final Stmt stmt = (Stmt) u;
if (DEBUG) {
logger.debug("stmt: ");
}
collector.collect(stmt, stmtBody);
if (DEBUG) {
logger.debug("" + stmt);
}
}
}
private void merge_connected_components() throws TypeException {
compute_solved();
if (IMPERFORMANT_TYPE_CHECK) {
List<TypeVariable> list = new ArrayList<TypeVariable>(solved.size() + unsolved.size());
list.addAll(solved);
list.addAll(unsolved);
// MMI: This method does not perform any changing effect
// on the list, just a bit error checking, if
// I see this correctly.
StronglyConnectedComponents.merge(list);
}
}
private void merge_single_constraints() throws TypeException {
for (boolean modified = true; modified;) {
modified = false;
refresh_solved();
for (TypeVariable var : unsolved) {
var.fixChildren();
TypeNode lca = null;
List<TypeVariable> children_to_remove = new LinkedList<TypeVariable>();
for (TypeVariable child : var.children()) {
TypeNode type = child.type();
if (type != null) {
children_to_remove.add(child);
lca = (lca == null) ? type : lca.lca_1(type);
}
}
if (lca != null) {
if (DEBUG) {
if (lca == ClassHierarchy.v().TOP) {
logger.debug("*** TOP *** " + var);
for (TypeVariable typeVariable : children_to_remove) {
logger.debug("-- " + typeVariable);
}
}
}
for (TypeVariable child : children_to_remove) {
var.removeChild(child);
}
var.addChild(typeVariable(lca));
}
if (var.children().size() == 1) {
TypeVariable child = var.children().get(0);
TypeNode type = child.type();
if (type == null || type.type() != null) {
var.union(child);
modified = true;
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
var.fixParents();
TypeNode gcd = null;
List<TypeVariable> parents_to_remove = new LinkedList<TypeVariable>();
for (TypeVariable parent : var.parents()) {
TypeNode type = parent.type();
if (type != null) {
parents_to_remove.add(parent);
gcd = (gcd == null) ? type : gcd.gcd_1(type);
}
}
if (gcd != null) {
for (TypeVariable parent : parents_to_remove) {
var.removeParent(parent);
}
var.addParent(typeVariable(gcd));
}
if (var.parents().size() == 1) {
TypeVariable parent = var.parents().get(0);
TypeNode type = parent.type();
if (type == null || type.type() != null) {
var.union(parent);
modified = true;
}
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
if (var.type() == null) {
final TypeNode inv_approx = var.inv_approx();
if (inv_approx != null && inv_approx.type() != null) {
if (DEBUG) {
logger.debug("*** I->" + inv_approx.type() + " *** " + var);
}
var.union(typeVariable(inv_approx));
modified = true;
}
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
if (var.type() == null) {
final TypeNode approx = var.approx();
if (approx != null && approx.type() != null) {
if (DEBUG) {
logger.debug("*** A->" + approx.type() + " *** " + var);
}
var.union(typeVariable(approx));
modified = true;
}
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
if (var.type() == null && var.approx() == ClassHierarchy.v().R0_32767) {
if (DEBUG) {
logger.debug("*** R->SHORT *** " + var);
}
var.union(SHORT);
modified = true;
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
if (var.type() == null && var.approx() == ClassHierarchy.v().R0_127) {
if (DEBUG) {
logger.debug("*** R->BYTE *** " + var);
}
var.union(BYTE);
modified = true;
}
}
}
if (!modified) {
for (TypeVariable var : R0_1.parents()) {
if (var.type() == null && var.approx() == ClassHierarchy.v().R0_1) {
if (DEBUG) {
logger.debug("*** R->BOOLEAN *** " + var);
}
var.union(BOOLEAN);
modified = true;
}
}
}
}
}
private void assign_types_1() throws TypeException {
for (Local local : stmtBody.getLocals()) {
if (local.getType() instanceof IntegerType) {
TypeVariable var = typeVariable(local);
TypeNode type = var.type();
if (type == null || type.type() == null) {
TypeVariable.error("Type Error(21): Variable without type");
} else {
local.setType(type.type());
}
if (DEBUG) {
if ((var != null) && (var.approx() != null) && (var.approx().type() != null) && (local != null)
&& (local.getType() != null) && !local.getType().equals(var.approx().type())) {
logger.debug("local: " + local + ", type: " + local.getType() + ", approx: " + var.approx().type());
}
}
}
}
}
private void assign_types_2() throws TypeException {
for (Local local : stmtBody.getLocals()) {
if (local.getType() instanceof IntegerType) {
TypeVariable var = typeVariable(local);
TypeNode inv_approx = var.inv_approx();
if (inv_approx != null && inv_approx.type() != null) {
local.setType(inv_approx.type());
} else {
TypeNode approx = var.approx();
if (approx.type() != null) {
local.setType(approx.type());
} else if (approx == ClassHierarchy.v().R0_1) {
local.setType(BooleanType.v());
} else if (approx == ClassHierarchy.v().R0_127) {
local.setType(ByteType.v());
} else {
local.setType(ShortType.v());
}
}
}
}
}
private void check_constraints() throws TypeException {
ConstraintChecker checker = new ConstraintChecker(this, false);
StringBuilder s = DEBUG ? new StringBuilder("Checking:\n") : null;
for (Unit stmt : stmtBody.getUnits()) {
if (DEBUG) {
s.append(' ').append(stmt).append('\n');
}
try {
checker.check((Stmt) stmt, stmtBody);
} catch (TypeException e) {
if (DEBUG) {
logger.debug(s.toString());
}
throw e;
}
}
}
private void check_and_fix_constraints() throws TypeException {
ConstraintChecker checker = new ConstraintChecker(this, true);
StringBuilder s = DEBUG ? new StringBuilder("Checking:\n") : null;
for (Iterator<Unit> it = stmtBody.getUnits().snapshotIterator(); it.hasNext();) {
Unit stmt = it.next();
if (DEBUG) {
s.append(' ').append(stmt).append('\n');
}
try {
checker.check((Stmt) stmt, stmtBody);
} catch (TypeException e) {
if (DEBUG) {
logger.debug(s.toString());
}
throw e;
}
}
}
private void compute_approximate_types() throws TypeException {
{
TreeSet<TypeVariable> workList = new TreeSet<TypeVariable>();
for (TypeVariable var : typeVariableList) {
if (var.type() != null) {
workList.add(var);
}
}
TypeVariable.computeApprox(workList);
}
{
TreeSet<TypeVariable> workList = new TreeSet<TypeVariable>();
for (TypeVariable var : typeVariableList) {
if (var.type() != null) {
workList.add(var);
}
}
TypeVariable.computeInvApprox(workList);
}
for (TypeVariable var : typeVariableList) {
if (var.approx() == null) {
var.union(INT);
}
}
}
private void compute_solved() {
Set<TypeVariable> unsolved_set = new TreeSet<TypeVariable>();
Set<TypeVariable> solved_set = new TreeSet<TypeVariable>();
for (TypeVariable var : typeVariableList) {
if (var.type() == null) {
unsolved_set.add(var);
} else {
solved_set.add(var);
}
}
solved = solved_set;
unsolved = unsolved_set;
}
private void refresh_solved() throws TypeException {
Set<TypeVariable> unsolved_set = new TreeSet<TypeVariable>();
Set<TypeVariable> solved_set = new TreeSet<TypeVariable>(solved);
for (TypeVariable var : unsolved) {
if (var.type() == null) {
unsolved_set.add(var);
} else {
solved_set.add(var);
}
}
solved = solved_set;
unsolved = unsolved_set;
}
}
| 15,498
| 27.595941
| 112
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/typing/integer/TypeVariable.java
|
package soot.jimple.toolkits.typing.integer;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2000 Etienne Gagnon. All rights reserved.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Represents a type variable. **/
class TypeVariable implements Comparable<Object> {
private static final Logger logger = LoggerFactory.getLogger(TypeVariable.class);
private static final boolean DEBUG = false;
private final int id;
private TypeVariable rep = this;
private int rank = 0;
private TypeNode approx;
private TypeNode inv_approx;
private TypeNode type;
private List<TypeVariable> parents = Collections.emptyList();
private List<TypeVariable> children = Collections.emptyList();
public TypeVariable(int id, TypeResolver resolver) {
this.id = id;
}
public TypeVariable(int id, TypeResolver resolver, TypeNode type) {
this.id = id;
this.type = type;
this.approx = type;
this.inv_approx = type;
}
@Override
public int hashCode() {
if (rep != this) {
return ecr().hashCode();
}
return id;
}
@Override
public boolean equals(Object obj) {
if (rep != this) {
return ecr().equals(obj);
}
if (obj == null) {
return false;
}
if (!obj.getClass().equals(this.getClass())) {
return false;
}
return ((TypeVariable) obj).ecr() == this;
}
@Override
public int compareTo(Object o) {
if (rep != this) {
return ecr().compareTo(o);
} else {
return id - ((TypeVariable) o).ecr().id;
}
}
private TypeVariable ecr() {
if (rep != this) {
rep = rep.ecr();
}
return rep;
}
public TypeVariable union(TypeVariable var) throws TypeException {
if (this.rep != this) {
return ecr().union(var);
}
TypeVariable y = var.ecr();
if (this == y) {
return this;
}
if (this.rank > y.rank) {
y.rep = this;
merge(y);
y.clear();
return this;
}
this.rep = y;
if (this.rank == y.rank) {
y.rank++;
}
y.merge(this);
clear();
return y;
}
private void clear() {
this.inv_approx = null;
this.approx = null;
this.type = null;
this.parents = null;
this.children = null;
}
private void merge(TypeVariable var) throws TypeException {
// Merge types
if (this.type == null) {
this.type = var.type;
} else if (var.type != null) {
error("Type Error(22): Attempt to merge two types.");
}
// Merge parents
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.parents);
set.addAll(var.parents);
set.remove(this);
this.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
// Merge children
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.children);
set.addAll(var.children);
set.remove(this);
this.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public int id() {
return (rep != this) ? ecr().id() : id;
}
public void addParent(TypeVariable variable) {
if (rep != this) {
ecr().addParent(variable);
return;
}
TypeVariable var = variable.ecr();
if (var == this) {
return;
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.parents);
set.add(var);
this.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(var.children);
set.add(this);
var.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public void removeParent(TypeVariable variable) {
if (rep != this) {
ecr().removeParent(variable);
return;
}
TypeVariable var = variable.ecr();
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.parents);
set.remove(var);
this.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(var.children);
set.remove(this);
var.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public void addChild(TypeVariable variable) {
if (rep != this) {
ecr().addChild(variable);
return;
}
TypeVariable var = variable.ecr();
if (var == this) {
return;
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.children);
set.add(var);
this.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(var.parents);
set.add(this);
var.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public void removeChild(TypeVariable variable) {
if (rep != this) {
ecr().removeChild(variable);
return;
}
TypeVariable var = variable.ecr();
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(this.children);
set.remove(var);
this.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
{
Set<TypeVariable> set = new TreeSet<TypeVariable>(var.parents);
set.remove(this);
var.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(set));
}
}
public List<TypeVariable> parents() {
return (rep != this) ? ecr().parents() : parents;
}
public List<TypeVariable> children() {
return (rep != this) ? ecr().children() : children;
}
public TypeNode approx() {
return (rep != this) ? ecr().approx() : approx;
}
public TypeNode inv_approx() {
return (rep != this) ? ecr().inv_approx() : inv_approx;
}
public TypeNode type() {
return (rep != this) ? ecr().type() : type;
}
static void error(String message) throws TypeException {
TypeException e = new TypeException(message);
if (DEBUG) {
logger.error(e.getMessage(), e);
}
throw e;
}
/**
* Computes approximative types. The work list must be initialized with all constant type variables.
*/
public static void computeApprox(TreeSet<TypeVariable> workList) throws TypeException {
while (workList.size() > 0) {
TypeVariable var = workList.first();
workList.remove(var);
var.fixApprox(workList);
}
}
public static void computeInvApprox(TreeSet<TypeVariable> workList) throws TypeException {
while (workList.size() > 0) {
TypeVariable var = workList.first();
workList.remove(var);
var.fixInvApprox(workList);
}
}
private void fixApprox(TreeSet<TypeVariable> workList) throws TypeException {
if (rep != this) {
ecr().fixApprox(workList);
return;
}
for (TypeVariable typeVariable : this.parents) {
TypeVariable parent = typeVariable.ecr();
if (parent.approx == null) {
parent.approx = this.approx;
workList.add(parent);
} else {
TypeNode type = parent.approx.lca_2(this.approx);
if (type != parent.approx) {
parent.approx = type;
workList.add(parent);
}
}
}
if (this.type != null) {
this.approx = this.type;
}
}
private void fixInvApprox(TreeSet<TypeVariable> workList) throws TypeException {
if (rep != this) {
ecr().fixInvApprox(workList);
return;
}
for (TypeVariable typeVariable : this.children) {
TypeVariable child = typeVariable.ecr();
if (child.inv_approx == null) {
child.inv_approx = this.inv_approx;
workList.add(child);
} else {
TypeNode type = child.inv_approx.gcd_2(this.inv_approx);
if (type != child.inv_approx) {
child.inv_approx = type;
workList.add(child);
}
}
}
if (this.type != null) {
this.inv_approx = this.type;
}
}
@Override
public String toString() {
if (rep != this) {
return ecr().toString();
}
StringBuilder s = new StringBuilder();
s.append("[id:").append(id);
if (type != null) {
s.append(",type:").append(type);
}
s.append(",approx:").append(approx);
s.append(",inv_approx:").append(inv_approx);
s.append(",[parents:");
{
boolean comma = false;
for (TypeVariable typeVariable : parents) {
if (comma) {
s.append(',');
} else {
comma = true;
}
s.append(typeVariable.id());
}
}
s.append("],[children:");
{
boolean comma = false;
for (TypeVariable typeVariable : children) {
if (comma) {
s.append(',');
} else {
comma = true;
}
s.append(typeVariable.id());
}
}
s.append("]]");
return s.toString();
}
public void fixParents() {
if (rep != this) {
ecr().fixParents();
return;
}
this.parents = Collections.unmodifiableList(new LinkedList<TypeVariable>(new TreeSet<TypeVariable>(parents)));
}
public void fixChildren() {
if (rep != this) {
ecr().fixChildren();
return;
}
this.children = Collections.unmodifiableList(new LinkedList<TypeVariable>(new TreeSet<TypeVariable>(children)));
}
}
| 10,125
| 23.757946
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/FieldRefValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Body;
import soot.ResolutionFailedException;
import soot.SootField;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.validation.BodyValidator;
import soot.validation.UnitValidationException;
import soot.validation.ValidationException;
public enum FieldRefValidator implements BodyValidator {
INSTANCE;
public static FieldRefValidator v() {
return INSTANCE;
}
/**
* Checks the consistency of field references.
*/
@Override
public void validate(Body body, List<ValidationException> exceptions) {
SootMethod method = body.getMethod();
if (method.isAbstract()) {
return;
}
for (Unit unit : body.getUnits().getNonPatchingChain()) {
Stmt s = (Stmt) unit;
if (!s.containsFieldRef()) {
continue;
}
FieldRef fr = s.getFieldRef();
if (fr instanceof StaticFieldRef) {
StaticFieldRef v = (StaticFieldRef) fr;
try {
SootField field = v.getField();
if (field == null) {
exceptions.add(new UnitValidationException(unit, body, "Resolved field is null: " + fr.toString()));
} else if (!field.isStatic() && !field.isPhantom()) {
exceptions
.add(new UnitValidationException(unit, body, "Trying to get a static field which is non-static: " + v));
}
} catch (ResolutionFailedException e) {
exceptions.add(new UnitValidationException(unit, body, "Trying to get a static field which is non-static: " + v));
}
} else if (fr instanceof InstanceFieldRef) {
InstanceFieldRef v = (InstanceFieldRef) fr;
try {
SootField field = v.getField();
if (field == null) {
exceptions.add(new UnitValidationException(unit, body, "Resolved field is null: " + fr.toString()));
} else if (field.isStatic() && !field.isPhantom()) {
exceptions.add(new UnitValidationException(unit, body, "Trying to get an instance field which is static: " + v));
}
} catch (ResolutionFailedException e) {
exceptions.add(new UnitValidationException(unit, body, "Trying to get an instance field which is static: " + v));
}
} else {
throw new AssertionError("unknown field ref: " + fr);
}
}
}
@Override
public boolean isBasicValidator() {
return true;
}
}
| 3,369
| 32.366337
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/IdentityStatementsValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Body;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.IdentityStmt;
import soot.jimple.ParameterRef;
import soot.jimple.ThisRef;
import soot.util.Chain;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
public enum IdentityStatementsValidator implements BodyValidator {
INSTANCE;
public static IdentityStatementsValidator v() {
return INSTANCE;
}
/**
* Checks the following invariants on this Jimple body:
* <ol>
* <li>this-references may only occur in instance methods
* <li>this-references may only occur as the first statement in a method, if they occur at all
* <li>param-references must precede all statements that are not themselves param-references or this-references, if they
* occur at all
* </ol>
*/
@Override
public void validate(Body body, List<ValidationException> exceptions) {
SootMethod method = body.getMethod();
if (method.isAbstract()) {
return;
}
Chain<Unit> units = body.getUnits().getNonPatchingChain();
boolean foundNonThisOrParamIdentityStatement = false;
boolean firstStatement = true;
for (Unit unit : units) {
if (unit instanceof IdentityStmt) {
IdentityStmt identityStmt = (IdentityStmt) unit;
if (identityStmt.getRightOp() instanceof ThisRef) {
if (method.isStatic()) {
exceptions.add(new ValidationException(identityStmt, "@this-assignment in a static method!"));
}
if (!firstStatement) {
exceptions.add(new ValidationException(identityStmt,
"@this-assignment statement should precede all other statements" + "\n method: " + method));
}
} else if (identityStmt.getRightOp() instanceof ParameterRef) {
if (foundNonThisOrParamIdentityStatement) {
exceptions.add(new ValidationException(identityStmt,
"@param-assignment statements should precede all non-identity statements" + "\n method: " + method));
}
} else {
// @caughtexception statement
foundNonThisOrParamIdentityStatement = true;
}
} else {
// non-identity statement
foundNonThisOrParamIdentityStatement = true;
}
firstStatement = false;
}
}
@Override
public boolean isBasicValidator() {
return true;
}
}
| 3,248
| 32.153061
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/IdentityValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Body;
import soot.IdentityUnit;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.ParameterRef;
import soot.jimple.ThisRef;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
/**
* This {@link BodyValidator} checks whether each {@link ParameterRef} and {@link ThisRef} is used exactly once.
*
* @author Marc Miltenberger
*/
public enum IdentityValidator implements BodyValidator {
INSTANCE;
public static IdentityValidator v() {
return INSTANCE;
}
@Override
public void validate(Body body, List<ValidationException> exceptions) {
final SootMethod method = body.getMethod();
final int paramCount = method.getParameterCount();
final boolean[] parameterRefs = new boolean[paramCount];
boolean hasThisLocal = false;
for (Unit u : body.getUnits()) {
if (u instanceof IdentityUnit) {
final IdentityUnit id = (IdentityUnit) u;
final Value rhs = id.getRightOp();
if (rhs instanceof ThisRef) {
hasThisLocal = true;
} else if (rhs instanceof ParameterRef) {
ParameterRef ref = (ParameterRef) rhs;
if (ref.getIndex() < 0 || ref.getIndex() >= paramCount) {
if (paramCount == 0) {
exceptions
.add(new ValidationException(id, "This method has no parameters, so no parameter reference is allowed"));
} else {
exceptions.add(new ValidationException(id,
String.format("Parameter reference index must be between 0 and %d (inclusive)", paramCount - 1)));
}
return;
}
if (parameterRefs[ref.getIndex()]) {
exceptions.add(
new ValidationException(id, String.format("Only one local for parameter %d is allowed", ref.getIndex())));
}
parameterRefs[ref.getIndex()] = true;
}
}
}
if (!method.isStatic() && !hasThisLocal) {
exceptions.add(new ValidationException(body,
String.format("The method %s is not static, but does not have a this local", method.getSignature())));
}
for (int i = 0; i < paramCount; i++) {
if (!parameterRefs[i]) {
exceptions
.add(new ValidationException(body, String.format("There is no parameter local for parameter number %d", i)));
}
}
}
@Override
public boolean isBasicValidator() {
return true;
}
}
| 3,325
| 31.930693
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/InvokeArgumentValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Body;
import soot.SootMethod;
import soot.Unit;
import soot.baf.BafBody;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
/**
* A basic {@link BodyValidator} that checks whether the length of the invoke statement's argument list matches the length of
* the target method's parameter type list.
*
* @author Steven Arzt
*/
public enum InvokeArgumentValidator implements BodyValidator {
INSTANCE;
public static InvokeArgumentValidator v() {
return INSTANCE;
}
@Override
public void validate(Body body, List<ValidationException> exceptions) {
if (body instanceof BafBody) {
// NOTE: The AbstractInvokeInst used for invoke expression in the BafBody
// does not contain the method arguments, it instead expects them to be
// available on the stack when the invoke expression is executed. Thus,
// there is no way to check the condition but we must avoid crashing.
} else {
for (Unit unit : body.getUnits().getNonPatchingChain()) {
Stmt s = (Stmt) unit;
if (s.containsInvokeExpr()) {
InvokeExpr iinvExpr = s.getInvokeExpr();
SootMethod callee = iinvExpr.getMethod();
if (callee != null && iinvExpr.getArgCount() != callee.getParameterCount()) {
exceptions.add(new ValidationException(s, "Invalid number of arguments"));
}
}
}
}
}
@Override
public boolean isBasicValidator() {
return true;
}
}
| 2,421
| 31.293333
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/InvokeValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Unit;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.VirtualInvokeExpr;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
public enum InvokeValidator implements BodyValidator {
INSTANCE;
public static InvokeValidator v() {
return INSTANCE;
}
@Override
public void validate(Body body, List<ValidationException> exceptions) {
final SootClass objClass = Scene.v().getObjectType().getSootClass();
for (Unit unit : body.getUnits()) {
if (unit instanceof Stmt) {
final Stmt statement = (Stmt) unit;
if (statement.containsInvokeExpr()) {
final InvokeExpr ie = statement.getInvokeExpr();
final SootMethodRef methodRef = ie.getMethodRef();
try {
final SootMethod method = methodRef.resolve();
if (!method.isPhantom()) {
if (method.isStaticInitializer()) {
exceptions.add(new ValidationException(unit, "Calling <clinit> methods is not allowed."));
} else if (method.isStatic()) {
if (!(ie instanceof StaticInvokeExpr)) {
exceptions.add(new ValidationException(unit, "Should use staticinvoke for static methods."));
}
} else {
final SootClass clazzDeclaring = method.getDeclaringClass();
if (clazzDeclaring.isInterface()) {
if (!(ie instanceof InterfaceInvokeExpr)) {
// There are cases where the Java bytecode verifier allows an
// invokevirtual or invokespecial to target an interface method.
if (!(ie instanceof VirtualInvokeExpr || ie instanceof SpecialInvokeExpr)) {
exceptions.add(new ValidationException(unit,
"Should use interface/virtual/specialinvoke for interface methods."));
}
}
} else if (method.isPrivate() || method.isConstructor()) {
if (!(ie instanceof SpecialInvokeExpr)) {
String type = method.isPrivate() ? "private methods" : "constructors";
exceptions.add(new ValidationException(unit, "Should use specialinvoke for " + type + "."));
}
} else if (methodRef.getDeclaringClass().isInterface() && objClass.equals(clazzDeclaring)) {
// invokeinterface can be used to invoke the base Object methods
if (!(ie instanceof InterfaceInvokeExpr || ie instanceof VirtualInvokeExpr
|| ie instanceof SpecialInvokeExpr)) {
exceptions.add(new ValidationException(unit,
"Should use interface/virtual/specialinvoke for java.lang.Object methods."));
}
} else {
// NOTE: beyond constructors, there's not a rule to separate
// super.X from this.X because there exist scenarios where it
// is valid to use the exact same references with either a
// specialinvoke or a virtualinvoke. Consider classes A and B
// where B extends A. Both classes define a method "void m()".
// It is legal for a method in B to have either of the these:
// - virtualinvoke this.<A: void m()>() //i.e. ((A)this).m()
// - specialinvoke this.<A: void m()>() //i.e. super.m()
// Both are valid bytecode (although their behavior differs).
if (!(ie instanceof VirtualInvokeExpr || ie instanceof SpecialInvokeExpr)) {
exceptions.add(new ValidationException(unit, "Should use virtualinvoke or specialinvoke."));
}
}
}
}
} catch (Exception e) {
// Error on resolving
}
}
}
}
}
@Override
public boolean isBasicValidator() {
return false;
}
}
| 5,146
| 42.252101
| 112
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/JimpleTrapValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import soot.Body;
import soot.Trap;
import soot.Unit;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.IdentityStmt;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
/**
* This validator checks whether the jimple traps are correct. It does not perform the same checks as
* {@link soot.validation.TrapsValidator}
*
* @see JimpleTrapValidator#validate(Body, List)
* @author Marc Miltenberger
*/
public enum JimpleTrapValidator implements BodyValidator {
INSTANCE;
public static JimpleTrapValidator v() {
return INSTANCE;
}
/**
* Checks whether all Caught-Exception-References are associated to traps.
*/
@Override
public void validate(Body body, List<ValidationException> exceptions) {
Set<Unit> caughtUnits = new HashSet<Unit>();
for (Trap trap : body.getTraps()) {
caughtUnits.add(trap.getHandlerUnit());
if (!(trap.getHandlerUnit() instanceof IdentityStmt)) {
exceptions.add(new ValidationException(trap, "Trap handler does not start with caught " + "exception reference"));
} else {
IdentityStmt is = (IdentityStmt) trap.getHandlerUnit();
if (!(is.getRightOp() instanceof CaughtExceptionRef)) {
exceptions.add(new ValidationException(trap, "Trap handler does not start with caught " + "exception reference"));
}
}
}
for (Unit u : body.getUnits()) {
if (u instanceof IdentityStmt) {
IdentityStmt id = (IdentityStmt) u;
if (id.getRightOp() instanceof CaughtExceptionRef) {
if (!caughtUnits.contains(id)) {
exceptions.add(new ValidationException(id, "Could not find a corresponding trap using this statement as handler",
"Body of method " + body.getMethod().getSignature() + " contains a caught exception reference,"
+ "but not a corresponding trap using this statement as handler"));
}
}
}
}
}
@Override
public boolean isBasicValidator() {
return true;
}
}
| 2,946
| 32.488636
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/MethodValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Body;
import soot.SootMethod;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
public enum MethodValidator implements BodyValidator {
INSTANCE;
public static MethodValidator v() {
return INSTANCE;
}
/**
* Checks the following invariants on this Jimple body:
* <ol>
* <li>static initializer should have 'static' modifier
* </ol>
*/
@Override
public void validate(Body body, List<ValidationException> exceptions) {
SootMethod method = body.getMethod();
if (method.isAbstract()) {
return;
}
if (method.isStaticInitializer() && !method.isStatic()) {
exceptions.add(new ValidationException(method,
SootMethod.staticInitializerName + " should be static! Static initializer without 'static'('0x8') modifier"
+ " will cause problem when running on android platform: "
+ "\"<clinit> is not flagged correctly wrt/ static\"!"));
}
}
@Override
public boolean isBasicValidator() {
return true;
}
}
| 1,922
| 29.046875
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/NewValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import soot.Body;
import soot.Local;
import soot.RefType;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NewExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.Stmt;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
/**
* A relatively simple validator. It tries to check whether after each new-expression-statement there is a corresponding call
* to the <init> method before a use or the end of the method.
*
* @author Marc Miltenberger
* @author Steven Arzt
*/
public enum NewValidator implements BodyValidator {
INSTANCE;
private static final String errorMsg
= "There is a path from '%s' to the usage '%s' where <init> does not get called in between.";
public static boolean MUST_CALL_CONSTRUCTOR_BEFORE_RETURN = false;
public static NewValidator v() {
return INSTANCE;
}
/**
* Checks whether after each new-instruction a constructor call follows.
*/
@Override
public void validate(Body body, List<ValidationException> exceptions) {
UnitGraph g = new BriefUnitGraph(body);
for (Unit u : body.getUnits()) {
if (u instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) u;
// First seek for a JNewExpr.
if (assign.getRightOp() instanceof NewExpr) {
if (!(assign.getLeftOp().getType() instanceof RefType)) {
exceptions.add(new ValidationException(u, "A new-expression must be used on reference type locals",
String.format("Body of method %s contains a new-expression, which is assigned to a non-reference local",
body.getMethod().getSignature())));
return;
}
// We search for a JSpecialInvokeExpr on the local.
checkForInitializerOnPath(g, assign, exceptions);
}
}
}
}
/**
* <p>
* Checks whether all paths from start to the end of the method have a call to the <init> method in between.
* </p>
* <code>
* $r0 = new X;<br>
* ...<br>
* specialinvoke $r0.<X: void <init>()>; //validator checks whether this statement is missing
* </code>
* <p>
* Regarding <i>aliasingLocals</i>:<br>
* The first local in the set is always the local on the LHS of the new-expression-assignment (called: original local; in
* the example <code>$r0</code>).
* </p>
*
* @param g
* the unit graph of the method
* @param exception
* the list of all collected exceptions
* @return true if a call to a <init>-Method has been found on this way.
*/
private boolean checkForInitializerOnPath(UnitGraph g, AssignStmt newStmt, List<ValidationException> exception) {
List<Unit> workList = new ArrayList<Unit>();
Set<Unit> doneSet = new HashSet<Unit>();
workList.add(newStmt);
Set<Local> aliasingLocals = new HashSet<Local>();
aliasingLocals.add((Local) newStmt.getLeftOp());
while (!workList.isEmpty()) {
Stmt curStmt = (Stmt) workList.remove(0);
if (!doneSet.add(curStmt)) {
continue;
}
if (!newStmt.equals(curStmt)) {
if (curStmt.containsInvokeExpr()) {
InvokeExpr expr = curStmt.getInvokeExpr();
if (expr.getMethod().isConstructor()) {
if (!(expr instanceof SpecialInvokeExpr)) {
exception.add(new ValidationException(curStmt, "<init> method calls may only be used with specialinvoke."));
// At least we found an initializer, so we return true...
return true;
}
if (!(curStmt instanceof InvokeStmt)) {
exception.add(new ValidationException(curStmt, "<init> methods may only be called with invoke statements."));
// At least we found an initializer, so we return true...
return true;
}
SpecialInvokeExpr invoke = (SpecialInvokeExpr) expr;
if (aliasingLocals.contains(invoke.getBase())) {
// We are happy now, continue the loop and check other paths
continue;
}
}
}
// We are still in the loop, so this was not the constructor call we
// were looking for
boolean creatingAlias = false;
if (curStmt instanceof AssignStmt) {
AssignStmt assignCheck = (AssignStmt) curStmt;
if (aliasingLocals.contains(assignCheck.getRightOp())) {
if (assignCheck.getLeftOp() instanceof Local) {
// A new alias is created.
aliasingLocals.add((Local) assignCheck.getLeftOp());
creatingAlias = true;
}
}
Local originalLocal = aliasingLocals.iterator().next();
if (originalLocal.equals(assignCheck.getLeftOp())) {
// In case of dead assignments:
// Handles cases like
// $r0 = new x;
// $r0 = null;
// But not cases like
// $r0 = new x;
// $r1 = $r0;
// $r1 = null;
// Because we check for the original local
continue;
} else {
// Since the local on the left hand side gets overwritten
// even if it was aliasing with our original local,
// now it does not any more...
aliasingLocals.remove(assignCheck.getLeftOp());
}
}
if (!creatingAlias) {
for (ValueBox box : curStmt.getUseBoxes()) {
Value used = box.getValue();
if (aliasingLocals.contains(used)) {
// The current unit uses one of the aliasing locals, but
// there was no initializer in between.
// However, when creating such an alias, the use is okay.
exception.add(new ValidationException(newStmt, String.format(errorMsg, newStmt, curStmt)));
return false;
}
}
}
}
// Enqueue the successors
List<Unit> successors = g.getSuccsOf(curStmt);
if (successors.isEmpty() && MUST_CALL_CONSTRUCTOR_BEFORE_RETURN) {
// This means that we are e.g. at the end of the method
// There was no <init> call on our way...
exception.add(new ValidationException(newStmt, String.format(errorMsg, newStmt, curStmt)));
return false;
}
workList.addAll(successors);
}
return true;
}
@Override
public boolean isBasicValidator() {
return false;
}
}
| 7,594
| 34.490654
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/ReturnStatementsValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Body;
import soot.SootMethod;
import soot.Unit;
import soot.VoidType;
import soot.baf.GotoInst;
import soot.baf.ReturnInst;
import soot.baf.ReturnVoidInst;
import soot.baf.ThrowInst;
import soot.jimple.GotoStmt;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ThrowStmt;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
/**
* Checks that this Body actually contains a throw or return statement, and that the return statement is of the appropriate
* type (i.e. void/non-void).
*/
public enum ReturnStatementsValidator implements BodyValidator {
INSTANCE;
public static ReturnStatementsValidator v() {
return INSTANCE;
}
@Override
public void validate(Body body, List<ValidationException> exceptions) {
final SootMethod method = body.getMethod();
// Checks that this Body actually contains a throw or return statement, and
// that the return statement is of the appropriate type (i.e. void/non-void)
for (Unit u : body.getUnits()) {
if (u instanceof ThrowStmt || u instanceof ThrowInst) {
return;
} else if (u instanceof ReturnStmt || u instanceof ReturnInst) {
if (!(method.getReturnType() instanceof VoidType)) {
return;
}
} else if (u instanceof ReturnVoidStmt || u instanceof ReturnVoidInst) {
if (method.getReturnType() instanceof VoidType) {
return;
}
}
}
// A method can have an infinite loop and no return statement:
// public static void main(String[] args) {
// int i = 0; while (true) {i += 1;}
// }
//
// Only check that the execution cannot fall off the code.
Unit last = body.getUnits().getLast();
if (last instanceof GotoStmt || last instanceof GotoInst || last instanceof ThrowStmt || last instanceof ThrowInst) {
return;
}
exceptions.add(new ValidationException(method,
"The method does not contain a return statement, or the return statement is not of the appropriate type",
"Body of method " + method.getSignature()
+ " does not contain a return statement, or the return statement is not of the appropriate type"));
}
@Override
public boolean isBasicValidator() {
return true;
}
}
| 3,169
| 32.368421
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/validation/TypesValidator.java
|
package soot.jimple.validation;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Body;
import soot.Local;
import soot.SootMethod;
import soot.Type;
import soot.validation.BodyValidator;
import soot.validation.ValidationException;
/**
* Checks whether the types used for locals, method parameters, and method return values are allowed in final Jimple code.
* This reports an error if a method uses e.g., null_type.
*/
public enum TypesValidator implements BodyValidator {
INSTANCE;
public static TypesValidator v() {
return INSTANCE;
}
@Override
public void validate(Body body, List<ValidationException> exceptions) {
SootMethod method = body.getMethod();
if (method != null) {
if (!method.getReturnType().isAllowedInFinalCode()) {
exceptions.add(new ValidationException(method, "Return type not allowed in final code: " + method.getReturnType(),
"return type not allowed in final code:" + method.getReturnType() + "\n method: " + method));
}
for (Type t : method.getParameterTypes()) {
if (!t.isAllowedInFinalCode()) {
exceptions.add(new ValidationException(method, "Parameter type not allowed in final code: " + t,
"parameter type not allowed in final code:" + t + "\n method: " + method));
}
}
}
for (Local l : body.getLocals()) {
Type t = l.getType();
if (!t.isAllowedInFinalCode()) {
exceptions.add(new ValidationException(l, "Local type not allowed in final code: " + t,
"(" + method + ") local type not allowed in final code: " + t + " local: " + l));
}
}
}
@Override
public boolean isBasicValidator() {
return true;
}
}
| 2,509
| 32.466667
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/options/OptionsBase.java
|
package soot.options;
/*-
* #%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.Deque;
import java.util.LinkedList;
import java.util.StringTokenizer;
import soot.Pack;
import soot.PackManager;
import soot.PhaseOptions;
import soot.Transform;
import soot.plugins.internal.PluginLoader;
/**
* Soot command-line options parser base class.
*
* @author Ondrej Lhotak
*/
abstract class OptionsBase {
private final Deque<String> options = new LinkedList<>();
protected LinkedList<String> classes = new LinkedList<String>();
private String pad(int initial, String opts, int tab, String desc) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < initial; i++) {
b.append(' ');
}
b.append(opts);
int i;
if (tab <= opts.length()) {
b.append('\n');
i = 0;
} else {
i = opts.length() + initial;
}
for (; i <= tab; i++) {
b.append(' ');
}
for (StringTokenizer t = new StringTokenizer(desc); t.hasMoreTokens();) {
String s = t.nextToken();
if (i + s.length() > 78) {
b.append('\n');
i = 0;
for (; i <= tab; i++) {
b.append(' ');
}
}
b.append(s);
b.append(' ');
i += s.length() + 1;
}
b.append('\n');
return b.toString();
}
protected String padOpt(String opts, String desc) {
return pad(1, opts, 30, desc);
}
protected String padVal(String vals, String desc) {
return pad(4, vals, 32, desc);
}
protected String getPhaseUsage() {
StringBuilder b = new StringBuilder();
b.append("\nPhases and phase options:\n");
for (Pack p : PackManager.v().allPacks()) {
b.append(padOpt(p.getPhaseName(), p.getDeclaredOptions()));
for (Transform ph : p) {
b.append(padVal(ph.getPhaseName(), ph.getDeclaredOptions()));
}
}
return b.toString();
}
protected void pushOption(String option) {
options.push(option);
}
protected boolean hasMoreOptions() {
return !options.isEmpty();
}
protected String nextOption() {
return options.removeFirst();
}
public LinkedList<String> classes() {
return classes;
}
public boolean setPhaseOption(String phase, String option) {
return PhaseOptions.v().processPhaseOptions(phase, option);
}
/**
* Handles the value of a plugin parameter.
*
* @param file
* the plugin parameter value.
* @return {@code true} on success.
*/
protected boolean loadPluginConfiguration(String file) {
return PluginLoader.load(file);
}
}
| 3,311
| 24.674419
| 77
|
java
|
soot
|
soot-master/src/main/java/soot/plugins/SootPhasePlugin.java
|
package soot.plugins;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2013 Bernhard J. Berger
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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.Transformer;
import soot.plugins.model.PhasePluginDescription;
/**
* An interface every phase plugin has to implement. The plugin has to support basic functionality, such as creating the
* transformer and support a list of possible options. The first method that is called after object creation is
* {@code setDescription} then the list of possible parameters is called and the last step is the call to
* {@code getTransformer}.
*
* @author Bernhard J. Berger
*/
public interface SootPhasePlugin {
/**
* Default option for enabling a plugin.
*/
public final String ENABLED_BY_DEFAULT = "enabled:true";
/**
* @return a list of phase options.
*/
public abstract String[] getDeclaredOptions();
/**
* Returns a list of default values for initializing the parameters. Each entry in the list is of kind
* "<parameter-name>:<default-value>". Please note, that you have to add the {@code ENABLED_BY_DEFAULT} option if you want
* the plugin to be enabled.
*
* @return a list of default values.
*/
public abstract String[] getDefaultOptions();
/**
* Creates a new transformer instance (either SceneTransformer or BodyTransformer). The method will be called just once.
*
* @return a new transformer instance.
*/
public abstract Transformer getTransformer();
public abstract void setDescription(final PhasePluginDescription pluginDescription);
}
| 2,244
| 33.538462
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/plugins/internal/ClassLoadingStrategy.java
|
package soot.plugins.internal;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2018 Bernhard J. Berger
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy 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 different class loading strategies.
*
* @author Bernhard J. Berger
*/
public interface ClassLoadingStrategy {
/**
* Creates an instance of the given class name.
*
* @param className
* Name of the class.
* @return The newly created instance.
*/
public Object create(final String className) throws ClassNotFoundException, InstantiationException;
}
| 1,237
| 29.195122
| 101
|
java
|
soot
|
soot-master/src/main/java/soot/plugins/internal/PluginLoader.java
|
package soot.plugins.internal;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2013 Bernhard J. Berger
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of 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.security.InvalidParameterException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.PackManager;
import soot.Transform;
import soot.plugins.SootPhasePlugin;
import soot.plugins.model.PhasePluginDescription;
import soot.plugins.model.PluginDescription;
import soot.plugins.model.Plugins;
/**
* Class for loading xml-based plugin configuration files.
*
* @author Bernhard J. Berger
*/
public class PluginLoader {
private static final Logger logger = LoggerFactory.getLogger(PluginLoader.class);
private static ClassLoadingStrategy loadStrategy = new ReflectionClassLoadingStrategy();
/**
* Each phase has to support the enabled option. We will add it if necessary.
*
* @param declaredOptions
* Options declared by the plugin.
* @return option list definitly containing enabled.
*/
private static String[] appendEnabled(final String[] options) {
for (String option : options) {
if ("enabled".equals(option)) {
return options;
}
}
String[] result = new String[options.length + 1];
result[0] = "enabled";
System.arraycopy(options, 0, result, 1, options.length);
return result;
}
/**
* Creates a space separated list from {@code declaredOptions}.
*
* @param options
* the list to transform.
* @return a string containing all options separated by a space.
*/
private static String concat(final String[] options) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String option : options) {
if (first) {
first = false;
} else {
sb.append(' ');
}
sb.append(option);
}
return sb.toString();
}
/**
* Splits a phase name and returns the pack name.
*
* @param phaseName
* Name of the phase.
* @return the name of the pack.
*/
private static String getPackName(final String phaseName) {
if (!phaseName.contains(".")) {
throw new RuntimeException("Name of phase '" + phaseName + "'does not contain a dot.");
}
return phaseName.substring(0, phaseName.indexOf('.'));
}
/**
* Loads the phase plugin and adds it to PackManager.
*
* @param pluginDescription
* the plugin description instance read from configuration file.
*/
private static void handlePhasePlugin(final PhasePluginDescription pluginDescription) {
try {
final Object instance = PluginLoader.loadStrategy.create(pluginDescription.getClassName());
if (!(instance instanceof SootPhasePlugin)) {
throw new RuntimeException(
"The plugin class '" + pluginDescription.getClassName() + "' does not implement SootPhasePlugin.");
}
final SootPhasePlugin phasePlugin = (SootPhasePlugin) instance;
phasePlugin.setDescription(pluginDescription);
final String packName = getPackName(pluginDescription.getPhaseName());
Transform transform = new Transform(pluginDescription.getPhaseName(), phasePlugin.getTransformer());
transform.setDeclaredOptions(concat(appendEnabled(phasePlugin.getDeclaredOptions())));
transform.setDefaultOptions(concat(phasePlugin.getDefaultOptions()));
PackManager.v().getPack(packName).add(transform);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Failed to load plugin class for " + pluginDescription + ".", e);
} catch (InstantiationException e) {
throw new RuntimeException("Failed to instanciate plugin class for " + pluginDescription + ".", e);
}
}
/**
* Loads the plugin configuration file {@code file} and registers the plugins.
*
* @param file
* the plugin configuration file.
* @return {@code true} on success.
*/
public static boolean load(final String file) {
final File configFile = new File(file);
if (!configFile.exists()) {
System.err.println("The configuration file '" + configFile + "' does not exist.");
return false;
}
if (!configFile.canRead()) {
System.err.println("Cannot read the configuration file '" + configFile + "'.");
return false;
}
try {
JAXBContext context = JAXBContext.newInstance(Plugins.class, PluginDescription.class, PhasePluginDescription.class);
Object root = context.createUnmarshaller().unmarshal(configFile);
if (!(root instanceof Plugins)) {
System.err.println("Expected a root node of type Plugins got " + root.getClass());
return false;
}
loadPlugins((Plugins) root);
} catch (RuntimeException e) {
System.err.println("Failed to load plugin correctly.");
logger.error(e.getMessage(), e);
return false;
} catch (JAXBException e) {
System.err.println("An error occured while loading plugin configuration '" + file + "'.");
logger.error(e.getMessage(), e);
return false;
}
return true;
}
/**
* Load all plugins. Can be called by a custom main function.
*
* @param plugins
* the plugins to load.
*
* @throws RuntimeException
* if an error occurs during loading.
*/
public static void loadPlugins(final Plugins plugins) throws RuntimeException {
for (PluginDescription plugin : plugins.getPluginDescriptions()) {
if (plugin instanceof PhasePluginDescription) {
handlePhasePlugin((PhasePluginDescription) plugin);
} else {
logger.debug("[Warning] Unhandled plugin of type '" + plugin.getClass() + "'");
}
}
}
/**
* Changes the class loading strategy used by Soot.
*
* @param strategy
* The new class loading strategy to use.
*/
public static void setClassLoadingStrategy(final ClassLoadingStrategy strategy) {
if (strategy == null) {
throw new InvalidParameterException("Class loading strategy is not allowed to be null.");
}
PluginLoader.loadStrategy = strategy;
}
private PluginLoader() {
}
}
| 6,906
| 30.395455
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/plugins/internal/ReflectionClassLoadingStrategy.java
|
package soot.plugins.internal;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2018 Bernhard J. Berger
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy 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 loading strategy that uses traditional reflection for instantiation.
*
* @author Bernhard J. Berger
*/
public class ReflectionClassLoadingStrategy implements ClassLoadingStrategy {
@Override
public Object create(final String className) throws ClassNotFoundException, InstantiationException {
final Class<?> clazz = Class.forName(className);
try {
return clazz.newInstance();
} catch (final IllegalAccessException e) {
throw new InstantiationException("Failed to create instance of " + className + " due to access restrictions.");
}
}
}
| 1,423
| 32.116279
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/plugins/model/PhasePluginDescription.java
|
package soot.plugins.model;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2013 Bernhard J. Berger
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import soot.plugins.SootPhasePlugin;
/**
* A phase plugin adds a new analysis to a pack. Therefore, it needs a phase name and a plugin class name.
*
* @author Bernhard J. Berger
*/
@XmlRootElement(namespace = "http://github.com/Sable/soot/plugins", name = "phase-plugin")
public class PhasePluginDescription extends PluginDescription {
/**
* Name of phase. Make sure it consists of '<pack>.<phase>'.
*/
private String phaseName;
/**
* Name of the plugin class that has to implement {@link SootPhasePlugin}.
*/
private String className;
@XmlAttribute(name = "class", required = true)
public String getClassName() {
return className;
}
public void setClassName(final String name) {
this.className = name;
}
@XmlAttribute(name = "phase", required = true)
public String getPhaseName() {
return phaseName;
}
public void setPhaseName(final String name) {
phaseName = name;
}
@Override
public String toString() {
return "<PhasePluginDescription name=" + getPhaseName() + " class= " + getClassName() + ">";
}
}
| 2,022
| 27.9
| 106
|
java
|
soot
|
soot-master/src/main/java/soot/plugins/model/PluginDescription.java
|
package soot.plugins.model;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2013 Bernhard J. Berger
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Base class of all available plugin description.
*
* @author Bernhard J. Berger.
*/
public abstract class PluginDescription {
}
| 970
| 29.34375
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/plugins/model/Plugins.java
|
package soot.plugins.model;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2013 Bernhard J. Berger
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Java representation of the xml root element. It's a simple holder for plugins.
*
* @author Bernhard J. Berger
*/
@XmlRootElement(namespace = "http://github.com/Sable/soot/plugins", name = "soot-plugins")
public class Plugins {
/**
* List of all plugin entries.
*/
private final List<PluginDescription> pluginDescriptions = new LinkedList<PluginDescription>();
@XmlElementRefs({ @XmlElementRef(name = "phase-plugin", type = PhasePluginDescription.class) })
public List<PluginDescription> getPluginDescriptions() {
return pluginDescriptions;
}
}
| 1,608
| 31.836735
| 97
|
java
|
soot
|
soot-master/src/main/java/soot/rtlib/tamiflex/DefaultHandler.java
|
package soot.rtlib.tamiflex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class DefaultHandler implements IUnexpectedReflectiveCallHandler {
@Override
public void methodInvoke(Object receiver, Method m) {
System.err.println("Unexpected reflective call to method " + m);
}
@Override
public void constructorNewInstance(Constructor<?> c) {
System.err.println("Unexpected reflective instantiation via constructor " + c);
}
@Override
public void classNewInstance(Class<?> c) {
System.err.println("Unexpected reflective instantiation via Class.newInstance on class " + c);
}
@Override
public void classForName(String typeName) {
System.err.println("Unexpected reflective loading of class " + typeName);
}
@Override
public void fieldSet(Object receiver, Field f) {
System.err.println("Unexpected reflective field set: " + f);
}
@Override
public void fieldGet(Object receiver, Field f) {
System.err.println("Unexpected reflective field get: " + f);
}
}
| 1,896
| 30.098361
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/rtlib/tamiflex/IUnexpectedReflectiveCallHandler.java
|
package soot.rtlib.tamiflex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public interface IUnexpectedReflectiveCallHandler {
public void classNewInstance(Class<?> c);
public void classForName(String typeName);
public void constructorNewInstance(Constructor<?> c);
public void methodInvoke(Object receiver, Method m);
public void fieldSet(Object receiver, Field f);
public void fieldGet(Object receiver, Field f);
}
| 1,313
| 28.863636
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/rtlib/tamiflex/OpaquePredicate.java
|
package soot.rtlib.tamiflex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class OpaquePredicate {
public static boolean getFalse() {
return false;
}
}
| 942
| 28.46875
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/rtlib/tamiflex/ReflectiveCalls.java
|
package soot.rtlib.tamiflex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
public class ReflectiveCalls {
private final static Set<String> classForName = new HashSet<String>();
private final static Set<String> classNewInstance = new HashSet<String>();
private final static Set<String> constructorNewInstance = new HashSet<String>();
private final static Set<String> methodInvoke = new HashSet<String>();
private final static Set<String> fieldSet = new HashSet<String>();
private final static Set<String> fieldGet = new HashSet<String>();
static {
// soot will add initialization code here
}
public static void knownClassForName(int contextId, String className) {
if (!classForName.contains(contextId + className)) {
UnexpectedReflectiveCall.classForName(className);
}
}
public static void knownClassNewInstance(int contextId, Class<?> c) {
if (!classNewInstance.contains(contextId + c.getName())) {
UnexpectedReflectiveCall.classNewInstance(c);
}
}
public static void knownConstructorNewInstance(int contextId, Constructor<?> c) {
if (!constructorNewInstance.contains(contextId + SootSig.sootSignature(c))) {
UnexpectedReflectiveCall.constructorNewInstance(c);
}
}
public static void knownMethodInvoke(int contextId, Object o, Method m) {
if (!methodInvoke.contains(contextId + SootSig.sootSignature(o, m))) {
UnexpectedReflectiveCall.methodInvoke(o, m);
}
}
public static void knownFieldSet(int contextId, Object o, Field f) {
if (!fieldSet.contains(contextId + SootSig.sootSignature(f))) {
UnexpectedReflectiveCall.fieldSet(o, f);
}
}
public static void knownFieldGet(int contextId, Object o, Field f) {
if (!fieldGet.contains(contextId + SootSig.sootSignature(f))) {
UnexpectedReflectiveCall.fieldGet(o, f);
}
}
}
| 2,778
| 33.7375
| 83
|
java
|
soot
|
soot-master/src/main/java/soot/rtlib/tamiflex/SilentHandler.java
|
package soot.rtlib.tamiflex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class SilentHandler implements IUnexpectedReflectiveCallHandler {
public void methodInvoke(Object receiver, Method m) {
}
public void constructorNewInstance(Constructor<?> c) {
}
public void classNewInstance(Class<?> c) {
}
public void classForName(String typeName) {
}
public void fieldSet(Object receiver, Field f) {
}
public void fieldGet(Object receiver, Field f) {
}
}
| 1,362
| 27.395833
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/rtlib/tamiflex/SootSig.java
|
package soot.rtlib.tamiflex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SootSig {
private static final Logger logger = LoggerFactory.getLogger(SootSig.class);
// TODO should be a map with soft keys, actually
private static Map<Constructor<?>, String> constrCache = new ConcurrentHashMap<Constructor<?>, String>();
// TODO should be a map with soft keys, actually
private static Map<Method, String> methodCache = new ConcurrentHashMap<Method, String>();
public static String sootSignature(Constructor<?> c) {
String res = constrCache.get(c);
if (res == null) {
String[] paramTypes = classesToTypeNames(c.getParameterTypes());
res = sootSignature(c.getDeclaringClass().getName(), "void", "<init>", paramTypes);
constrCache.put(c, res);
}
return res;
}
public static String sootSignature(Object receiver, Method m) {
Class<?> receiverClass = Modifier.isStatic(m.getModifiers()) ? m.getDeclaringClass() : receiver.getClass();
try {
// resolve virtual call
Method resolved = null;
Class<?> c = receiverClass;
do {
try {
resolved = c.getDeclaredMethod(m.getName(), m.getParameterTypes());
} catch (NoSuchMethodException e) {
c = c.getSuperclass();
}
} while (resolved == null && c != null);
if (resolved == null) {
Error error = new Error("Method not found : " + m + " in class " + receiverClass + " and super classes.");
logger.error(error.getMessage(), error);
}
String res = methodCache.get(resolved);
if (res == null) {
String[] paramTypes = classesToTypeNames(resolved.getParameterTypes());
res = sootSignature(resolved.getDeclaringClass().getName(), getTypeName(resolved.getReturnType()),
resolved.getName(), paramTypes);
methodCache.put(resolved, res);
}
return res;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String[] classesToTypeNames(Class<?>[] params) {
String[] paramTypes = new String[params.length];
int i = 0;
for (Class<?> type : params) {
paramTypes[i] = getTypeName(type);
i++;
}
return paramTypes;
}
private static String getTypeName(Class<?> type) {
// copied from java.lang.reflect.Field.getTypeName(Class)
if (type.isArray()) {
try {
Class<?> cl = type;
int dimensions = 0;
while (cl.isArray()) {
dimensions++;
cl = cl.getComponentType();
}
StringBuilder sb = new StringBuilder();
sb.append(cl.getName());
for (int i = 0; i < dimensions; i++) {
sb.append("[]");
}
return sb.toString();
} catch (Throwable e) {
/* FALLTHRU */ }
}
return type.getName();
}
private static String sootSignature(String declaringClass, String returnType, String name, String... paramTypes) {
StringBuilder b = new StringBuilder();
b.append('<');
b.append(declaringClass);
b.append(": ");
b.append(returnType);
b.append(' ');
b.append(name);
b.append('(');
int i = 0;
for (String type : paramTypes) {
i++;
b.append(type);
if (i < paramTypes.length) {
b.append(',');
}
}
b.append(")>");
return b.toString();
}
public static String sootSignature(Field f) {
StringBuilder b = new StringBuilder();
b.append('<');
b.append(getTypeName(f.getDeclaringClass()));
b.append(": ");
b.append(getTypeName(f.getType()));
b.append(' ');
b.append(f.getName());
b.append('>');
return b.toString();
}
}
| 4,714
| 30.644295
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/rtlib/tamiflex/UnexpectedReflectiveCall.java
|
package soot.rtlib.tamiflex;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class UnexpectedReflectiveCall {
private final static IUnexpectedReflectiveCallHandler handler;
static {
String listenerClassName = System.getProperty("BOOSTER_LISTENER", "soot.rtlib.tamiflex.DefaultHandler");
try {
handler = (IUnexpectedReflectiveCallHandler) Class.forName(listenerClassName).newInstance();
} catch (Exception e) {
throw new Error("Error instantiating listener for Booster.", e);
}
}
// delegate methods
public static void classNewInstance(Class<?> c) {
handler.classNewInstance(c);
}
public static void classForName(String typeName) {
handler.classForName(typeName);
}
public static void constructorNewInstance(Constructor<?> c) {
handler.constructorNewInstance(c);
}
public static void methodInvoke(Object receiver, Method m) {
handler.methodInvoke(receiver, m);
}
public static void fieldSet(Object receiver, Field f) {
handler.fieldSet(receiver, f);
}
public static void fieldGet(Object receiver, Field f) {
handler.fieldGet(receiver, f);
}
}
| 2,017
| 28.676471
| 108
|
java
|
soot
|
soot-master/src/main/java/soot/rtlib/tamiflex/package-info.java
|
/*-
* #%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%
*/
/**
* This package contains classes that may be emitted into a program during code generation. If Soot cannot find a class on
* the soot-classpath then it automatically loads the class from Soot's own JAR file but <i>only</i> if this class is in this
* package. This is to avoid accidental mix-ups between the classes of the application being analyzed and Soot's own classes.
*
* To add a class, use, for example, the following:
*
* <pre>
* // before calling soot.Main.main
* Scene.v().addBasicClass(SootSig.class.getName(), SootClass.BODIES);
* // then at some point
* Scene.v().getSootClass(SootSig.class.getName()).setApplicationClass();
* </pre>
*
* This will cause Soot to emit the class SootSig along with the analyzed program.
*/
package soot.rtlib.tamiflex;
| 1,600
| 39.025
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/AbstractShimpleExprSwitch.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.jimple.AbstractExprSwitch;
/**
* @author Navindra Umanee
**/
public abstract class AbstractShimpleExprSwitch<T> extends AbstractExprSwitch<T> implements ShimpleExprSwitch {
@Override
public void casePhiExpr(PhiExpr v) {
defaultCase(v);
}
}
| 1,112
| 29.916667
| 111
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/AbstractShimpleValueSwitch.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.jimple.AbstractJimpleValueSwitch;
/**
* @author Navindra Umanee
**/
public abstract class AbstractShimpleValueSwitch<T> extends AbstractJimpleValueSwitch<T> implements ShimpleValueSwitch {
@Override
public void casePhiExpr(PhiExpr e) {
defaultCase(e);
}
}
| 1,128
| 30.361111
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/DefaultShimpleFactory.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Body;
import soot.jimple.toolkits.scalar.UnreachableCodeEliminator;
import soot.shimple.toolkits.graph.GlobalValueNumberer;
import soot.shimple.toolkits.graph.SimpleGlobalValueNumberer;
import soot.toolkits.graph.Block;
import soot.toolkits.graph.BlockGraph;
import soot.toolkits.graph.BlockGraphConverter;
import soot.toolkits.graph.CytronDominanceFrontier;
import soot.toolkits.graph.DominanceFrontier;
import soot.toolkits.graph.DominatorTree;
import soot.toolkits.graph.DominatorsFinder;
import soot.toolkits.graph.ExceptionalBlockGraph;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.HashReversibleGraph;
import soot.toolkits.graph.ReversibleGraph;
import soot.toolkits.graph.SimpleDominatorsFinder;
import soot.toolkits.graph.UnitGraph;
/**
* @author Navindra Umanee
*/
public class DefaultShimpleFactory implements ShimpleFactory {
protected final Body body;
protected UnitGraph ug;
protected BlockGraph bg;
protected DominatorsFinder<Block> dFinder;
protected DominatorTree<Block> dTree;
protected DominanceFrontier<Block> dFrontier;
protected GlobalValueNumberer gvn;
protected ReversibleGraph<Block> rbg;
protected DominatorsFinder<Block> rdFinder;
protected DominatorTree<Block> rdTree;
protected DominanceFrontier<Block> rdFrontier;
public DefaultShimpleFactory(Body body) {
this.body = body;
}
@Override
public void clearCache() {
this.ug = null;
this.bg = null;
this.dFinder = null;
this.dTree = null;
this.dFrontier = null;
this.gvn = null;
this.rbg = null;
this.rdFinder = null;
this.rdTree = null;
this.rdFrontier = null;
}
public Body getBody() {
Body body = this.body;
if (body == null) {
throw new RuntimeException("Assertion failed: Call setBody() first.");
}
return body;
}
@Override
public ReversibleGraph<Block> getReverseBlockGraph() {
ReversibleGraph<Block> rbg = this.rbg;
if (rbg == null) {
rbg = new HashReversibleGraph<Block>(getBlockGraph());
rbg.reverse();
this.rbg = rbg;
}
return rbg;
}
@Override
public DominatorsFinder<Block> getReverseDominatorsFinder() {
DominatorsFinder<Block> rdFinder = this.rdFinder;
if (rdFinder == null) {
rdFinder = new SimpleDominatorsFinder<Block>(getReverseBlockGraph());
this.rdFinder = rdFinder;
}
return rdFinder;
}
@Override
public DominatorTree<Block> getReverseDominatorTree() {
DominatorTree<Block> rdTree = this.rdTree;
if (rdTree == null) {
rdTree = new DominatorTree<Block>(getReverseDominatorsFinder());
this.rdTree = rdTree;
}
return rdTree;
}
@Override
public DominanceFrontier<Block> getReverseDominanceFrontier() {
DominanceFrontier<Block> rdFrontier = this.rdFrontier;
if (rdFrontier == null) {
rdFrontier = new CytronDominanceFrontier<Block>(getReverseDominatorTree());
this.rdFrontier = rdFrontier;
}
return rdFrontier;
}
@Override
public BlockGraph getBlockGraph() {
BlockGraph bg = this.bg;
if (bg == null) {
bg = new ExceptionalBlockGraph((ExceptionalUnitGraph) getUnitGraph());
BlockGraphConverter.addStartStopNodesTo(bg);
this.bg = bg;
}
return bg;
}
@Override
public UnitGraph getUnitGraph() {
UnitGraph ug = this.ug;
if (ug == null) {
Body body = getBody();
UnreachableCodeEliminator.v().transform(body);
ug = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body);
this.ug = ug;
}
return ug;
}
@Override
public DominatorsFinder<Block> getDominatorsFinder() {
DominatorsFinder<Block> dFinder = this.dFinder;
if (dFinder == null) {
dFinder = new SimpleDominatorsFinder<Block>(getBlockGraph());
this.dFinder = dFinder;
}
return dFinder;
}
@Override
public DominatorTree<Block> getDominatorTree() {
DominatorTree<Block> dTree = this.dTree;
if (dTree == null) {
dTree = new DominatorTree<Block>(getDominatorsFinder());
this.dTree = dTree;
}
return dTree;
}
@Override
public DominanceFrontier<Block> getDominanceFrontier() {
DominanceFrontier<Block> dFrontier = this.dFrontier;
if (dFrontier == null) {
dFrontier = new CytronDominanceFrontier<Block>(getDominatorTree());
this.dFrontier = dFrontier;
}
return dFrontier;
}
@Override
public GlobalValueNumberer getGlobalValueNumberer() {
GlobalValueNumberer gvn = this.gvn;
if (gvn == null) {
gvn = new SimpleGlobalValueNumberer(getBlockGraph());
this.gvn = gvn;
}
return gvn;
}
}
| 5,549
| 27.608247
| 81
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/PhiExpr.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.Local;
import soot.Unit;
import soot.Value;
import soot.toolkits.graph.Block;
import soot.toolkits.scalar.ValueUnitPair;
/**
* A fully defined PhiExpr usually consists of a list of Values for the arguments alongst with the corresponding control flow
* predecessor for each argument. This may be provided either as a Soot CFG Block or more directly as the Unit at the end of
* the corresponding CFG block.
*
* <p>
* As much as possible we try to conform to the semantics as described by Cytron et al., TOPLAS Oct. 91. A Phi node such as
* "x_1 = Phi(x_2, x_3)" is eliminated by respectively adding the statements "x_1 = x_2" and "x_1 = x_3" at the end of the
* corresponding control flow predecessor.
*
* <p>
* However, due to the fact that each argument is explicitly associated with the control flow predecessor, there may be some
* subtle differences. We tried to make the behaviour as robust and transparent as possible by handling the common cases of
* Unit chain manipulations in the Shimple internal implementation of PatchingChain.
*
* @author Navindra Umanee
* @see <a href="http://citeseer.nj.nec.com/cytron91efficiently.html">Efficiently Computing Static Single Assignment Form and
* the Control Dependence Graph</a>
* @see Shimple#newPhiExpr(List, List)
* @see Shimple#newPhiExpr(Local, List)
**/
public interface PhiExpr extends ShimpleExpr {
/**
* Returns an unmodifiable, backed view of the arguments to this PhiExpr. Each argument is a ValueUnitPair.
*
* @see soot.toolkits.scalar.ValueUnitPair
**/
public List<ValueUnitPair> getArgs();
/**
* Returns a list of the values used by this PhiExpr.
**/
public List<Value> getValues();
/**
* Returns a list of the control flow predecessor Units being tracked by this PhiExpr
**/
public List<Unit> getPreds();
/**
* Returns the number of arguments in this PhiExpr.
**/
public int getArgCount();
/**
* Returns the argument pair for the given index. Null if out-of-bounds.
**/
public ValueUnitPair getArgBox(int index);
/**
* Returns the value for the given index into the PhiExpr. Null if out-of-bounds.
**/
public Value getValue(int index);
/**
* Returns the control flow predecessor Unit for the given index into the PhiExpr. Null if out-of-bounds.
**/
public Unit getPred(int index);
/**
* Returns the index of the argument associated with the given control flow predecessor Unit. Returns -1 if not found.
**/
public int getArgIndex(Unit predTailUnit);
/**
* Returns the argument pair corresponding to the given CFG predecessor. Returns null if not found.
**/
public ValueUnitPair getArgBox(Unit predTailUnit);
/**
* Get the PhiExpr argument corresponding to the given control flow predecessor, returns null if not available.
**/
public Value getValue(Unit predTailUnit);
/**
* Returns the index of the argument associated with the given control flow predecessor. Returns -1 if not found.
**/
public int getArgIndex(Block pred);
/**
* Returns the argument pair corresponding to the given CFG predecessor. Returns null if not found.
**/
public ValueUnitPair getArgBox(Block pred);
/**
* Get the PhiExpr argument corresponding to the given control flow predecessor, returns null if not available.
**/
public Value getValue(Block pred);
/**
* Modify the PhiExpr argument at the given index with the given information. Returns false on failure.
**/
public boolean setArg(int index, Value arg, Unit predTailUnit);
/**
* Modify the PhiExpr argument at the given index with the given information. Returns false on failure.
**/
public boolean setArg(int index, Value arg, Block pred);
/**
* Set the value at the given index into the PhiExpr. Returns false on failure.
**/
public boolean setValue(int index, Value arg);
/**
* Locate the argument associated with the given CFG predecessor unit and set the value. Returns false on failure.
**/
public boolean setValue(Unit predTailUnit, Value arg);
/**
* Locate the argument associated with the given CFG predecessor and set the value. Returns false on failure.
**/
public boolean setValue(Block pred, Value arg);
/**
* Update the CFG predecessor associated with the PhiExpr argument at the given index. Returns false on failure.
**/
public boolean setPred(int index, Unit predTailUnit);
/**
* Update the CFG predecessor associated with the PhiExpr argument at the given index. Returns false on failure.
**/
public boolean setPred(int index, Block pred);
/**
* Remove the argument at the given index. Returns false on failure.
**/
public boolean removeArg(int index);
/**
* Remove the argument corresponding to the given CFG predecessor. Returns false on failure.
**/
public boolean removeArg(Unit predTailUnit);
/**
* Remove the argument corresponding to the given CFG predecessor. Returns false on failure.
**/
public boolean removeArg(Block pred);
/**
* Remove the given argument. Returns false on failure.
**/
public boolean removeArg(ValueUnitPair arg);
/**
* Add the given argument associated with the given CFG predecessor. Returns false on failure.
**/
public boolean addArg(Value arg, Block pred);
/**
* Add the given argument associated with the given CFG predecessor. Returns false on failure.
**/
public boolean addArg(Value arg, Unit predTailUnit);
/**
* Set the block number of the Phi node.
**/
public void setBlockId(int blockId);
/**
* Returns the id number of the block from which the Phi node originated from.
**/
public int getBlockId();
}
| 6,581
| 32.411168
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/PiExpr.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Unit;
import soot.Value;
import soot.toolkits.scalar.ValueUnitPair;
/**
* @author Navindra Umanee
**/
public interface PiExpr extends ShimpleExpr {
public ValueUnitPair getArgBox();
public Value getValue();
public Unit getCondStmt();
public Object getTargetKey();
public void setValue(Value v);
public void setCondStmt(Unit cs);
public void setTargetKey(Object targetKey);
}
| 1,257
| 25.765957
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/Shimple.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.Local;
import soot.PhaseOptions;
import soot.Singletons;
import soot.SootMethod;
import soot.Unit;
import soot.UnitBox;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.JimpleBody;
import soot.options.Options;
import soot.shimple.internal.SPhiExpr;
import soot.shimple.internal.SPiExpr;
import soot.toolkits.graph.Block;
import soot.toolkits.scalar.ValueUnitPair;
import soot.util.Chain;
/**
* Contains the constructors for the components of the SSA Shimple grammar. Methods are available to construct Shimple from
* Jimple/Shimple, create Phi nodes, and converting back from Shimple to Jimple.
*
* <p>
* This should normally be used in conjunction with the constructor methods from soot.jimple.Jimple.
*
* <p>
* Miscellaneous utility functions are also available in this class.
*
* @author Navindra Umanee
* @see soot.jimple.Jimple
* @see <a href="http://citeseer.nj.nec.com/cytron91efficiently.html">Efficiently Computing Static Single Assignment Form and
* the Control Dependence Graph</a>
*/
public class Shimple {
private static final Logger logger = LoggerFactory.getLogger(Shimple.class);
public static final String IFALIAS = "IfAlias";
public static final String MAYMODIFY = "MayModify";
public static final String PHI = "Phi";
public static final String PI = "Pi";
public static final String PHASE = "shimple";
public Shimple(Singletons.Global g) {
}
public static Shimple v() {
return G.v().soot_shimple_Shimple();
}
/**
* Returns an empty ShimpleBody associated with method m, using default phase options.
*/
public ShimpleBody newBody(SootMethod m) {
Map<String, String> options = PhaseOptions.v().getPhaseOptions(PHASE);
return new ShimpleBody(m, options);
}
/**
* Returns an empty ShimpleBody associated with method m, using provided option map.
*/
public ShimpleBody newBody(SootMethod m, Map<String, String> options) {
return new ShimpleBody(m, options);
}
/**
* Returns a ShimpleBody constructed from b, using default phase options.
*/
public ShimpleBody newBody(Body b) {
Map<String, String> options = PhaseOptions.v().getPhaseOptions(PHASE);
return new ShimpleBody(b, options);
}
/**
* Returns a ShimpleBody constructed from b, using provided option Map.
*/
public ShimpleBody newBody(Body b, Map<String, String> options) {
return new ShimpleBody(b, options);
}
/**
* Create a trivial PhiExpr, where preds are an ordered list of the control predecessor Blocks of the Phi expression.
* Instead of a list of blocks, you may provide a list of the tail Units from the corresponding blocks.
*/
public PhiExpr newPhiExpr(Local leftLocal, List<Block> preds) {
return new SPhiExpr(leftLocal, preds);
}
public PiExpr newPiExpr(Local local, Unit predicate, Object targetKey) {
return new SPiExpr(local, predicate, targetKey);
}
/**
* Create a PhiExpr with the provided list of Values (Locals or Constants) and the corresponding control flow predecessor
* Blocks. Instead of a list of predecessor blocks, you may provide a list of the tail Units from the corresponding blocks.
*/
public PhiExpr newPhiExpr(List<Value> args, List<Unit> preds) {
return new SPhiExpr(args, preds);
}
/**
* Constructs a JimpleBody from a ShimpleBody.
*
* @see soot.options.ShimpleOptions
*/
public JimpleBody newJimpleBody(ShimpleBody body) {
return body.toJimpleBody();
}
/**
* Returns true if the value is a Phi expression, false otherwise.
*/
public static boolean isPhiExpr(Value value) {
return (value instanceof PhiExpr);
}
/**
* Returns true if the unit is a Phi node, false otherwise.
*/
public static boolean isPhiNode(Unit unit) {
return getPhiExpr(unit) != null;
}
/**
* Returns the corresponding PhiExpr if the unit is a Phi node, null otherwise.
*/
public static PhiExpr getPhiExpr(Unit unit) {
if (unit instanceof AssignStmt) {
Value right = ((AssignStmt) unit).getRightOp();
if (isPhiExpr(right)) {
return (PhiExpr) right;
}
}
return null;
}
public static boolean isPiExpr(Value value) {
return (value instanceof PiExpr);
}
public static boolean isPiNode(Unit unit) {
return getPiExpr(unit) != null;
}
public static PiExpr getPiExpr(Unit unit) {
if (unit instanceof AssignStmt) {
Value right = ((AssignStmt) unit).getRightOp();
if (isPiExpr(right)) {
return (PiExpr) right;
}
}
return null;
}
/**
* Returns the corresponding left Local if the unit is a Shimple node, null otherwise.
*/
public static Local getLhsLocal(Unit unit) {
if (unit instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) unit;
if (assign.getRightOp() instanceof ShimpleExpr) {
return (Local) assign.getLeftOp();
}
}
return null;
}
/**
* If you are removing a Unit from a Unit chain which contains PhiExpr's, you might want to call this utility function in
* order to update any PhiExpr pointers to the Unit to point to the Unit's predecessor(s). This function will not modify
* "branch target" UnitBoxes.
*
* <p>
* Normally you should not have to call this function directly, since patching is taken care of Shimple's internal
* implementation of PatchingChain.
*/
public static void redirectToPreds(Body body, Unit remove) {
/* Determine whether we should continue processing or not. */
if (remove.getBoxesPointingToThis().isEmpty()) {
return;
}
/* Ok, continuing... */
boolean debug = Options.v().debug();
if (body instanceof ShimpleBody) {
debug |= ((ShimpleBody) body).getOptions().debug();
}
final Chain<Unit> units = body.getUnits();
final Set<Unit> preds = new HashSet<Unit>();
final Set<PhiExpr> phis = new HashSet<PhiExpr>();
// find fall-through pred
if (!remove.equals(units.getFirst())) {
Unit possiblePred = units.getPredOf(remove);
if (possiblePred.fallsThrough()) {
preds.add(possiblePred);
}
}
// find the rest of the preds and all Phi's that point to remove
for (Unit unit : units) {
for (UnitBox targetBox : unit.getUnitBoxes()) {
if (remove.equals(targetBox.getUnit())) {
if (targetBox.isBranchTarget()) {
preds.add(unit);
} else {
PhiExpr phiExpr = Shimple.getPhiExpr(unit);
if (phiExpr != null) {
phis.add(phiExpr);
}
}
}
}
}
/* sanity check */
if (phis.isEmpty()) {
if (debug) {
// Only print the warning if there exists a UnitBox referencing 'remove' that is not
// a branch target (i.e. otherwise, we shouldn't expect to find a PHI node anyway).
for (UnitBox u : remove.getBoxesPointingToThis()) {
if (!u.isBranchTarget()) {
logger.warn("Orphaned UnitBoxes to " + remove + "? Shimple.redirectToPreds is giving up.");
break;
}
}
}
return;
}
if (preds.isEmpty()) {
if (debug) {
logger.warn("Shimple.redirectToPreds found no predecessors for " + remove + " in " + body.getMethod() + ".");
}
if (!remove.equals(units.getFirst())) {
Unit pred = units.getPredOf(remove);
if (debug) {
logger.warn("Falling back to immediate chain predecessor: " + pred + ".");
}
preds.add(pred);
} else if (!remove.equals(units.getLast())) {
Unit succ = units.getSuccOf(remove);
if (debug) {
logger.warn("Falling back to immediate chain successor: " + succ + ".");
}
preds.add(succ);
} else {
throw new RuntimeException("Assertion failed.");
}
}
// At this point we have found all the preds and relevant Phis.
// Each Phi needs an argument for each pred.
for (PhiExpr phiExpr : phis) {
ValueUnitPair argBox = phiExpr.getArgBox(remove);
if (argBox == null) {
throw new RuntimeException("Assertion failed.");
}
// now we've got the value!
Value arg = argBox.getValue();
phiExpr.removeArg(argBox);
// add new arguments to Phi
for (Unit pred : preds) {
boolean added = phiExpr.addArg(arg, pred);
if (!added) {
soot.BriefUnitPrinter prtr = new soot.BriefUnitPrinter(body);
prtr.setIndent("");
phiExpr.toString(prtr);
logger.warn("Shimple.redirectToPreds failed to add " + arg + " (for predecessor: " + pred + ") to "
+ prtr.toString() + " in " + body.getMethod() + ".");
}
}
}
}
/**
* Redirects PhiExpr pointers referencing the first Unit to instead reference the second Unit.
*
* <p>
* Normally you should not have to call this function directly, since patching is taken care of Shimple's internal
* implementation of PatchingChain.
*/
public static void redirectPointers(Unit oldLocation, Unit newLocation) {
// important to make a copy to avoid concurrent modification
for (UnitBox box : new ArrayList<>(oldLocation.getBoxesPointingToThis())) {
if (box.getUnit() != oldLocation) {
throw new RuntimeException("Something weird's happening");
}
if (!box.isBranchTarget()) {
box.setUnit(newLocation);
}
}
}
}
| 10,517
| 30.680723
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/ShimpleBody.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.StmtBody;
import soot.options.Options;
import soot.options.ShimpleOptions;
import soot.shimple.internal.SPatchingChain;
import soot.shimple.internal.ShimpleBodyBuilder;
import soot.util.HashChain;
// * <p> We decided to hide all the intelligence in
// * internal.ShimpleBodyBuilder for clarity of API. Eventually we will
// * likely switch to an explicit Strategy pattern that will allow us to
// * select different SSA behaviours and algorithms.
/**
* Implementation of the Body class for the SSA Shimple IR. This class provides methods for maintaining SSA form as well as
* eliminating SSA form.
*
* @author Navindra Umanee
* @see soot.shimple.internal.ShimpleBodyBuilder
* @see <a href="http://citeseer.nj.nec.com/cytron91efficiently.html">Efficiently Computing Static Single Assignment Form and
* the Control Dependence Graph</a>
*/
public class ShimpleBody extends StmtBody {
private static final Logger logger = LoggerFactory.getLogger(ShimpleBody.class);
/**
* Holds our options map...
*/
protected ShimpleOptions options;
protected ShimpleBodyBuilder sbb;
/**
* Set isSSA boolean to indicate whether a ShimpleBody is still in SSA form or not. Could be useful for book-keeping
* purposes.
*/
protected boolean isSSA = false;
/**
* Construct an empty ShimpleBody associated with m.
*/
ShimpleBody(SootMethod m, Map<String, String> options) {
super(m);
// must happen before SPatchingChain gets created
this.options = new ShimpleOptions(options);
setSSA(true);
this.unitChain = new SPatchingChain(this, new HashChain<Unit>());
this.sbb = new ShimpleBodyBuilder(this);
}
/**
* Constructs a ShimpleBody from the given Body and options.
*
* <p>
* Currently available option is "naive-phi-elimination", typically in the "shimple" phase (eg, -p shimple
* naive-phi-elimination) which can be useful for understanding the effect of analyses.
*/
ShimpleBody(Body body, Map<String, String> options) {
super(body.getMethod());
if (!(body instanceof JimpleBody || body instanceof ShimpleBody)) {
throw new RuntimeException("Cannot construct ShimpleBody from given Body type: " + body.getClass());
}
if (Options.v().verbose()) {
logger.debug("[" + getMethod().getName() + "] Constructing ShimpleBody...");
}
// must happen before SPatchingChain gets created
this.options = new ShimpleOptions(options);
this.unitChain = new SPatchingChain(this, new HashChain<Unit>());
importBodyContentsFrom(body);
/* Shimplise body */
this.sbb = new ShimpleBodyBuilder(this);
rebuild(body instanceof ShimpleBody);
}
/**
* Recompute SSA form.
*
* <p>
* Note: assumes presence of Phi nodes in body that require elimination. If you *know* there are no Phi nodes present, you
* may prefer to use rebuild(false) in order to skip some transformations during the Phi elimination process.
*/
public void rebuild() {
rebuild(true);
}
/**
* Rebuild SSA form.
*
* <p>
* If there are Phi nodes already present in the body, it is imperative that we specify this so that the algorithm can
* eliminate them before rebuilding SSA.
*
* <p>
* The eliminate Phi nodes stage is harmless, but if you *know* that no Phi nodes are present and you wish to avoid the
* transformations involved in eliminating Phi nodes, use rebuild(false).
*/
public void rebuild(boolean hasPhiNodes) {
sbb.transform();
setSSA(true);
}
/**
* Returns an equivalent unbacked JimpleBody of the current Body by eliminating the Phi nodes.
*
* <p>
* Currently available option is "naive-phi-elimination", typically specified in the "shimple" phase (eg, -p shimple
* naive-phi-elimination) which skips the dead code elimination and register allocation phase before eliminating Phi nodes.
* This can be useful for understanding the effect of analyses.
*
* <p>
* Remember to setActiveBody() if necessary in your SootMethod.
*
* @see #eliminatePhiNodes()
*/
public JimpleBody toJimpleBody() {
ShimpleBody sBody = (ShimpleBody) this.clone();
sBody.eliminateNodes();
JimpleBody jBody = Jimple.v().newBody(sBody.getMethod());
jBody.importBodyContentsFrom(sBody);
return jBody;
}
/**
* Remove Phi nodes from body. SSA form is no longer a given once done.
*
* <p>
* Currently available option is "naive-phi-elimination", typically specified in the "shimple" phase (eg, -p shimple
* naive-phi-elimination) which skips the dead code elimination and register allocation phase before eliminating Phi nodes.
* This can be useful for understanding the effect of analyses.
*
* @see #toJimpleBody()
*/
public void eliminatePhiNodes() {
sbb.preElimOpt();
sbb.eliminatePhiNodes();
sbb.postElimOpt();
setSSA(false);
}
public void eliminatePiNodes() {
sbb.eliminatePiNodes();
}
public void eliminateNodes() {
sbb.preElimOpt();
sbb.eliminatePhiNodes();
if (options.extended()) {
sbb.eliminatePiNodes();
}
sbb.postElimOpt();
setSSA(false);
}
/**
* Returns a copy of the current ShimpleBody.
*/
@Override
public Object clone() {
Body b = Shimple.v().newBody(getMethodUnsafe());
b.importBodyContentsFrom(this);
return b;
}
/**
* Sets a flag that indicates whether ShimpleBody is still in SSA form after a transformation or not. It is often up to the
* user to indicate if a body is no longer in SSA form.
*/
public void setSSA(boolean isSSA) {
this.isSSA = isSSA;
}
/**
* Returns value of, optional, user-maintained SSA boolean.
*
* @see #setSSA(boolean)
*/
public boolean isSSA() {
return isSSA;
}
public boolean isExtendedSSA() {
return options.extended();
}
/**
* Returns the Shimple options applicable to this body.
*/
public ShimpleOptions getOptions() {
return options;
}
/**
* Make sure the locals in this body all have unique String names. If the standard-local-names option is specified to
* Shimple, this results in the LocalNameStandardizer being applied. Otherwise, renaming is kept to a minimum and an
* underscore notation is used to differentiate locals previously of the same name.
*
* @see soot.jimple.toolkits.scalar.LocalNameStandardizer
*/
public void makeUniqueLocalNames() {
sbb.makeUniqueLocalNames();
}
}
| 7,529
| 29.987654
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/ShimpleExpr.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.UnitBoxOwner;
import soot.jimple.Expr;
public interface ShimpleExpr extends Expr, UnitBoxOwner {
}
| 959
| 31
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/ShimpleExprSwitch.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.jimple.ExprSwitch;
/**
* @author Navindra Umanee
**/
public interface ShimpleExprSwitch extends ExprSwitch {
public abstract void casePhiExpr(PhiExpr v);
}
| 1,020
| 29.939394
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/ShimpleFactory.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.shimple.toolkits.graph.GlobalValueNumberer;
import soot.toolkits.graph.Block;
import soot.toolkits.graph.BlockGraph;
import soot.toolkits.graph.DominanceFrontier;
import soot.toolkits.graph.DominatorTree;
import soot.toolkits.graph.DominatorsFinder;
import soot.toolkits.graph.ReversibleGraph;
import soot.toolkits.graph.UnitGraph;
/**
* @author Navindra Umanee
**/
public interface ShimpleFactory {
/**
* Constructors should memoize their return value. Call clearCache() to force recomputations if body has changed and
* setBody() hasn't been called again.
**/
public void clearCache();
public UnitGraph getUnitGraph();
public BlockGraph getBlockGraph();
public DominatorsFinder<Block> getDominatorsFinder();
public DominatorTree<Block> getDominatorTree();
public DominanceFrontier<Block> getDominanceFrontier();
public GlobalValueNumberer getGlobalValueNumberer();
public ReversibleGraph<Block> getReverseBlockGraph();
public DominatorsFinder<Block> getReverseDominatorsFinder();
public DominatorTree<Block> getReverseDominatorTree();
public DominanceFrontier<Block> getReverseDominanceFrontier();
}
| 2,008
| 29.907692
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/ShimpleMethodSource.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Body;
import soot.MethodSource;
import soot.SootMethod;
public class ShimpleMethodSource implements MethodSource {
MethodSource ms;
public ShimpleMethodSource(MethodSource ms) {
this.ms = ms;
}
@Override
public Body getBody(SootMethod m, String phaseName) {
Body b = ms.getBody(m, phaseName);
return b == null ? null : Shimple.v().newBody(b);
}
}
| 1,233
| 28.380952
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/ShimpleTransformer.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.options.Options;
/**
* Traverses all methods, in all classes from the Scene, and transforms them to Shimple. Typically used for whole-program
* analysis on Shimple.
*
* @author Navindra Umanee
*/
public class ShimpleTransformer extends SceneTransformer {
private static final Logger logger = LoggerFactory.getLogger(ShimpleTransformer.class);
public ShimpleTransformer(Singletons.Global g) {
}
public static ShimpleTransformer v() {
return G.v().soot_shimple_ShimpleTransformer();
}
@Override
protected void internalTransform(String phaseName, Map options) {
if (Options.v().verbose()) {
logger.debug("Transforming all classes in the Scene to Shimple...");
}
// *** FIXME: Add debug output to indicate which class/method is being shimplified.
// *** FIXME: Is ShimpleTransformer the right solution? The call graph may deem
// some classes unreachable.
for (SootClass sClass : Scene.v().getClasses()) {
if (!sClass.isPhantom()) {
for (SootMethod method : sClass.getMethods()) {
if (method.isConcrete()) {
if (method.hasActiveBody()) {
Body body = method.getActiveBody();
ShimpleBody sBody;
if (body instanceof ShimpleBody) {
sBody = (ShimpleBody) body;
if (!sBody.isSSA()) {
sBody.rebuild();
}
} else {
sBody = Shimple.v().newBody(body);
}
method.setActiveBody(sBody);
} else {
method.setSource(new ShimpleMethodSource(method.getSource()));
}
}
}
}
}
}
}
| 2,777
| 29.527473
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/ShimpleValueSwitch.java
|
package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.jimple.JimpleValueSwitch;
/**
* @author Navindra Umanee
**/
public interface ShimpleValueSwitch extends JimpleValueSwitch, ShimpleExprSwitch {
}
| 1,007
| 30.5
| 82
|
java
|
soot
|
soot-master/src/main/java/soot/shimple/internal/PhiNodeManager.java
|
package soot.shimple.internal;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import soot.IdentityUnit;
import soot.Local;
import soot.Trap;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
import soot.shimple.PhiExpr;
import soot.shimple.Shimple;
import soot.shimple.ShimpleBody;
import soot.shimple.ShimpleFactory;
import soot.toolkits.graph.Block;
import soot.toolkits.graph.BlockGraph;
import soot.toolkits.graph.DominanceFrontier;
import soot.toolkits.graph.DominatorNode;
import soot.toolkits.graph.DominatorTree;
import soot.toolkits.scalar.ValueUnitPair;
import soot.util.Chain;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
/**
* @author Navindra Umanee
* @see soot.shimple.ShimpleBody
* @see <a href="http://citeseer.nj.nec.com/cytron91efficiently.html">Efficiently Computing Static Single Assignment Form and
* the Control Dependence Graph</a>
*/
public class PhiNodeManager {
protected final ShimpleBody body;
protected final ShimpleFactory sf;
protected BlockGraph cfg;
protected MultiMap<Local, Block> varToBlocks;
protected Map<Unit, Block> unitToBlock;
public PhiNodeManager(ShimpleBody body, ShimpleFactory sf) {
this.body = body;
this.sf = sf;
}
public void update() {
BlockGraph oldCfg = this.cfg;
this.cfg = sf.getBlockGraph();
if (oldCfg != this.cfg) {
// If the CFG was rebuilt, clear the maps because Blocks are stale
this.unitToBlock = null;
this.varToBlocks = null;
}
}
/**
* Phi node Insertion Algorithm from Cytron et al 91, P24-5,
*
* <p>
* Special Java case: If a variable is not defined along all paths of entry to a node, a Phi node is not needed.
* </p>
*/
public boolean insertTrivialPhiNodes() {
update();
this.varToBlocks = new HashMultiMap<Local, Block>();
final Map<Local, List<Block>> localsToDefPoints = new LinkedHashMap<Local, List<Block>>();
// compute localsToDefPoints and varToBlocks
for (Block block : cfg) {
for (Unit unit : block) {
for (ValueBox vb : unit.getDefBoxes()) {
Value def = vb.getValue();
if (def instanceof Local) {
Local local = (Local) def;
List<Block> def_points = localsToDefPoints.get(local);
if (def_points == null) {
def_points = new ArrayList<Block>();
localsToDefPoints.put(local, def_points);
}
def_points.add(block);
}
}
if (Shimple.isPhiNode(unit)) {
varToBlocks.put(Shimple.getLhsLocal(unit), block);
}
}
}
boolean change = false;
{
final DominatorTree<Block> dt = sf.getDominatorTree();
final DominanceFrontier<Block> df = sf.getDominanceFrontier();
/* Routine initialisations. */
int iterCount = 0;
int[] workFlags = new int[cfg.size()];
Stack<Block> workList = new Stack<Block>();
Map<Integer, Integer> has_already = new HashMap<Integer, Integer>();
for (Block block : cfg) {
has_already.put(block.getIndexInMethod(), 0);
}
/* Main Cytron algorithm. */
for (Map.Entry<Local, List<Block>> e : localsToDefPoints.entrySet()) {
iterCount++;
// initialise worklist
{
assert (workList.isEmpty());
List<Block> def_points = e.getValue();
// if the local is only defined once, no need for phi nodes
if (def_points.size() == 1) {
continue;
}
for (Block block : def_points) {
workFlags[block.getIndexInMethod()] = iterCount;
workList.push(block);
}
}
Local local = e.getKey();
while (!workList.empty()) {
Block block = workList.pop();
for (DominatorNode<Block> dn : df.getDominanceFrontierOf(dt.getDode(block))) {
Block frontierBlock = dn.getGode();
if (!frontierBlock.iterator().hasNext()) {
continue;
}
int fBIndex = frontierBlock.getIndexInMethod();
if (has_already.get(fBIndex) < iterCount) {
has_already.put(fBIndex, iterCount);
prependTrivialPhiNode(local, frontierBlock);
change = true;
if (workFlags[fBIndex] < iterCount) {
workFlags[fBIndex] = iterCount;
workList.push(frontierBlock);
}
}
}
}
}
}
return change;
}
/**
* Inserts a trivial Phi node with the appropriate number of arguments.
*/
public void prependTrivialPhiNode(Local local, Block frontierBlock) {
PhiExpr pe = Shimple.v().newPhiExpr(local, frontierBlock.getPreds());
pe.setBlockId(frontierBlock.getIndexInMethod());
Unit trivialPhi = Jimple.v().newAssignStmt(local, pe);
// is it a catch block?
Unit head = frontierBlock.getHead();
if (head instanceof IdentityUnit) {
frontierBlock.insertAfter(trivialPhi, head);
} else {
frontierBlock.insertBefore(trivialPhi, head);
}
varToBlocks.put(local, frontierBlock);
}
/**
* Exceptional Phi nodes have a huge number of arguments and control flow predecessors by default. Since it is useless
* trying to keep the number of arguments and control flow predecessors in synch, we might as well trim out all redundant
* arguments and eliminate a huge number of copy statements when we get out of SSA form in the process.
*/
public void trimExceptionalPhiNodes() {
Set<Unit> handlerUnits = new HashSet<Unit>();
for (Trap trap : body.getTraps()) {
handlerUnits.add(trap.getHandlerUnit());
}
for (Block block : cfg) {
// trim relevant Phi expressions
if (handlerUnits.contains(block.getHead())) {
for (Unit unit : block) {
// if(!(newPhiNodes.contains(unit)))
PhiExpr phi = Shimple.getPhiExpr(unit);
if (phi != null) {
trimPhiNode(phi);
}
}
}
}
}
/**
* @see #trimExceptionalPhiNodes()
*/
public void trimPhiNode(PhiExpr phiExpr) {
/*
* A value may appear many times in an exceptional Phi. Hence, the same value may be associated with many UnitBoxes. We
* build the MultiMap valueToPairs for convenience.
*/
MultiMap<Value, ValueUnitPair> valueToPairs = new HashMultiMap<Value, ValueUnitPair>();
for (ValueUnitPair argPair : phiExpr.getArgs()) {
valueToPairs.put(argPair.getValue(), argPair);
}
/*
* Consider each value and see if we can find the dominating UnitBoxes. Once we have found all the dominating UnitBoxes,
* the rest of the redundant arguments can be trimmed.
*/
for (Value value : valueToPairs.keySet()) {
// although the champs list constantly shrinks, guaranteeing
// termination, the challengers list never does. This could
// be optimised.
Set<ValueUnitPair> pairsSet = valueToPairs.get(value);
List<ValueUnitPair> champs = new LinkedList<ValueUnitPair>(pairsSet);
List<ValueUnitPair> challengers = new LinkedList<ValueUnitPair>(pairsSet);
// champ is the currently assumed dominator
ValueUnitPair champ = champs.remove(0);
Unit champU = champ.getUnit();
// hopefully everything will work out the first time, but
// if not, we will have to try a new champion just in case
// there is more that can be trimmed.
for (boolean retry = true; retry;) {
retry = false;
// go through each challenger and see if we dominate them
// if not, the challenger becomes the new champ
for (Iterator<ValueUnitPair> itr = challengers.iterator(); itr.hasNext();) {
ValueUnitPair challenger = itr.next();
if (challenger.equals(champ)) {
continue;
}
Unit challengerU = challenger.getUnit();
if (dominates(champU, challengerU)) {
// kill the challenger
phiExpr.removeArg(challenger);
itr.remove();
} else if (dominates(challengerU, champU)) {
// we die, find a new champ
phiExpr.removeArg(champ);
champ = challenger;
champU = champ.getUnit();
} else {
// neither wins, oops! we'll have to try the next available champ
// at the next pass. It may very well be inevitable that we will
// have two identical value args in an exceptional PhiExpr, but the
// more we can trim the better.
retry = true;
}
}
if (retry) {
if (champs.isEmpty()) {
break;
} else {
champ = champs.remove(0);
champU = champ.getUnit();
}
}
}
}
/*
* { List preds = phiExpr.getPreds();
*
* for(int i = 0; i < phiExpr.getArgCount(); i++){ ValueUnitPair vup = phiExpr.getArgBox(i); Value value =
* vup.getValue(); Unit unit = vup.getUnit();
*
* PhiExpr innerPhi = Shimple.getPhiExpr(unit); if(innerPhi == null) continue;
*
* Value innerValue = Shimple.getLhsLocal(unit); if(!innerValue.equals(value)) continue;
*
* boolean canRemove = true; for(int j = 0; j < innerPhi.getArgCount(); j++){ Unit innerPred = innerPhi.getPred(j);
* if(!preds.contains(innerPred)){ canRemove = false; break; } }
*
* if(canRemove) phiExpr.removeArg(vup); } }
*/
}
/**
* Returns true if champ dominates challenger. Note that false doesn't necessarily mean that challenger dominates champ.
*/
public boolean dominates(Unit champ, Unit challenger) {
if (champ == null || challenger == null) {
throw new RuntimeException("Assertion failed.");
}
// self-domination
if (champ.equals(challenger)) {
return true;
}
Map<Unit, Block> unitToBlock = this.unitToBlock;
if (unitToBlock == null) {
unitToBlock = getUnitToBlockMap(cfg);
this.unitToBlock = unitToBlock;
}
Block champBlock = unitToBlock.get(champ);
Block challengerBlock = unitToBlock.get(challenger);
if (champBlock.equals(challengerBlock)) {
for (Unit unit : champBlock) {
if (unit.equals(champ)) {
return true;
}
if (unit.equals(challenger)) {
return false;
}
}
throw new RuntimeException("Assertion failed.");
}
DominatorTree<Block> dt = sf.getDominatorTree();
DominatorNode<Block> champNode = dt.getDode(champBlock);
DominatorNode<Block> challengerNode = dt.getDode(challengerBlock);
// *** FIXME: System.out.println("champ: " + champNode);
// System.out.println("chall: " + challengerNode);
return dt.isDominatorOf(champNode, challengerNode);
}
/**
* Eliminate Phi nodes in block by naively replacing them with shimple assignment statements in the control flow
* predecessors. Returns true if new locals were added to the body during the process, false otherwise.
*/
public boolean doEliminatePhiNodes() {
// flag that indicates whether we created new locals during the elimination process
boolean addedNewLocals = false;
// List of Phi nodes to be deleted.
List<Unit> phiNodes = new ArrayList<Unit>();
// This stores the assignment statements equivalent to each
// (and every) Phi. We use lists instead of a Map of
// non-determinate order since we prefer to preserve the order
// of the assignment statements, i.e. if a block has more than
// one Phi expression, we prefer that the equivalent
// assignments be placed in the same order as the Phi expressions.
List<AssignStmt> equivStmts = new ArrayList<AssignStmt>();
// Similarly, to preserve order, instead of directly storing
// the pred, we store the pred box so that we follow the
// pointers when SPatchingChain moves them.
List<ValueUnitPair> predBoxes = new ArrayList<ValueUnitPair>();
final Jimple jimp = Jimple.v();
final Chain<Unit> units = body.getUnits();
for (Unit unit : units) {
PhiExpr phi = Shimple.getPhiExpr(unit);
if (phi != null) {
Local lhsLocal = Shimple.getLhsLocal(unit);
for (ValueUnitPair vup : phi.getArgs()) {
predBoxes.add(vup);
equivStmts.add(jimp.newAssignStmt(lhsLocal, vup.getValue()));
}
phiNodes.add(unit);
}
}
if (equivStmts.size() != predBoxes.size()) {
throw new RuntimeException("Assertion failed.");
}
for (ListIterator<ValueUnitPair> it = predBoxes.listIterator(); it.hasNext();) {
Unit pred = it.next().getUnit();
if (pred == null) {
throw new RuntimeException("Assertion failed.");
}
AssignStmt stmt = equivStmts.get(it.previousIndex());
// if we need to insert the copy statement *before* an
// instruction that happens to be *using* the Local being
// defined, we need to do some extra work to make sure we
// don't overwrite the old value of the local
if (pred.branches()) {
boolean needPriming = false;
Local lhsLocal = (Local) stmt.getLeftOp();
Local savedLocal = jimp.newLocal(lhsLocal.getName() + "_", lhsLocal.getType());
for (ValueBox useBox : pred.getUseBoxes()) {
if (lhsLocal.equals(useBox.getValue())) {
needPriming = true;
addedNewLocals = true;
useBox.setValue(savedLocal);
}
}
if (needPriming) {
body.getLocals().add(savedLocal);
units.insertBefore(jimp.newAssignStmt(savedLocal, lhsLocal), pred);
}
// this is all we really wanted to do!
units.insertBefore(stmt, pred);
} else {
units.insertAfter(stmt, pred);
}
}
for (Unit removeMe : phiNodes) {
units.remove(removeMe);
removeMe.clearUnitBoxes();
}
return addedNewLocals;
}
/**
* Convenience function that maps units to blocks. Should probably be in BlockGraph.
*/
public static Map<Unit, Block> getUnitToBlockMap(BlockGraph blocks) {
Map<Unit, Block> unitToBlock = new HashMap<Unit, Block>();
for (Block block : blocks) {
for (Unit unit : block) {
unitToBlock.put(unit, block);
}
}
return unitToBlock;
}
}
| 15,448
| 32.731441
| 125
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.