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/pointer/representations/GeneralConstObject.java
|
package soot.jimple.toolkits.pointer.representations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.G;
import soot.Type;
public class GeneralConstObject extends ConstantObject {
/* what's the soot class */
private Type type;
private String name;
private int id;
public GeneralConstObject(Type t, String n) {
this.type = t;
this.name = n;
this.id = G.v().GeneralConstObject_counter++;
}
public Type getType() {
return type;
}
public String toString() {
return name;
}
public int hashCode() {
return this.id;
}
public boolean equals(Object other) {
return this == other;
}
}
| 1,397
| 23.526316
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/pointer/representations/ReferenceVariable.java
|
package soot.jimple.toolkits.pointer.representations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public interface ReferenceVariable {
}
| 888
| 31.925926
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/pointer/representations/TypeConstants.java
|
package soot.jimple.toolkits.pointer.representations;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.AnySubType;
import soot.ArrayType;
import soot.G;
import soot.PhaseOptions;
import soot.RefType;
import soot.Singletons;
import soot.Type;
import soot.options.CGOptions;
public class TypeConstants {
public static TypeConstants v() {
return G.v().soot_jimple_toolkits_pointer_representations_TypeConstants();
}
public Type OBJECTCLASS;
public Type STRINGCLASS;
public Type CLASSLOADERCLASS;
public Type PROCESSCLASS;
public Type THREADCLASS;
public Type CLASSCLASS;
public Type FIELDCLASS;
public Type METHODCLASS;
public Type CONSTRUCTORCLASS;
public Type FILESYSTEMCLASS;
public Type PRIVILEGEDACTIONEXCEPTION;
public Type ACCESSCONTROLCONTEXT;
public Type ARRAYFIELDS;
public Type ARRAYMETHODS;
public Type ARRAYCONSTRUCTORS;
public Type ARRAYCLASSES;
public TypeConstants(Singletons.Global g) {
int jdkver = new CGOptions(PhaseOptions.v().getPhaseOptions("cg")).jdkver();
OBJECTCLASS = RefType.v("java.lang.Object");
STRINGCLASS = RefType.v("java.lang.String");
CLASSLOADERCLASS = AnySubType.v(RefType.v("java.lang.ClassLoader"));
PROCESSCLASS = AnySubType.v(RefType.v("java.lang.Process"));
THREADCLASS = AnySubType.v(RefType.v("java.lang.Thread"));
CLASSCLASS = RefType.v("java.lang.Class");
FIELDCLASS = RefType.v("java.lang.reflect.Field");
METHODCLASS = RefType.v("java.lang.reflect.Method");
CONSTRUCTORCLASS = RefType.v("java.lang.reflect.Constructor");
if (jdkver >= 2) {
FILESYSTEMCLASS = AnySubType.v(RefType.v("java.io.FileSystem"));
}
if (jdkver >= 2) {
PRIVILEGEDACTIONEXCEPTION = AnySubType.v(RefType.v("java.security.PrivilegedActionException"));
ACCESSCONTROLCONTEXT = RefType.v("java.security.AccessControlContext");
}
ARRAYFIELDS = ArrayType.v(RefType.v("java.lang.reflect.Field"), 1);
ARRAYMETHODS = ArrayType.v(RefType.v("java.lang.reflect.Method"), 1);
ARRAYCONSTRUCTORS = ArrayType.v(RefType.v("java.lang.reflect.Constructor"), 1);
ARRAYCLASSES = ArrayType.v(RefType.v("java.lang.Class"), 1);
}
}
| 2,933
| 30.548387
| 101
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/pointer/util/NativeHelper.java
|
package soot.jimple.toolkits.pointer.util;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.jimple.toolkits.pointer.representations.AbstractObject;
import soot.jimple.toolkits.pointer.representations.ReferenceVariable;
public abstract class NativeHelper {
/**
* Regular assignment such as "a = b".
*/
public void assign(ReferenceVariable lhs, ReferenceVariable rhs) {
assignImpl(lhs, rhs);
}
/**
* Assignment of an abstract object to the variable, such as " a = new A()", which is considered to add a target in a's
* points-to set.
*
* This method is used to formulate the effect of getting an environmental constant object such as 'getClass'.
*/
public void assignObjectTo(ReferenceVariable lhs, AbstractObject obj) {
assignObjectToImpl(lhs, obj);
}
/**
* Throw of an abstract object as an exception.
*/
public void throwException(AbstractObject obj) {
throwExceptionImpl(obj);
}
/**
* Returns a reference variable representing the array element of this variable. Now it does not look at the array index.
*/
public ReferenceVariable arrayElementOf(ReferenceVariable base) {
return arrayElementOfImpl(base);
}
/**
* Returns a variable which has the effect of cloning. A moderate approach would return the variable itself.
*
* e.g., a = b.clone() will be rendered to: Vr.isAssigned(Vb.cloneObject()); Va = Vr;
*/
public ReferenceVariable cloneObject(ReferenceVariable source) {
return cloneObjectImpl(source);
}
/**
* Returns a variable which carries an allocation site with the least type (an artificial type, subtype of any other types,
* which means such type info is useless for resolving invocation targets).
*
* It is used for simulating java.lang.Class.newInstance0(); To verify, @this variable mush have CLASSCLASS type.
*/
public ReferenceVariable newInstanceOf(ReferenceVariable cls) {
return newInstanceOfImpl(cls);
}
/**
* Returns a reference variable representing a static Java field. The implementation must ensure that there is only one
* such representation for each static field.
*
* @param field,
* must be a static field
*/
public ReferenceVariable staticField(String className, String fieldName) {
return staticFieldImpl(className, fieldName);
}
/**
* Returns a variable representing a non-existing Java field, used by e.g., java.lang.Class: getSingers, setSigners
* java.lang.Class: getProtectionDomain0, setProtectionDomain0
*
* To simplify simulation, the temporary field variable is like a static field.
*
* The temporary fields are uniquely indexed by signatures.
*/
public ReferenceVariable tempField(String fieldsig) {
return tempFieldImpl(fieldsig);
}
/**
* Make a temporary variable. It is used for assignment where both sides are complex variables. e.g., for java.lang.System
* arraycopy(src, ..., dst, ...) instead of make an expression : dst[] = src[], it introduces a temporary variable t =
* src[] dst[] = t
*
* The temporary variable has to be unique.
*/
public ReferenceVariable tempVariable() {
return tempVariableImpl();
}
public ReferenceVariable tempLocalVariable(SootMethod method) {
return tempLocalVariableImpl(method);
}
/**
* Sub classes should implement both.
*/
protected abstract void assignImpl(ReferenceVariable lhs, ReferenceVariable rhs);
protected abstract void assignObjectToImpl(ReferenceVariable lhs, AbstractObject obj);
protected abstract void throwExceptionImpl(AbstractObject obj);
protected abstract ReferenceVariable arrayElementOfImpl(ReferenceVariable base);
protected abstract ReferenceVariable cloneObjectImpl(ReferenceVariable source);
protected abstract ReferenceVariable newInstanceOfImpl(ReferenceVariable cls);
protected abstract ReferenceVariable staticFieldImpl(String className, String fieldName);
protected abstract ReferenceVariable tempFieldImpl(String fieldsig);
protected abstract ReferenceVariable tempVariableImpl();
protected abstract ReferenceVariable tempLocalVariableImpl(SootMethod method);
}
| 4,933
| 33.746479
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/pointer/util/NativeMethodDriver.java
|
package soot.jimple.toolkits.pointer.util;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootMethod;
import soot.jimple.toolkits.pointer.nativemethods.JavaIoFileDescriptorNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaIoFileInputStreamNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaIoFileOutputStreamNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaIoFileSystemNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaIoObjectInputStreamNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaIoObjectOutputStreamNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaIoObjectStreamClassNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangClassLoaderNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangClassLoaderNativeLibraryNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangClassNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangDoubleNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangFloatNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangObjectNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangPackageNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangReflectArrayNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangReflectConstructorNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangReflectFieldNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangReflectMethodNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangReflectProxyNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangRuntimeNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangSecurityManagerNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangShutdownNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangStrictMathNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangStringNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangSystemNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangThreadNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaLangThrowableNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaNetInetAddressImplNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaNetInetAddressNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaSecurityAccessControllerNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaUtilJarJarFileNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaUtilResourceBundleNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaUtilTimeZoneNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaUtilZipCRC32Native;
import soot.jimple.toolkits.pointer.nativemethods.JavaUtilZipInflaterNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaUtilZipZipEntryNative;
import soot.jimple.toolkits.pointer.nativemethods.JavaUtilZipZipFileNative;
import soot.jimple.toolkits.pointer.nativemethods.NativeMethodClass;
import soot.jimple.toolkits.pointer.nativemethods.NativeMethodNotSupportedException;
import soot.jimple.toolkits.pointer.nativemethods.SunMiscSignalHandlerNative;
import soot.jimple.toolkits.pointer.nativemethods.SunMiscSignalNative;
import soot.jimple.toolkits.pointer.nativemethods.SunMiscUnsafeNative;
import soot.jimple.toolkits.pointer.representations.ReferenceVariable;
public class NativeMethodDriver {
private static final Logger logger = LoggerFactory.getLogger(NativeMethodDriver.class);
public NativeMethodDriver(NativeHelper helper) {
cnameToSim.put("java.lang.Object", new JavaLangObjectNative(helper));
cnameToSim.put("java.lang.System", new JavaLangSystemNative(helper));
cnameToSim.put("java.lang.Runtime", new JavaLangRuntimeNative(helper));
cnameToSim.put("java.lang.Shutdown", new JavaLangShutdownNative(helper));
cnameToSim.put("java.lang.String", new JavaLangStringNative(helper));
cnameToSim.put("java.lang.Float", new JavaLangFloatNative(helper));
cnameToSim.put("java.lang.Double", new JavaLangDoubleNative(helper));
cnameToSim.put("java.lang.StrictMath", new JavaLangStrictMathNative(helper));
cnameToSim.put("java.lang.Throwable", new JavaLangThrowableNative(helper));
cnameToSim.put("java.lang.Class", new JavaLangClassNative(helper));
cnameToSim.put("java.lang.Package", new JavaLangPackageNative(helper));
cnameToSim.put("java.lang.Thread", new JavaLangThreadNative(helper));
cnameToSim.put("java.lang.ClassLoader", new JavaLangClassLoaderNative(helper));
cnameToSim.put("java.lang.ClassLoader$NativeLibrary", new JavaLangClassLoaderNativeLibraryNative(helper));
cnameToSim.put("java.lang.SecurityManager", new JavaLangSecurityManagerNative(helper));
cnameToSim.put("java.lang.reflect.Field", new JavaLangReflectFieldNative(helper));
cnameToSim.put("java.lang.reflect.Array", new JavaLangReflectArrayNative(helper));
cnameToSim.put("java.lang.reflect.Method", new JavaLangReflectMethodNative(helper));
cnameToSim.put("java.lang.reflect.Constructor", new JavaLangReflectConstructorNative(helper));
cnameToSim.put("java.lang.reflect.Proxy", new JavaLangReflectProxyNative(helper));
cnameToSim.put("java.io.FileInputStream", new JavaIoFileInputStreamNative(helper));
cnameToSim.put("java.io.FileOutputStream", new JavaIoFileOutputStreamNative(helper));
cnameToSim.put("java.io.ObjectInputStream", new JavaIoObjectInputStreamNative(helper));
cnameToSim.put("java.io.ObjectOutputStream", new JavaIoObjectOutputStreamNative(helper));
cnameToSim.put("java.io.ObjectStreamClass", new JavaIoObjectStreamClassNative(helper));
cnameToSim.put("java.io.FileSystem", new JavaIoFileSystemNative(helper));
cnameToSim.put("java.io.FileDescriptor", new JavaIoFileDescriptorNative(helper));
cnameToSim.put("java.util.ResourceBundle", new JavaUtilResourceBundleNative(helper));
cnameToSim.put("java.util.TimeZone", new JavaUtilTimeZoneNative(helper));
cnameToSim.put("java.util.jar.JarFile", new JavaUtilJarJarFileNative(helper));
cnameToSim.put("java.util.zip.CRC32", new JavaUtilZipCRC32Native(helper));
cnameToSim.put("java.util.zip.Inflater", new JavaUtilZipInflaterNative(helper));
cnameToSim.put("java.util.zip.ZipFile", new JavaUtilZipZipFileNative(helper));
cnameToSim.put("java.util.zip.ZipEntry", new JavaUtilZipZipEntryNative(helper));
cnameToSim.put("java.security.AccessController", new JavaSecurityAccessControllerNative(helper));
cnameToSim.put("java.net.InetAddress", new JavaNetInetAddressNative(helper));
cnameToSim.put("java.net.InetAddressImpl", new JavaNetInetAddressImplNative(helper));
cnameToSim.put("sun.misc.Signal", new SunMiscSignalNative(helper));
cnameToSim.put("sun.misc.NativeSignalHandler", new SunMiscSignalHandlerNative(helper));
cnameToSim.put("sun.misc.Unsafe", new SunMiscUnsafeNative(helper));
}
protected final HashMap<String, NativeMethodClass> cnameToSim = new HashMap<String, NativeMethodClass>(100);
private final boolean DEBUG = false;
/**
* The entry point of native method simulation.
*
* @param method,
* must be a native method
* @param thisVar,
* the variable represent @this, it can be null if the method is static
* @param returnVar,
* the variable represent @return it is null if the method has no return
* @param params,
* array of parameters.
*/
public boolean process(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar,
ReferenceVariable params[]) {
String cname = method.getDeclaringClass().getName();
NativeMethodClass clsSim = cnameToSim.get(cname);
// logger.debug(""+method.toString());
if (clsSim == null) {
// logger.warn("it is unsafe to simulate the method ");
// logger.debug(" "+method.toString());
// throw new NativeMethodNotSupportedException(method);
return false;
} else {
try {
clsSim.simulateMethod(method, thisVar, returnVar, params);
return true;
} catch (NativeMethodNotSupportedException e) {
if (DEBUG) {
logger.warn("it is unsafe to simulate the method ");
logger.debug(" " + method.toString());
}
}
return false;
}
}
}
| 9,195
| 52.777778
| 110
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/reflection/ConstantInvokeMethodBaseTransformer.java
|
package soot.jimple.toolkits.reflection;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.Local;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.InvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.util.Chain;
/**
* This class creates a local for each string constant that is used as a base object to a reflective Method.invoke call.
* Therefore, {@link soot.jimple.toolkits.callgraph.OnFlyCallGraphBuilder.TypeBasedReflectionModel} can handle such cases and
* extend the call graph for edges to the specific java.lang.String method invoked by the reflective call.
*
* @author Manuel Benz created on 02.08.17
*/
public class ConstantInvokeMethodBaseTransformer extends SceneTransformer {
private static final Logger logger = LoggerFactory.getLogger(ConstantInvokeMethodBaseTransformer.class);
private final static String INVOKE_SIG =
"<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>";
public ConstantInvokeMethodBaseTransformer(Singletons.Global g) {
}
public static ConstantInvokeMethodBaseTransformer v() {
return G.v().soot_jimple_toolkits_reflection_ConstantInvokeMethodBaseTransformer();
}
@Override
protected void internalTransform(String phaseName, Map<String, String> options) {
final boolean verbose = options.containsKey("verbose");
final Jimple jimp = Jimple.v();
for (SootClass sootClass : Scene.v().getApplicationClasses()) {
// In some rare cases we will have application classes that are not resolved due to being located in excluded packages
// (e.g., the ServiceConnection class constructed by FlowDroid:
// soot.jimple.infoflow.cfg.LibraryClassPatcher#patchServiceConnection)
if (sootClass.resolvingLevel() < SootClass.BODIES) {
continue;
}
for (SootMethod sootMethod : sootClass.getMethods()) {
Body body = sootMethod.retrieveActiveBody();
final Chain<Local> locals = body.getLocals();
final Chain<Unit> units = body.getUnits();
for (Iterator<Unit> iterator = units.snapshotIterator(); iterator.hasNext();) {
Stmt s = (Stmt) iterator.next();
if (s.containsInvokeExpr()) {
InvokeExpr invokeExpr = s.getInvokeExpr();
if (INVOKE_SIG.equals(invokeExpr.getMethod().getSignature())) {
Value arg0 = invokeExpr.getArg(0);
if (arg0 instanceof StringConstant) {
Local newLocal = jimp.newLocal("sc" + locals.size(), arg0.getType());
locals.add(newLocal);
units.insertBefore(jimp.newAssignStmt(newLocal, (StringConstant) arg0), s);
invokeExpr.setArg(0, newLocal);
if (verbose) {
logger.debug("Replaced constant base object of Method.invoke() by local in: " + sootMethod.toString());
}
}
}
}
}
}
}
}
}
| 4,028
| 36.654206
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/reflection/ReflInliner.java
|
package soot.jimple.toolkits.reflection;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2011 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.CompilationDeathException;
import soot.PackManager;
import soot.Scene;
import soot.SootClass;
import soot.Transform;
import soot.options.Options;
import soot.rtlib.tamiflex.DefaultHandler;
import soot.rtlib.tamiflex.IUnexpectedReflectiveCallHandler;
import soot.rtlib.tamiflex.OpaquePredicate;
import soot.rtlib.tamiflex.ReflectiveCalls;
import soot.rtlib.tamiflex.SootSig;
import soot.rtlib.tamiflex.UnexpectedReflectiveCall;
public class ReflInliner {
private static final Logger logger = LoggerFactory.getLogger(ReflInliner.class);
public static void main(String[] args) {
PackManager.v().getPack("wjpp").add(new Transform("wjpp.inlineReflCalls", new ReflectiveCallsInliner()));
final Scene scene = Scene.v();
scene.addBasicClass(Object.class.getName());
scene.addBasicClass(SootSig.class.getName(), SootClass.BODIES);
scene.addBasicClass(UnexpectedReflectiveCall.class.getName(), SootClass.BODIES);
scene.addBasicClass(IUnexpectedReflectiveCallHandler.class.getName(), SootClass.BODIES);
scene.addBasicClass(DefaultHandler.class.getName(), SootClass.BODIES);
scene.addBasicClass(OpaquePredicate.class.getName(), SootClass.BODIES);
scene.addBasicClass(ReflectiveCalls.class.getName(), SootClass.BODIES);
ArrayList<String> argList = new ArrayList<String>(Arrays.asList(args));
argList.add("-w");
argList.add("-p");
argList.add("cg");
argList.add("enabled:false");
argList.add("-app");
Options.v().set_keep_line_number(true);
logger.debug("TamiFlex Booster Version " + ReflInliner.class.getPackage().getImplementationVersion());
try {
soot.Main.main(argList.toArray(new String[0]));
} catch (CompilationDeathException e) {
logger.debug("\nERROR: " + e.getMessage() + "\n");
logger.debug(
"The command-line options are described at:\n" + "http://www.sable.mcgill.ca/soot/tutorial/usage/index.html");
if (Options.v().verbose()) {
throw e;
} else {
logger.debug("Use -verbose to see stack trace.");
}
usage();
}
}
private static void usage() {
logger.debug(Options.v().getUsage());
}
}
| 3,115
| 34.409091
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/reflection/ReflectionTraceInfo.java
|
package soot.jimple.toolkits.reflection;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2010 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.tagkit.Host;
import soot.tagkit.LineNumberTag;
import soot.tagkit.SourceLnPosTag;
public class ReflectionTraceInfo {
private static final Logger logger = LoggerFactory.getLogger(ReflectionTraceInfo.class);
public enum Kind {
ClassForName, ClassNewInstance, ConstructorNewInstance, MethodInvoke, FieldSet, FieldGet
}
protected final Map<SootMethod, Set<String>> classForNameReceivers;
protected final Map<SootMethod, Set<String>> classNewInstanceReceivers;
protected final Map<SootMethod, Set<String>> constructorNewInstanceReceivers;
protected final Map<SootMethod, Set<String>> methodInvokeReceivers;
protected final Map<SootMethod, Set<String>> fieldSetReceivers;
protected final Map<SootMethod, Set<String>> fieldGetReceivers;
public ReflectionTraceInfo(String logFile) {
this.classForNameReceivers = new LinkedHashMap<SootMethod, Set<String>>();
this.classNewInstanceReceivers = new LinkedHashMap<SootMethod, Set<String>>();
this.constructorNewInstanceReceivers = new LinkedHashMap<SootMethod, Set<String>>();
this.methodInvokeReceivers = new LinkedHashMap<SootMethod, Set<String>>();
this.fieldSetReceivers = new LinkedHashMap<SootMethod, Set<String>>();
this.fieldGetReceivers = new LinkedHashMap<SootMethod, Set<String>>();
if (logFile == null) {
throw new InternalError("Trace based refection model enabled but no trace file given!?");
} else {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFile)))) {
final Scene sc = Scene.v();
final Set<String> ignoredKinds = new HashSet<String>();
for (String line; (line = reader.readLine()) != null;) {
if (line.isEmpty()) {
continue;
}
final String[] portions = line.split(";", -1);
final String kind = portions[0];
final String target = portions[1];
final String source = portions[2];
final int lineNumber = portions[3].length() == 0 ? -1 : Integer.parseInt(portions[3]);
for (SootMethod sourceMethod : inferSource(source, lineNumber)) {
switch (kind) {
case "Class.forName": {
Set<String> receiverNames = classForNameReceivers.get(sourceMethod);
if (receiverNames == null) {
classForNameReceivers.put(sourceMethod, receiverNames = new LinkedHashSet<String>());
}
receiverNames.add(target);
break;
}
case "Class.newInstance": {
Set<String> receiverNames = classNewInstanceReceivers.get(sourceMethod);
if (receiverNames == null) {
classNewInstanceReceivers.put(sourceMethod, receiverNames = new LinkedHashSet<String>());
}
receiverNames.add(target);
break;
}
case "Method.invoke": {
if (!sc.containsMethod(target)) {
throw new RuntimeException("Unknown method for signature: " + target);
}
Set<String> receiverNames = methodInvokeReceivers.get(sourceMethod);
if (receiverNames == null) {
methodInvokeReceivers.put(sourceMethod, receiverNames = new LinkedHashSet<String>());
}
receiverNames.add(target);
break;
}
case "Constructor.newInstance": {
if (!sc.containsMethod(target)) {
throw new RuntimeException("Unknown method for signature: " + target);
}
Set<String> receiverNames = constructorNewInstanceReceivers.get(sourceMethod);
if (receiverNames == null) {
constructorNewInstanceReceivers.put(sourceMethod, receiverNames = new LinkedHashSet<String>());
}
receiverNames.add(target);
break;
}
case "Field.set*": {
if (!sc.containsField(target)) {
throw new RuntimeException("Unknown method for signature: " + target);
}
Set<String> receiverNames = fieldSetReceivers.get(sourceMethod);
if (receiverNames == null) {
fieldSetReceivers.put(sourceMethod, receiverNames = new LinkedHashSet<String>());
}
receiverNames.add(target);
break;
}
case "Field.get*": {
if (!sc.containsField(target)) {
throw new RuntimeException("Unknown method for signature: " + target);
}
Set<String> receiverNames = fieldGetReceivers.get(sourceMethod);
if (receiverNames == null) {
fieldGetReceivers.put(sourceMethod, receiverNames = new LinkedHashSet<String>());
}
receiverNames.add(target);
break;
}
default:
ignoredKinds.add(kind);
break;
}
}
}
if (!ignoredKinds.isEmpty()) {
logger.debug("Encountered reflective calls entries of the following kinds that\ncannot currently be handled:");
for (String kind : ignoredKinds) {
logger.debug(kind);
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("Trace file not found.", e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private Set<SootMethod> inferSource(String source, int lineNumber) {
int dotIndex = source.lastIndexOf('.');
String className = source.substring(0, dotIndex);
String methodName = source.substring(dotIndex + 1);
final Scene scene = Scene.v();
if (!scene.containsClass(className)) {
scene.addBasicClass(className, SootClass.BODIES);
scene.loadBasicClasses();
if (!scene.containsClass(className)) {
throw new RuntimeException("Trace file refers to unknown class: " + className);
}
}
Set<SootMethod> methodsWithRightName = new LinkedHashSet<SootMethod>();
for (SootMethod m : scene.getSootClass(className).getMethods()) {
if (m.isConcrete() && m.getName().equals(methodName)) {
methodsWithRightName.add(m);
}
}
if (methodsWithRightName.isEmpty()) {
throw new RuntimeException("Trace file refers to unknown method with name " + methodName + " in Class " + className);
} else if (methodsWithRightName.size() == 1) {
return Collections.singleton(methodsWithRightName.iterator().next());
} else {
// more than one method with that name
for (SootMethod sootMethod : methodsWithRightName) {
if (coversLineNumber(lineNumber, sootMethod)) {
return Collections.singleton(sootMethod);
}
if (sootMethod.isConcrete()) {
if (!sootMethod.hasActiveBody()) {
sootMethod.retrieveActiveBody();
}
Body body = sootMethod.getActiveBody();
if (coversLineNumber(lineNumber, body)) {
return Collections.singleton(sootMethod);
}
for (Unit u : body.getUnits()) {
if (coversLineNumber(lineNumber, u)) {
return Collections.singleton(sootMethod);
}
}
}
}
// if we get here then we found no method with the right line number information;
// be conservative and return all method that we found
return methodsWithRightName;
}
}
private boolean coversLineNumber(int lineNumber, Host host) {
{
SourceLnPosTag tag = (SourceLnPosTag) host.getTag(SourceLnPosTag.NAME);
if (tag != null) {
if (tag.startLn() <= lineNumber && tag.endLn() >= lineNumber) {
return true;
}
}
}
{
LineNumberTag tag = (LineNumberTag) host.getTag(LineNumberTag.NAME);
if (tag != null) {
if (tag.getLineNumber() == lineNumber) {
return true;
}
}
}
return false;
}
public Set<String> classForNameClassNames(SootMethod container) {
Set<String> ret = classForNameReceivers.get(container);
return (ret != null) ? ret : Collections.emptySet();
}
public Set<SootClass> classForNameClasses(SootMethod container) {
Set<SootClass> result = new LinkedHashSet<SootClass>();
for (String className : classForNameClassNames(container)) {
result.add(Scene.v().getSootClass(className));
}
return result;
}
public Set<String> classNewInstanceClassNames(SootMethod container) {
Set<String> ret = classNewInstanceReceivers.get(container);
return (ret != null) ? ret : Collections.emptySet();
}
public Set<SootClass> classNewInstanceClasses(SootMethod container) {
Set<SootClass> result = new LinkedHashSet<SootClass>();
for (String className : classNewInstanceClassNames(container)) {
result.add(Scene.v().getSootClass(className));
}
return result;
}
public Set<String> constructorNewInstanceSignatures(SootMethod container) {
Set<String> ret = constructorNewInstanceReceivers.get(container);
return (ret != null) ? ret : Collections.emptySet();
}
public Set<SootMethod> constructorNewInstanceConstructors(SootMethod container) {
Set<SootMethod> result = new LinkedHashSet<SootMethod>();
for (String signature : constructorNewInstanceSignatures(container)) {
result.add(Scene.v().getMethod(signature));
}
return result;
}
public Set<String> methodInvokeSignatures(SootMethod container) {
Set<String> ret = methodInvokeReceivers.get(container);
return (ret != null) ? ret : Collections.emptySet();
}
public Set<SootMethod> methodInvokeMethods(SootMethod container) {
Set<SootMethod> result = new LinkedHashSet<SootMethod>();
for (String signature : methodInvokeSignatures(container)) {
result.add(Scene.v().getMethod(signature));
}
return result;
}
public Set<SootMethod> methodsContainingReflectiveCalls() {
Set<SootMethod> res = new LinkedHashSet<SootMethod>();
res.addAll(classForNameReceivers.keySet());
res.addAll(classNewInstanceReceivers.keySet());
res.addAll(constructorNewInstanceReceivers.keySet());
res.addAll(methodInvokeReceivers.keySet());
return res;
}
public Set<String> fieldSetSignatures(SootMethod container) {
Set<String> ret = fieldSetReceivers.get(container);
return (ret != null) ? ret : Collections.emptySet();
}
public Set<String> fieldGetSignatures(SootMethod container) {
Set<String> ret = fieldGetReceivers.get(container);
return (ret != null) ? ret : Collections.emptySet();
}
}
| 12,128
| 37.875
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/reflection/ReflectiveCallsInliner.java
|
package soot.jimple.toolkits.reflection;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2010 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.ArrayType;
import soot.Body;
import soot.BooleanType;
import soot.Local;
import soot.LocalGenerator;
import soot.Modifier;
import soot.PatchingChain;
import soot.PhaseOptions;
import soot.PrimType;
import soot.RefLikeType;
import soot.RefType;
import soot.Scene;
import soot.SceneTransformer;
import soot.SootClass;
import soot.SootField;
import soot.SootFieldRef;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.VoidType;
import soot.javaToJimple.DefaultLocalGenerator;
import soot.jimple.AssignStmt;
import soot.jimple.ClassConstant;
import soot.jimple.FieldRef;
import soot.jimple.GotoStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.toolkits.reflection.ReflectionTraceInfo.Kind;
import soot.jimple.toolkits.scalar.CopyPropagator;
import soot.jimple.toolkits.scalar.DeadAssignmentEliminator;
import soot.jimple.toolkits.scalar.NopEliminator;
import soot.options.CGOptions;
import soot.options.Options;
import soot.rtlib.tamiflex.DefaultHandler;
import soot.rtlib.tamiflex.IUnexpectedReflectiveCallHandler;
import soot.rtlib.tamiflex.OpaquePredicate;
import soot.rtlib.tamiflex.ReflectiveCalls;
import soot.rtlib.tamiflex.SootSig;
import soot.rtlib.tamiflex.UnexpectedReflectiveCall;
import soot.toolkits.scalar.UnusedLocalEliminator;
import soot.util.Chain;
import soot.util.HashChain;
public class ReflectiveCallsInliner extends SceneTransformer {
private static final String ALREADY_CHECKED_FIELDNAME = "SOOT$Reflection$alreadyChecked";
private static final List<String> fieldSets
= Arrays.asList("set", "setBoolean", "setByte", "setChar", "setInt", "setLong", "setFloat", "setDouble", "setShort");
private static final List<String> fieldGets
= Arrays.asList("get", "getBoolean", "getByte", "getChar", "getInt", "getLong", "getFloat", "getDouble", "getShort");
// caching currently does not work because it adds fields to Class, Method and Constructor,
// but such fields cannot currently be added using the Instrumentation API
private static final boolean useCaching = false;
private ReflectionTraceInfo RTI;
private SootMethodRef UNINTERPRETED_METHOD;
private boolean initialized = false;
private int callSiteId;
private int callNum;
private SootClass reflectiveCallsClass;
@Override
protected void internalTransform(String phaseName, Map<String, String> options) {
if (!this.initialized) {
final CGOptions cgOptions = new CGOptions(PhaseOptions.v().getPhaseOptions("cg"));
this.RTI = new ReflectionTraceInfo(cgOptions.reflection_log());
final Scene scene = Scene.v();
scene.getSootClass(SootSig.class.getName()).setApplicationClass();
scene.getSootClass(UnexpectedReflectiveCall.class.getName()).setApplicationClass();
scene.getSootClass(IUnexpectedReflectiveCallHandler.class.getName()).setApplicationClass();
scene.getSootClass(DefaultHandler.class.getName()).setApplicationClass();
scene.getSootClass(OpaquePredicate.class.getName()).setApplicationClass();
scene.getSootClass(ReflectiveCalls.class.getName()).setApplicationClass();
SootClass reflectiveCallsClass = new SootClass("soot.rtlib.tamiflex.ReflectiveCallsWrapper", Modifier.PUBLIC);
scene.addClass(reflectiveCallsClass);
reflectiveCallsClass.setApplicationClass();
this.reflectiveCallsClass = reflectiveCallsClass;
this.UNINTERPRETED_METHOD = scene.makeMethodRef(scene.getSootClass("soot.rtlib.tamiflex.OpaquePredicate"), "getFalse",
Collections.emptyList(), BooleanType.v(), true);
if (useCaching) {
addCaching();
}
initializeReflectiveCallsTable();
this.callSiteId = 0;
this.callNum = 0;
this.initialized = true;
}
final boolean validate = Options.v().validate();
for (SootMethod m : RTI.methodsContainingReflectiveCalls()) {
Body b = m.retrieveActiveBody();
{
Set<String> classForNameClassNames = RTI.classForNameClassNames(m);
if (!classForNameClassNames.isEmpty()) {
inlineRelectiveCalls(m, classForNameClassNames, ReflectionTraceInfo.Kind.ClassForName);
if (validate) {
b.validate();
}
}
}
{
Set<String> classNewInstanceClassNames = RTI.classNewInstanceClassNames(m);
if (!classNewInstanceClassNames.isEmpty()) {
inlineRelectiveCalls(m, classNewInstanceClassNames, ReflectionTraceInfo.Kind.ClassNewInstance);
if (validate) {
b.validate();
}
}
}
{
Set<String> constructorNewInstanceSignatures = RTI.constructorNewInstanceSignatures(m);
if (!constructorNewInstanceSignatures.isEmpty()) {
inlineRelectiveCalls(m, constructorNewInstanceSignatures, ReflectionTraceInfo.Kind.ConstructorNewInstance);
if (validate) {
b.validate();
}
}
}
{
Set<String> methodInvokeSignatures = RTI.methodInvokeSignatures(m);
if (!methodInvokeSignatures.isEmpty()) {
inlineRelectiveCalls(m, methodInvokeSignatures, ReflectionTraceInfo.Kind.MethodInvoke);
if (validate) {
b.validate();
}
}
}
{
Set<String> fieldSetSignatures = RTI.fieldSetSignatures(m);
if (!fieldSetSignatures.isEmpty()) {
inlineRelectiveCalls(m, fieldSetSignatures, ReflectionTraceInfo.Kind.FieldSet);
if (validate) {
b.validate();
}
}
}
{
Set<String> fieldGetSignatures = RTI.fieldGetSignatures(m);
if (!fieldGetSignatures.isEmpty()) {
inlineRelectiveCalls(m, fieldGetSignatures, ReflectionTraceInfo.Kind.FieldGet);
if (validate) {
b.validate();
}
}
}
// clean up after us
cleanup(b);
}
}
private void cleanup(Body b) {
CopyPropagator.v().transform(b);
DeadAssignmentEliminator.v().transform(b);
UnusedLocalEliminator.v().transform(b);
NopEliminator.v().transform(b);
}
private void initializeReflectiveCallsTable() {
final Jimple jimp = Jimple.v();
final Scene scene = Scene.v();
final SootClass reflCallsClass = scene.getSootClass("soot.rtlib.tamiflex.ReflectiveCalls");
final Body body = reflCallsClass.getMethodByName(SootMethod.staticInitializerName).retrieveActiveBody();
final LocalGenerator localGen = scene.createLocalGenerator(body);
final Chain<Unit> newUnits = new HashChain<>();
final SootClass sootClassSet = scene.getSootClass("java.util.Set");
final RefType refTypeSet = sootClassSet.getType();
final SootMethodRef addMethodRef = sootClassSet.getMethodByName("add").makeRef();
int callSiteId = 0;
for (SootMethod m : RTI.methodsContainingReflectiveCalls()) {
if (!RTI.classForNameClassNames(m).isEmpty()) {
SootFieldRef fieldRef = scene.makeFieldRef(reflCallsClass, "classForName", refTypeSet, true);
Local setLocal = localGen.generateLocal(refTypeSet);
newUnits.add(jimp.newAssignStmt(setLocal, jimp.newStaticFieldRef(fieldRef)));
for (String className : RTI.classForNameClassNames(m)) {
InterfaceInvokeExpr invokeExpr
= jimp.newInterfaceInvokeExpr(setLocal, addMethodRef, StringConstant.v(callSiteId + className));
newUnits.add(jimp.newInvokeStmt(invokeExpr));
}
callSiteId++;
}
if (!RTI.classNewInstanceClassNames(m).isEmpty()) {
SootFieldRef fieldRef = scene.makeFieldRef(reflCallsClass, "classNewInstance", refTypeSet, true);
Local setLocal = localGen.generateLocal(refTypeSet);
newUnits.add(jimp.newAssignStmt(setLocal, jimp.newStaticFieldRef(fieldRef)));
for (String className : RTI.classNewInstanceClassNames(m)) {
InterfaceInvokeExpr invokeExpr
= jimp.newInterfaceInvokeExpr(setLocal, addMethodRef, StringConstant.v(callSiteId + className));
newUnits.add(jimp.newInvokeStmt(invokeExpr));
}
callSiteId++;
}
if (!RTI.constructorNewInstanceSignatures(m).isEmpty()) {
SootFieldRef fieldRef = scene.makeFieldRef(reflCallsClass, "constructorNewInstance", refTypeSet, true);
Local setLocal = localGen.generateLocal(refTypeSet);
newUnits.add(jimp.newAssignStmt(setLocal, jimp.newStaticFieldRef(fieldRef)));
for (String constrSig : RTI.constructorNewInstanceSignatures(m)) {
InterfaceInvokeExpr invokeExpr
= jimp.newInterfaceInvokeExpr(setLocal, addMethodRef, StringConstant.v(callSiteId + constrSig));
newUnits.add(jimp.newInvokeStmt(invokeExpr));
}
callSiteId++;
}
if (!RTI.methodInvokeSignatures(m).isEmpty()) {
SootFieldRef fieldRef = scene.makeFieldRef(reflCallsClass, "methodInvoke", refTypeSet, true);
Local setLocal = localGen.generateLocal(refTypeSet);
newUnits.add(jimp.newAssignStmt(setLocal, jimp.newStaticFieldRef(fieldRef)));
for (String methodSig : RTI.methodInvokeSignatures(m)) {
InterfaceInvokeExpr invokeExpr
= jimp.newInterfaceInvokeExpr(setLocal, addMethodRef, StringConstant.v(callSiteId + methodSig));
newUnits.add(jimp.newInvokeStmt(invokeExpr));
}
callSiteId++;
}
}
PatchingChain<Unit> units = body.getUnits();
units.insertAfter(newUnits, units.getPredOf(units.getLast()));
if (Options.v().validate()) {
body.validate();
}
}
private void addCaching() {
final Scene scene = Scene.v();
final BooleanType bt = BooleanType.v();
scene.getSootClass("java.lang.reflect.Method").addField(scene.makeSootField(ALREADY_CHECKED_FIELDNAME, bt));
scene.getSootClass("java.lang.reflect.Constructor").addField(scene.makeSootField(ALREADY_CHECKED_FIELDNAME, bt));
scene.getSootClass("java.lang.Class").addField(scene.makeSootField(ALREADY_CHECKED_FIELDNAME, bt));
for (Kind k : Kind.values()) {
addCaching(k);
}
}
private void addCaching(Kind kind) {
final Scene scene = Scene.v();
SootClass c;
String methodName;
switch (kind) {
case ClassNewInstance:
c = scene.getSootClass("java.lang.Class");
methodName = "knownClassNewInstance";
break;
case ConstructorNewInstance:
c = scene.getSootClass("java.lang.reflect.Constructor");
methodName = "knownConstructorNewInstance";
break;
case MethodInvoke:
c = scene.getSootClass("java.lang.reflect.Method");
methodName = "knownMethodInvoke";
break;
case ClassForName:
// Cannot implement caching in this case because we can add no field
// to the String argument
return;
default:
throw new IllegalStateException("unknown kind: " + kind);
}
final SootMethod m = scene.getSootClass("soot.rtlib.tamiflex.ReflectiveCalls").getMethodByName(methodName);
final JimpleBody body = (JimpleBody) m.retrieveActiveBody();
final Chain<Unit> units = body.getUnits();
final Unit firstStmt = units.getPredOf(body.getFirstNonIdentityStmt());
final Chain<Unit> newUnits = new HashChain<>();
final BooleanType bt = BooleanType.v();
final Jimple jimp = Jimple.v();
// alreadyCheckedLocal = m.alreadyChecked
InstanceFieldRef fieldRef = jimp.newInstanceFieldRef(body.getParameterLocal(m.getParameterCount() - 1),
scene.makeFieldRef(c, ALREADY_CHECKED_FIELDNAME, bt, false));
LocalGenerator localGen = scene.createLocalGenerator(body);
Local alreadyCheckedLocal = localGen.generateLocal(bt);
newUnits.add(jimp.newAssignStmt(alreadyCheckedLocal, fieldRef));
// if(!alreadyChecked) goto jumpTarget
Stmt jumpTarget = jimp.newNopStmt();
newUnits.add(jimp.newIfStmt(jimp.newEqExpr(alreadyCheckedLocal, IntConstant.v(0)), jumpTarget));
// return
newUnits.add(jimp.newReturnVoidStmt());
// jumpTarget: nop
newUnits.add(jumpTarget);
// m.alreadyChecked = true
newUnits.add(jimp.newAssignStmt(jimp.newInstanceFieldRef(body.getParameterLocal(m.getParameterCount() - 1),
scene.makeFieldRef(c, ALREADY_CHECKED_FIELDNAME, bt, false)), IntConstant.v(1)));
units.insertAfter(newUnits, firstStmt);
if (Options.v().validate()) {
body.validate();
}
}
private void inlineRelectiveCalls(SootMethod m, Set<String> targets, Kind callKind) {
final Body b = m.retrieveActiveBody();
final Chain<Unit> units = b.getUnits();
final Scene scene = Scene.v();
final LocalGenerator localGen = scene.createLocalGenerator(b);
final Jimple jimp = Jimple.v();
// for all units
for (Iterator<Unit> iter = units.snapshotIterator(); iter.hasNext();) {
Stmt s = (Stmt) iter.next();
Chain<Unit> newUnits = new HashChain<>();
// if we have an invoke expression, test to see if it is a
// reflective invoke expression
if (s.containsInvokeExpr()) {
InvokeExpr ie = s.getInvokeExpr();
boolean found = false;
Type fieldSetGetType = null;
if (callKind == Kind.ClassForName
&& ("<java.lang.Class: java.lang.Class forName(java.lang.String)>".equals(ie.getMethodRef().getSignature())
|| "<java.lang.Class: java.lang.Class forName(java.lang.String,boolean,java.lang.ClassLoader)>"
.equals(ie.getMethodRef().getSignature()))) {
found = true;
Value classNameValue = ie.getArg(0);
newUnits.add(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(scene
.getMethod("<soot.rtlib.tamiflex.ReflectiveCalls: void knownClassForName(int,java.lang.String)>").makeRef(),
IntConstant.v(callSiteId), classNameValue)));
} else if (callKind == Kind.ClassNewInstance
&& "<java.lang.Class: java.lang.Object newInstance()>".equals(ie.getMethodRef().getSignature())) {
found = true;
Local classLocal = (Local) ((InstanceInvokeExpr) ie).getBase();
newUnits.add(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(scene
.getMethod("<soot.rtlib.tamiflex.ReflectiveCalls: void knownClassNewInstance(int,java.lang.Class)>").makeRef(),
IntConstant.v(callSiteId), classLocal)));
} else if (callKind == Kind.ConstructorNewInstance
&& "<java.lang.reflect.Constructor: java.lang.Object newInstance(java.lang.Object[])>"
.equals(ie.getMethodRef().getSignature())) {
found = true;
Local constrLocal = (Local) ((InstanceInvokeExpr) ie).getBase();
newUnits.add(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(scene.getMethod(
"<soot.rtlib.tamiflex.ReflectiveCalls: void knownConstructorNewInstance(int,java.lang.reflect.Constructor)>")
.makeRef(), IntConstant.v(callSiteId), constrLocal)));
} else if (callKind == Kind.MethodInvoke
&& "<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>"
.equals(ie.getMethodRef().getSignature())) {
found = true;
Local methodLocal = (Local) ((InstanceInvokeExpr) ie).getBase();
Value recv = ie.getArg(0);
newUnits.add(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(scene.getMethod(
"<soot.rtlib.tamiflex.ReflectiveCalls: void knownMethodInvoke(int,java.lang.Object,java.lang.reflect.Method)>")
.makeRef(), IntConstant.v(callSiteId), recv, methodLocal)));
} else if (callKind == Kind.FieldSet) {
SootMethod sootMethod = ie.getMethodRef().resolve();
if ("java.lang.reflect.Field".equals(sootMethod.getDeclaringClass().getName())
&& fieldSets.contains(sootMethod.getName())) {
found = true;
// assign type of 2nd parameter (1st is receiver object)
fieldSetGetType = sootMethod.getParameterType(1);
Value recv = ie.getArg(0);
Value field = ((InstanceInvokeExpr) ie).getBase();
newUnits.add(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(scene.getMethod(
"<soot.rtlib.tamiflex.ReflectiveCalls: void knownFieldSet(int,java.lang.Object,java.lang.reflect.Field)>")
.makeRef(), IntConstant.v(callSiteId), recv, field)));
}
} else if (callKind == Kind.FieldGet) {
SootMethod sootMethod = ie.getMethodRef().resolve();
if ("java.lang.reflect.Field".equals(sootMethod.getDeclaringClass().getName())
&& fieldGets.contains(sootMethod.getName())) {
found = true;
// assign return type of get
fieldSetGetType = sootMethod.getReturnType();
Value recv = ie.getArg(0);
Value field = ((InstanceInvokeExpr) ie).getBase();
newUnits.add(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(scene.getMethod(
"<soot.rtlib.tamiflex.ReflectiveCalls: void knownFieldSet(int,java.lang.Object,java.lang.reflect.Field)>")
.makeRef(), IntConstant.v(callSiteId), recv, field)));
}
}
if (!found) {
continue;
}
final NopStmt endLabel = jimp.newNopStmt();
// for all recorded targets
for (String target : targets) {
NopStmt jumpTarget = jimp.newNopStmt();
// boolean predLocal = Opaque.getFalse();
Local predLocal = localGen.generateLocal(BooleanType.v());
newUnits.add(jimp.newAssignStmt(predLocal, jimp.newStaticInvokeExpr(UNINTERPRETED_METHOD)));
// if predLocal == 0 goto <original reflective call>
newUnits.add(jimp.newIfStmt(jimp.newEqExpr(IntConstant.v(0), predLocal), jumpTarget));
SootMethod newMethod = createNewMethod(callKind, target, fieldSetGetType);
List<Value> args = new LinkedList<>();
switch (callKind) {
case ClassForName:
case ClassNewInstance:
// no arguments
break;
case ConstructorNewInstance:
// add Object[] argument
args.add(ie.getArgs().get(0));
break;
case MethodInvoke:
// add Object argument
args.add(ie.getArgs().get(0));
// add Object[] argument
args.add(ie.getArgs().get(1));
break;
case FieldSet:
// add Object argument
args.add(ie.getArgs().get(0));
// add value argument
args.add(ie.getArgs().get(1));
break;
case FieldGet:
// add Object argument
args.add(ie.getArgs().get(0));
break;
default:
throw new IllegalStateException();
}
Local retLocal = localGen.generateLocal(newMethod.getReturnType());
newUnits.add(jimp.newAssignStmt(retLocal, jimp.newStaticInvokeExpr(newMethod.makeRef(), args)));
if (s instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) s;
newUnits.add(jimp.newAssignStmt(assignStmt.getLeftOp(), retLocal));
}
GotoStmt gotoStmt = jimp.newGotoStmt(endLabel);
newUnits.add(gotoStmt);
newUnits.add(jumpTarget);
}
Unit end = newUnits.getLast();
units.insertAfter(newUnits, s);
units.remove(s);
units.insertAfter(s, end);
units.insertAfter(endLabel, s);
}
}
callSiteId++;
}
private SootMethod createNewMethod(Kind callKind, String target, Type fieldSetGetType) {
List<Type> parameterTypes = new LinkedList<>();
Type returnType = null;
switch (callKind) {
case ClassForName:
returnType = RefType.v("java.lang.Class");
break;
case ClassNewInstance:
returnType = RefType.v("java.lang.Object");
break;
case ConstructorNewInstance:
returnType = RefType.v("java.lang.Object");
parameterTypes.add(ArrayType.v(returnType, 1));
break;
case MethodInvoke:
returnType = RefType.v("java.lang.Object");
parameterTypes.add(returnType);
parameterTypes.add(ArrayType.v(returnType, 1));
break;
case FieldSet:
returnType = VoidType.v();
parameterTypes.add(RefType.v("java.lang.Object"));
parameterTypes.add(fieldSetGetType);
break;
case FieldGet:
returnType = fieldSetGetType;
parameterTypes.add(RefType.v("java.lang.Object"));
break;
default:
throw new IllegalStateException();
}
final Jimple jimp = Jimple.v();
final Scene scene = Scene.v();
final SootMethod newMethod = scene.makeSootMethod("reflectiveCall" + (callNum++), parameterTypes, returnType,
Modifier.PUBLIC | Modifier.STATIC);
final Body newBody = jimp.newBody(newMethod);
newMethod.setActiveBody(newBody);
reflectiveCallsClass.addMethod(newMethod);
final PatchingChain<Unit> newUnits = newBody.getUnits();
final LocalGenerator localGen = scene.createLocalGenerator(newBody);
Local freshLocal;
Value replacement = null;
Local[] paramLocals = null;
switch (callKind) {
case ClassForName: {
// replace by: <Class constant for <target>>
freshLocal = localGen.generateLocal(RefType.v("java.lang.Class"));
replacement = ClassConstant.v(target.replace('.', '/'));
break;
}
case ClassNewInstance: {
// replace by: new <target>
RefType targetType = RefType.v(target);
freshLocal = localGen.generateLocal(targetType);
replacement = jimp.newNewExpr(targetType);
break;
}
case ConstructorNewInstance: {
/*
* replace r=constr.newInstance(args) by: Object p0 = args[0]; ... Object pn = args[n]; T0 a0 = (T0)p0; ... Tn an =
* (Tn)pn;
*/
SootMethod constructor = scene.getMethod(target);
paramLocals = new Local[constructor.getParameterCount()];
if (constructor.getParameterCount() > 0) {
// argArrayLocal = @parameter-0
ArrayType arrayType = ArrayType.v(RefType.v("java.lang.Object"), 1);
Local argArrayLocal = localGen.generateLocal(arrayType);
newUnits.add(jimp.newIdentityStmt(argArrayLocal, jimp.newParameterRef(arrayType, 0)));
int i = 0;
for (Type paramType : constructor.getParameterTypes()) {
paramLocals[i] = localGen.generateLocal(paramType);
unboxParameter(argArrayLocal, i, paramLocals, paramType, newUnits, localGen);
i++;
}
}
RefType targetType = constructor.getDeclaringClass().getType();
freshLocal = localGen.generateLocal(targetType);
replacement = jimp.newNewExpr(targetType);
break;
}
case MethodInvoke: {
/*
* replace r=m.invoke(obj,args) by: T recv = (T)obj; Object p0 = args[0]; ... Object pn = args[n]; T0 a0 = (T0)p0;
* ... Tn an = (Tn)pn;
*/
SootMethod method = scene.getMethod(target);
// recvObject = @parameter-0
RefType objectType = RefType.v("java.lang.Object");
Local recvObject = localGen.generateLocal(objectType);
newUnits.add(jimp.newIdentityStmt(recvObject, jimp.newParameterRef(objectType, 0)));
paramLocals = new Local[method.getParameterCount()];
if (method.getParameterCount() > 0) {
// argArrayLocal = @parameter-1
ArrayType arrayType = ArrayType.v(RefType.v("java.lang.Object"), 1);
Local argArrayLocal = localGen.generateLocal(arrayType);
newUnits.add(jimp.newIdentityStmt(argArrayLocal, jimp.newParameterRef(arrayType, 1)));
int i = 0;
for (Type paramType : ((Collection<Type>) method.getParameterTypes())) {
paramLocals[i] = localGen.generateLocal(paramType);
unboxParameter(argArrayLocal, i, paramLocals, paramType, newUnits, localGen);
i++;
}
}
RefType targetType = method.getDeclaringClass().getType();
freshLocal = localGen.generateLocal(targetType);
replacement = jimp.newCastExpr(recvObject, method.getDeclaringClass().getType());
break;
}
case FieldSet:
case FieldGet: {
/*
* replace f.set(o,v) by: Object obj = @parameter-0; T freshLocal = (T)obj;
*/
RefType objectType = RefType.v("java.lang.Object");
Local recvObject = localGen.generateLocal(objectType);
newUnits.add(jimp.newIdentityStmt(recvObject, jimp.newParameterRef(objectType, 0)));
RefType fieldClassType = scene.getField(target).getDeclaringClass().getType();
freshLocal = localGen.generateLocal(fieldClassType);
replacement = jimp.newCastExpr(recvObject, fieldClassType);
break;
}
default:
throw new InternalError("Unknown kind of reflective call " + callKind);
}
final AssignStmt replStmt = jimp.newAssignStmt(freshLocal, replacement);
newUnits.add(replStmt);
final Local retLocal = localGen.generateLocal(returnType);
switch (callKind) {
case ClassForName: {
// add: retLocal = freshLocal;
newUnits.add(jimp.newAssignStmt(retLocal, freshLocal));
break;
}
case ClassNewInstance: {
// add: freshLocal.<init>()
newUnits.add(jimp.newInvokeStmt(jimp.newSpecialInvokeExpr(freshLocal, scene.makeMethodRef(scene.getSootClass(target),
SootMethod.constructorName, Collections.emptyList(), VoidType.v(), false))));
// add: retLocal = freshLocal
newUnits.add(jimp.newAssignStmt(retLocal, freshLocal));
break;
}
case ConstructorNewInstance: {
// add: freshLocal.<target>(a0,...,an);
newUnits.add(jimp.newInvokeStmt(
jimp.newSpecialInvokeExpr(freshLocal, scene.getMethod(target).makeRef(), Arrays.asList(paramLocals))));
// add: retLocal = freshLocal
newUnits.add(jimp.newAssignStmt(retLocal, freshLocal));
break;
}
case MethodInvoke: {
// add: freshLocal=recv.<target>(a0,...,an);
SootMethod method = scene.getMethod(target);
InvokeExpr invokeExpr;
if (method.isStatic()) {
invokeExpr = jimp.newStaticInvokeExpr(method.makeRef(), Arrays.asList(paramLocals));
} else {
invokeExpr = jimp.newVirtualInvokeExpr(freshLocal, method.makeRef(), Arrays.asList(paramLocals));
}
if (VoidType.v().equals(method.getReturnType())) {
// method returns null; simply invoke it and return null
newUnits.add(jimp.newInvokeStmt(invokeExpr));
newUnits.add(jimp.newAssignStmt(retLocal, NullConstant.v()));
} else {
newUnits.add(jimp.newAssignStmt(retLocal, invokeExpr));
}
break;
}
case FieldSet: {
// add freshLocal.<f> = v;
Local value = localGen.generateLocal(fieldSetGetType);
newUnits.insertBeforeNoRedirect(jimp.newIdentityStmt(value, jimp.newParameterRef(fieldSetGetType, 1)), replStmt);
SootField field = scene.getField(target);
Local boxedOrCasted = localGen.generateLocal(field.getType());
insertCastOrUnboxingCode(boxedOrCasted, value, newUnits);
FieldRef fieldRef;
if (field.isStatic()) {
fieldRef = jimp.newStaticFieldRef(field.makeRef());
} else {
fieldRef = jimp.newInstanceFieldRef(freshLocal, field.makeRef());
}
newUnits.add(jimp.newAssignStmt(fieldRef, boxedOrCasted));
break;
}
case FieldGet: {
/*
* add: T2 temp = recv.<f>; return temp;
*/
SootField field = scene.getField(target);
Local value = localGen.generateLocal(field.getType());
FieldRef fieldRef;
if (field.isStatic()) {
fieldRef = jimp.newStaticFieldRef(field.makeRef());
} else {
fieldRef = jimp.newInstanceFieldRef(freshLocal, field.makeRef());
}
newUnits.add(jimp.newAssignStmt(value, fieldRef));
insertCastOrBoxingCode(retLocal, value, newUnits);
break;
}
}
if (!VoidType.v().equals(returnType)) {
newUnits.add(jimp.newReturnStmt(retLocal));
}
if (Options.v().validate()) {
newBody.validate();
}
cleanup(newBody);
return newMethod;
}
private void insertCastOrUnboxingCode(Local lhs, Local rhs, Chain<Unit> newUnits) {
final Type lhsType = lhs.getType();
// if assigning to a reference type then there's nothing to do
if (lhsType instanceof PrimType) {
final Type rhsType = rhs.getType();
if (rhsType instanceof PrimType) {
// insert cast
newUnits.add(Jimple.v().newAssignStmt(lhs, Jimple.v().newCastExpr(rhs, lhsType)));
} else {
// reference type in rhs; insert unboxing code
RefType boxedType = (RefType) rhsType;
SootMethodRef ref = Scene.v().makeMethodRef(boxedType.getSootClass(), lhsType.toString() + "Value",
Collections.emptyList(), lhsType, false);
newUnits.add(Jimple.v().newAssignStmt(lhs, Jimple.v().newVirtualInvokeExpr(rhs, ref)));
}
}
}
private void insertCastOrBoxingCode(Local lhs, Local rhs, Chain<Unit> newUnits) {
final Type lhsType = lhs.getType();
// if assigning to a primitive type then there's nothing to do
if (lhsType instanceof RefLikeType) {
final Type rhsType = rhs.getType();
if (rhsType instanceof RefLikeType) {
// insert cast
newUnits.add(Jimple.v().newAssignStmt(lhs, Jimple.v().newCastExpr(rhs, lhsType)));
} else {
// primitive type in rhs; insert boxing code
RefType boxedType = ((PrimType) rhsType).boxedType();
SootMethodRef ref = Scene.v().makeMethodRef(boxedType.getSootClass(), "valueOf", Collections.singletonList(rhsType),
boxedType, true);
newUnits.add(Jimple.v().newAssignStmt(lhs, Jimple.v().newStaticInvokeExpr(ref, rhs)));
}
}
}
/**
* Auto-unboxes an argument array.
*
* @param argsArrayLocal
* a local holding the argument Object[] array
* @param paramIndex
* the index of the parameter to unbox
* @param paramType
* the (target) type of the parameter
* @param newUnits
* the Unit chain to which the unboxing code will be appended
* @param localGen
* a {@link DefaultLocalGenerator} for the body holding the units
*/
private void unboxParameter(Local argsArrayLocal, int paramIndex, Local[] paramLocals, Type paramType,
Chain<Unit> newUnits, LocalGenerator localGen) {
final Jimple jimp = Jimple.v();
if (paramType instanceof PrimType) {
// Unbox the value if needed
RefType boxedType = ((PrimType) paramType).boxedType();
Local boxedLocal = localGen.generateLocal(RefType.v("java.lang.Object"));
newUnits.add(jimp.newAssignStmt(boxedLocal, jimp.newArrayRef(argsArrayLocal, IntConstant.v(paramIndex))));
Local castedLocal = localGen.generateLocal(boxedType);
newUnits.add(jimp.newAssignStmt(castedLocal, jimp.newCastExpr(boxedLocal, boxedType)));
newUnits.add(jimp.newAssignStmt(paramLocals[paramIndex], jimp.newVirtualInvokeExpr(castedLocal, Scene.v()
.makeMethodRef(boxedType.getSootClass(), paramType + "Value", Collections.emptyList(), paramType, false))));
} else {
Local boxedLocal = localGen.generateLocal(RefType.v("java.lang.Object"));
newUnits.add(jimp.newAssignStmt(boxedLocal, jimp.newArrayRef(argsArrayLocal, IntConstant.v(paramIndex))));
Local castedLocal = localGen.generateLocal(paramType);
newUnits.add(jimp.newAssignStmt(castedLocal, jimp.newCastExpr(boxedLocal, paramType)));
newUnits.add(jimp.newAssignStmt(paramLocals[paramIndex], castedLocal));
}
}
}
| 33,382
| 40.991195
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/AbstractStaticnessCorrector.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.BodyTransformer;
import soot.RefType;
import soot.SootClass;
import soot.Type;
/**
* Abstract base class for all transformers that fix wrong code that declares something as static, but uses it like an
* instance or vice versa.
*
* @author Steven Arzt
*/
public abstract class AbstractStaticnessCorrector extends BodyTransformer {
protected static boolean isClassLoaded(SootClass sc) {
return sc.resolvingLevel() >= SootClass.SIGNATURES;
}
protected static boolean isTypeLoaded(Type tp) {
if (tp instanceof RefType) {
RefType rt = (RefType) tp;
if (rt.hasSootClass()) {
return isClassLoaded(rt.getSootClass());
}
}
return false;
}
}
| 1,558
| 28.980769
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/AvailableExpressions.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import soot.EquivalentValue;
import soot.Unit;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
/**
* Provides an user-interface for the AvailableExpressionsAnalysis class. Returns, for each statement, the list of
* expressions available before and after it.
*/
public interface AvailableExpressions {
/** Returns a List containing the UnitValueBox pairs corresponding to expressions available before u. */
public List<UnitValueBoxPair> getAvailablePairsBefore(Unit u);
/** Returns a List containing the UnitValueBox pairs corresponding to expressions available after u. */
public List<UnitValueBoxPair> getAvailablePairsAfter(Unit u);
/** Returns a Chain containing the EquivalentValue objects corresponding to expressions available before u. */
public Chain<EquivalentValue> getAvailableEquivsBefore(Unit u);
/** Returns a Chain containing the EquivalentValue objects corresponding to expressions available after u. */
public Chain<EquivalentValue> getAvailableEquivsAfter(Unit u);
}
| 1,888
| 37.55102
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/CommonPrecedingEqualValueAnalysis.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.EquivalentValue;
import soot.Unit;
import soot.ValueBox;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.BackwardFlowAnalysis;
import soot.toolkits.scalar.FlowSet;
// EqualLocalsAnalysis written by Richard L. Halpert, 2006-12-04
// Finds all values at the given statement from which all of the listed uses come.
public class CommonPrecedingEqualValueAnalysis extends BackwardFlowAnalysis<Unit, FlowSet<Object>> {
private static final Logger logger = LoggerFactory.getLogger(CommonPrecedingEqualValueAnalysis.class);
protected Map<? extends Unit, List<Object>> unitToAliasSet = null;
protected Stmt s = null;
public CommonPrecedingEqualValueAnalysis(UnitGraph g) {
super(g);
// analysis is done on-demand, not now
}
/** Returns a list of EquivalentLocals that must always be equal to l at s */
public List<Object> getCommonAncestorValuesOf(Map<? extends Unit, List<Object>> unitToAliasSet, Stmt s) {
this.unitToAliasSet = unitToAliasSet;
this.s = s;
doAnalysis();
FlowSet<Object> fs = (FlowSet<Object>) getFlowAfter(s);
List<Object> ancestorList = new ArrayList<Object>(fs.size());
for (Object o : fs) {
ancestorList.add(o);
}
return ancestorList;
}
@Override
protected void merge(FlowSet<Object> in1, FlowSet<Object> in2, FlowSet<Object> out) {
in1.intersection(in2, out);
// in1.union(in2, out);
}
@Override
protected void flowThrough(FlowSet<Object> in, Unit unit, FlowSet<Object> out) {
in.copy(out);
// get list of definitions at this unit
List<EquivalentValue> newDefs = new ArrayList<EquivalentValue>();
for (ValueBox vb : unit.getDefBoxes()) {
newDefs.add(new EquivalentValue(vb.getValue()));
}
// If the local of interest was defined in this statement, then we must
// generate a new list of aliases to it starting here
List<Object> aliases = unitToAliasSet.get(unit);
if (aliases != null) {
out.clear();
for (Object next : aliases) {
out.add(next);
}
} else if (unit instanceof DefinitionStmt) {
for (EquivalentValue ev : newDefs) {
out.remove(ev);
// to be smarter, we could also add the right side to the list of aliases...
}
}
// logger.debug(stmt + " HAS ALIASES in=" + in + " out=" + out);
}
@Override
protected void copy(FlowSet<Object> source, FlowSet<Object> dest) {
source.copy(dest);
}
@Override
protected FlowSet<Object> entryInitialFlow() {
return new ArraySparseSet<Object>(); // should be a full set, not an empty one
}
@Override
protected FlowSet<Object> newInitialFlow() {
return new ArraySparseSet<Object>(); // should be a full set, not an empty one
}
}
| 3,838
| 30.991667
| 107
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/CommonSubexpressionEliminator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.EquivalentValue;
import soot.G;
import soot.Local;
import soot.PhaseOptions;
import soot.Scene;
import soot.SideEffectTester;
import soot.Singletons;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
import soot.jimple.NaiveSideEffectTester;
import soot.jimple.toolkits.pointer.PASideEffectTester;
import soot.options.Options;
import soot.tagkit.StringTag;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
/**
* Runs an available expressions analysis on a body, then eliminates common subexpressions.
*
* This implementation is especially slow, as it does not run on basic blocks. A better implementation (which wouldn't catch
* every single cse, but would get most) would use basic blocks instead.
*
* It is also slow because the flow universe is explicitly created; it need not be. A better implementation would implicitly
* compute the kill sets at every node.
*/
public class CommonSubexpressionEliminator extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(CommonSubexpressionEliminator.class);
public CommonSubexpressionEliminator(Singletons.Global g) {
}
public static CommonSubexpressionEliminator v() {
return G.v().soot_jimple_toolkits_scalar_CommonSubexpressionEliminator();
}
/** Common subexpression eliminator. */
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
final Chain<Local> locals = b.getLocals();
// Sigh. check for name collisions.
Set<String> localNames = new HashSet<String>(locals.size());
for (Local loc : locals) {
localNames.add(loc.getName());
}
final SideEffectTester sideEffect;
if (Scene.v().hasCallGraph() && !PhaseOptions.getBoolean(options, "naive-side-effect")) {
sideEffect = new PASideEffectTester();
} else {
sideEffect = new NaiveSideEffectTester();
}
sideEffect.newMethod(b.getMethod());
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Eliminating common subexpressions "
+ (sideEffect instanceof NaiveSideEffectTester ? "(naively)" : "") + "...");
}
AvailableExpressions ae = // new SlowAvailableExpressions(b);
new FastAvailableExpressions(b, sideEffect);
int counter = 0;
final Chain<Unit> units = b.getUnits();
for (Iterator<Unit> unitsIt = units.snapshotIterator(); unitsIt.hasNext();) {
Unit u = unitsIt.next();
if (u instanceof AssignStmt) {
// logger.debug("availExprs: "+availExprs);
Value v = ((AssignStmt) u).getRightOp();
EquivalentValue ev = new EquivalentValue(v);
if (ae.getAvailableEquivsBefore(u).contains(ev)) {
// now we need to track down the containing stmt.
for (UnitValueBoxPair up : ae.getAvailablePairsBefore(u)) {
if (up.getValueBox().getValue().equivTo(v)) {
// create a local for temp storage.
// (we could check to see that the def must-reach, I guess...)
String newName;
do {
newName = "$cseTmp" + counter;
counter++;
} while (localNames.contains(newName));
Local l = Jimple.v().newLocal(newName, Type.toMachineType(v.getType()));
locals.add(l);
// I hope it's always an AssignStmt -- Jimple should guarantee this.
AssignStmt origCalc = (AssignStmt) up.getUnit();
Unit copier = Jimple.v().newAssignStmt(origCalc.getLeftOp(), l);
origCalc.setLeftOp(l);
units.insertAfter(copier, origCalc);
((AssignStmt) u).setRightOp(l);
copier.addTag(new StringTag("Common sub-expression"));
u.addTag(new StringTag("Common sub-expression"));
// logger.debug("added tag to : "+copier);
// logger.debug("added tag to : "+s);
}
}
}
}
}
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Eliminating common subexpressions done!");
}
}
}
| 5,223
| 34.537415
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/ConditionalBranchFolder.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Phong Co
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Singletons;
import soot.Unit;
import soot.Value;
import soot.jimple.IfStmt;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.StmtBody;
import soot.options.Options;
import soot.util.Chain;
public class ConditionalBranchFolder extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(ConditionalBranchFolder.class);
public ConditionalBranchFolder(Singletons.Global g) {
}
public static ConditionalBranchFolder v() {
return G.v().soot_jimple_toolkits_scalar_ConditionalBranchFolder();
}
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
StmtBody stmtBody = (StmtBody) body;
if (Options.v().verbose()) {
logger.debug("[" + stmtBody.getMethod().getName() + "] Folding conditional branches...");
}
int numTrue = 0, numFalse = 0;
Chain<Unit> units = stmtBody.getUnits();
for (Iterator<Unit> it = units.snapshotIterator(); it.hasNext();) {
Unit stmt = it.next();
if (stmt instanceof IfStmt) {
IfStmt ifs = (IfStmt) stmt;
// check for constant-valued conditions
Value cond = Evaluator.getConstantValueOf(ifs.getCondition());
if (cond != null) {
assert (cond instanceof IntConstant);
if (((IntConstant) cond).value == 1) {
// if condition always true, convert if to goto
units.swapWith(stmt, Jimple.v().newGotoStmt(ifs.getTarget()));
numTrue++;
} else {
// if condition is always false, just remove it
assert (((IntConstant) cond).value == 0);// only true/false
units.remove(stmt);
numFalse++;
}
}
}
}
if (Options.v().verbose()) {
logger.debug(
"[" + stmtBody.getMethod().getName() + "] Folded " + numTrue + " true, " + numFalse + " conditional branches");
}
} // foldBranches
} // BranchFolder
| 2,981
| 31.413043
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/ConstantCastEliminator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2015 Steven Arzt
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.DoubleType;
import soot.FloatType;
import soot.G;
import soot.Singletons;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
/**
* Transformer for removing unnecessary casts on primitive values. An assignment a = (float) 42 will for instance be
* transformed to a = 42f;
*
* @author Steven Arzt
*/
public class ConstantCastEliminator extends BodyTransformer {
public ConstantCastEliminator(Singletons.Global g) {
}
public static ConstantCastEliminator v() {
return G.v().soot_jimple_toolkits_scalar_ConstantCastEliminator();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
// Check for all assignments that perform casts on primitive constants
for (Unit u : b.getUnits()) {
if (u instanceof AssignStmt) {
AssignStmt assign = (AssignStmt) u;
Value rightOp = assign.getRightOp();
if (rightOp instanceof CastExpr) {
CastExpr ce = (CastExpr) rightOp;
Value castOp = ce.getOp();
if (castOp instanceof IntConstant) {
Type castType = ce.getType();
if (castType instanceof FloatType) {
// a = (float) 42
assign.setRightOp(FloatConstant.v(((IntConstant) castOp).value));
} else if (castType instanceof DoubleType) {
// a = (double) 42
assign.setRightOp(DoubleConstant.v(((IntConstant) castOp).value));
}
}
}
}
}
}
}
| 2,569
| 30.341463
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/ConstantPropagatorAndFolder.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Phong Co
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Local;
import soot.RefType;
import soot.Singletons;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.CastExpr;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.NullConstant;
import soot.jimple.NumericConstant;
import soot.jimple.StringConstant;
import soot.options.Options;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.PseudoTopologicalOrderer;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.LocalDefs;
/**
* Does constant propagation and folding. Constant folding is the compile-time evaluation of constant expressions (i.e. 2 *
* 3).
*/
public class ConstantPropagatorAndFolder extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(ConstantPropagatorAndFolder.class);
public ConstantPropagatorAndFolder(Singletons.Global g) {
}
public static ConstantPropagatorAndFolder v() {
return G.v().soot_jimple_toolkits_scalar_ConstantPropagatorAndFolder();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
int numFolded = 0;
int numPropagated = 0;
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Propagating and folding constants...");
}
UnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b);
LocalDefs localDefs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(g);
// Perform a constant/local propagation pass.
// go through each use box in each statement
for (Unit u : (new PseudoTopologicalOrderer<Unit>()).newList(g, false)) {
// propagation pass
for (ValueBox useBox : u.getUseBoxes()) {
Value value = useBox.getValue();
if (value instanceof Local) {
Local local = (Local) value;
List<Unit> defsOfUse = localDefs.getDefsOfAt(local, u);
if (defsOfUse.size() == 1) {
DefinitionStmt defStmt = (DefinitionStmt) defsOfUse.get(0);
Value rhs = defStmt.getRightOp();
if (rhs instanceof NumericConstant || rhs instanceof StringConstant || rhs instanceof NullConstant) {
if (useBox.canContainValue(rhs)) {
useBox.setValue(rhs);
numPropagated++;
}
} else if (rhs instanceof CastExpr) {
CastExpr ce = (CastExpr) rhs;
if (ce.getCastType() instanceof RefType && ce.getOp() instanceof NullConstant) {
defStmt.getRightOpBox().setValue(NullConstant.v());
numPropagated++;
}
}
}
}
}
// folding pass
for (ValueBox useBox : u.getUseBoxes()) {
Value value = useBox.getValue();
if (!(value instanceof Constant)) {
if (Evaluator.isValueConstantValued(value)) {
Value constValue = Evaluator.getConstantValueOf(value);
if (useBox.canContainValue(constValue)) {
useBox.setValue(constValue);
numFolded++;
}
}
}
}
}
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Propagated: " + numPropagated + ", Folded: " + numFolded);
}
}
}
| 4,301
| 33.142857
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/CopyPropagator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.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.G;
import soot.Local;
import soot.NullType;
import soot.RefLikeType;
import soot.Scene;
import soot.Singletons;
import soot.Timers;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.options.CPOptions;
import soot.options.Options;
import soot.tagkit.Host;
import soot.tagkit.LineNumberTag;
import soot.tagkit.SourceLnPosTag;
import soot.tagkit.Tag;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.PseudoTopologicalOrderer;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.LocalDefs;
public class CopyPropagator extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(CopyPropagator.class);
protected ThrowAnalysis throwAnalysis = null;
protected boolean forceOmitExceptingUnitEdges = false;
public CopyPropagator(Singletons.Global g) {
}
public CopyPropagator(ThrowAnalysis ta) {
this.throwAnalysis = ta;
}
public CopyPropagator(ThrowAnalysis ta, boolean forceOmitExceptingUnitEdges) {
this.throwAnalysis = ta;
this.forceOmitExceptingUnitEdges = forceOmitExceptingUnitEdges;
}
public static CopyPropagator v() {
return G.v().soot_jimple_toolkits_scalar_CopyPropagator();
}
/**
* Cascaded copy propagator.
*
* <p>
* If it encounters situations of the form: A: a = ...; B: ... x = a; C:... use (x); where a has only one definition, and x
* has only one definition (B), then it can propagate immediately without checking between B and C for redefinitions of a
* (namely) A because they cannot occur. In this case the propagator is global.
*
* <p>
* Otherwise, if a has multiple definitions then it only checks for redefinitions of Propagates constants and copies in
* extended basic blocks.
*
* <p>
* Does not propagate stack locals when the "only-regular-locals" option is true.
*/
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> opts) {
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Propagating copies...");
}
if (Options.v().time()) {
Timers.v().propagatorTimer.start();
}
// Count number of definitions for each local.
Map<Local, Integer> localToDefCount = new HashMap<Local, Integer>(b.getLocalCount() * 2 + 1);
for (Unit u : b.getUnits()) {
if (u instanceof DefinitionStmt) {
Value leftOp = ((DefinitionStmt) u).getLeftOp();
if (leftOp instanceof Local) {
Local loc = (Local) leftOp;
Integer old = localToDefCount.get(loc);
localToDefCount.put(loc, (old == null) ? 1 : (old + 1));
}
}
}
if (throwAnalysis == null) {
throwAnalysis = Scene.v().getDefaultThrowAnalysis();
}
if (!forceOmitExceptingUnitEdges) {
forceOmitExceptingUnitEdges = Options.v().omit_excepting_unit_edges();
}
{
// Go through the definitions, building the webs
int fastCopyPropagationCount = 0;
int slowCopyPropagationCount = 0;
UnitGraph graph
= ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b, throwAnalysis, forceOmitExceptingUnitEdges);
LocalDefs localDefs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(graph);
CPOptions options = new CPOptions(opts);
boolean onlyRegularLocals = options.only_regular_locals();
boolean onlyStackLocals = options.only_stack_locals();
boolean allLocals = onlyRegularLocals && onlyStackLocals;
// Perform a local propagation pass.
for (Unit u : (new PseudoTopologicalOrderer<Unit>()).newList(graph, false)) {
for (ValueBox useBox : u.getUseBoxes()) {
Value value = useBox.getValue();
if (value instanceof Local) {
Local l = (Local) value;
// We force propagating nulls. If a target can only be
// null due to typing, we always inline that constant.
if (!allLocals && !(l.getType() instanceof NullType)) {
if (onlyRegularLocals && l.isStackLocal()) {
continue;
}
if (onlyStackLocals && !l.isStackLocal()) {
continue;
}
}
// We can propagate the definition if we either only have one definition
// or all definitions are side-effect free and equal. For starters, we
// only support constants in the case of multiple definitions.
List<Unit> defsOfUse = localDefs.getDefsOfAt(l, u);
boolean propagateDef = defsOfUse.size() == 1;
if (!propagateDef && defsOfUse.size() > 0) {
boolean agrees = true;
Constant constVal = null;
for (Unit defUnit : defsOfUse) {
boolean defAgrees = false;
if (defUnit instanceof AssignStmt) {
Value rightOp = ((AssignStmt) defUnit).getRightOp();
if (rightOp instanceof Constant) {
if (constVal == null) {
constVal = (Constant) rightOp;
defAgrees = true;
} else if (constVal.equals(rightOp)) {
defAgrees = true;
}
}
}
agrees &= defAgrees;
}
propagateDef = agrees;
}
if (propagateDef) {
final DefinitionStmt def = (DefinitionStmt) defsOfUse.get(0);
final Value rightOp = def.getRightOp();
if (rightOp instanceof Constant) {
if (useBox.canContainValue(rightOp)) {
useBox.setValue(rightOp);
copyLineTags(useBox, def);
}
} else if (rightOp instanceof CastExpr) {
CastExpr ce = (CastExpr) rightOp;
if (ce.getCastType() instanceof RefLikeType) {
Value op = ce.getOp();
if ((op instanceof IntConstant && ((IntConstant) op).value == 0)
|| (op instanceof LongConstant && ((LongConstant) op).value == 0)) {
if (useBox.canContainValue(NullConstant.v())) {
useBox.setValue(NullConstant.v());
copyLineTags(useBox, def);
}
}
}
} else if (rightOp instanceof Local) {
Local m = (Local) rightOp;
if (l != m) {
Integer defCount = localToDefCount.get(m);
if (defCount == null || defCount == 0) {
throw new RuntimeException("Variable " + m + " used without definition!");
} else if (defCount == 1) {
useBox.setValue(m);
copyLineTags(useBox, def);
fastCopyPropagationCount++;
continue;
}
List<Unit> path = graph.getExtendedBasicBlockPathBetween(def, u);
if (path == null) {
// no path in the extended basic block
continue;
}
{
boolean isRedefined = false;
Iterator<Unit> pathIt = path.iterator();
// Skip first node
pathIt.next();
// Make sure that m is not redefined along path
while (pathIt.hasNext()) {
Stmt s = (Stmt) pathIt.next();
if (u == s) {
// Don't look at the last statement
// since it is evaluated after the uses.
break;
}
if (s instanceof DefinitionStmt) {
if (((DefinitionStmt) s).getLeftOp() == m) {
isRedefined = true;
break;
}
}
}
if (isRedefined) {
continue;
}
}
useBox.setValue(m);
slowCopyPropagationCount++;
}
}
}
}
}
}
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Propagated: " + fastCopyPropagationCount + " fast copies "
+ slowCopyPropagationCount + " slow copies");
}
}
if (Options.v().time()) {
Timers.v().propagatorTimer.end();
}
}
public static void copyLineTags(ValueBox useBox, DefinitionStmt def) {
// we might have a def statement which contains a propagated constant itself as right-op. we
// want to propagate the tags of this constant and not the def statement itself in this case.
if (!copyLineTags(useBox, def.getRightOpBox())) {
copyLineTags(useBox, (Host) def);
}
}
/**
* Copies the {@link SourceLnPosTag} and {@link LineNumberTag}s from the given host to the given ValueBox
*
* @param useBox
* The box to which the position tags should be copied
* @param host
* The host from which the position tags should be copied
* @return True if a copy was conducted, false otherwise
*/
private static boolean copyLineTags(ValueBox useBox, Host host) {
boolean res = false;
Tag tag = host.getTag(SourceLnPosTag.NAME);
if (tag != null) {
useBox.addTag(tag);
res = true;
}
tag = host.getTag(LineNumberTag.NAME);
if (tag != null) {
useBox.addTag(tag);
res = true;
}
return res;
}
}
| 11,078
| 34.171429
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/DeadAssignmentEliminator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.PhaseOptions;
import soot.RefLikeType;
import soot.Scene;
import soot.Singletons;
import soot.Timers;
import soot.Trap;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.DivExpr;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.RemExpr;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.toolkits.scalar.LocalDefs;
import soot.toolkits.scalar.LocalUses;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
public class DeadAssignmentEliminator extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(DeadAssignmentEliminator.class);
public DeadAssignmentEliminator(Singletons.Global g) {
}
public static DeadAssignmentEliminator v() {
return G.v().soot_jimple_toolkits_scalar_DeadAssignmentEliminator();
}
/**
* Eliminates dead code in a linear fashion. Complexity is linear with respect to the statements.
*
* Does not work on grimp code because of the check on the right hand side for side effects.
*/
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
final boolean eliminateOnlyStackLocals = PhaseOptions.getBoolean(options, "only-stack-locals");
final Options soptions = Options.v();
if (soptions.verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Eliminating dead code...");
}
if (soptions.time()) {
Timers.v().deadCodeTimer.start();
}
final Chain<Unit> units = b.getUnits();
Deque<Unit> q = new ArrayDeque<Unit>(units.size());
// Make a first pass through the statements, noting
// the statements we must absolutely keep.
boolean isStatic = b.getMethod().isStatic();
boolean allEssential = true;
boolean checkInvoke = false;
Local thisLocal = null;
for (Iterator<Unit> it = units.iterator(); it.hasNext();) {
Unit s = it.next();
boolean isEssential = true;
if (s instanceof NopStmt) {
// Hack: do not remove nop if is is used for a Trap
// which is at the very end of the code.
boolean removeNop = it.hasNext();
if (!removeNop) {
removeNop = true;
for (Trap t : b.getTraps()) {
if (t.getEndUnit() == s) {
removeNop = false;
break;
}
}
}
if (removeNop) {
it.remove();
continue;
}
} else if (s instanceof AssignStmt) {
AssignStmt as = (AssignStmt) s;
Value lhs = as.getLeftOp();
Value rhs = as.getRightOp();
// Stmt is of the form a = a which is useless
if (lhs == rhs && lhs instanceof Local) {
it.remove();
continue;
}
if (lhs instanceof Local
&& (!eliminateOnlyStackLocals || ((Local) lhs).isStackLocal() || lhs.getType() instanceof NullType)) {
isEssential = false;
if (!checkInvoke) {
checkInvoke = as.containsInvokeExpr();
}
if (rhs instanceof CastExpr) {
// CastExpr : can trigger ClassCastException, but null-casts never fail
CastExpr ce = (CastExpr) rhs;
Type t = ce.getCastType();
Value v = ce.getOp();
isEssential = !(v instanceof NullConstant) && t instanceof RefLikeType;
} else if (rhs instanceof InvokeExpr || rhs instanceof ArrayRef || rhs instanceof NewExpr
|| rhs instanceof NewArrayExpr || rhs instanceof NewMultiArrayExpr || rhs instanceof LengthExpr) {
// ArrayRef : can have side effects (like throwing a null pointer exception)
// InvokeExpr : can have side effects (like throwing a null pointer exception)
// NewArrayExpr : can throw exception
// NewMultiArrayExpr : can throw exception
// NewExpr : can trigger class initialization
// LengthExpr : can throw exception
isEssential = true;
} else if (rhs instanceof FieldRef) {
// Can trigger class initialization
isEssential = true;
if (rhs instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) rhs;
if (!isStatic && thisLocal == null) {
thisLocal = b.getThisLocal();
}
// Any InstanceFieldRef may have side effects,
// unless the base is reading from 'this'
// in a non-static method
isEssential = (isStatic || thisLocal != ifr.getBase());
}
} else if (rhs instanceof DivExpr || rhs instanceof RemExpr) {
BinopExpr expr = (BinopExpr) rhs;
Type t1 = expr.getOp1().getType();
Type t2 = expr.getOp2().getType();
// Can trigger a division by zero
boolean t2Int = t2 instanceof IntType;
isEssential = t2Int || t1 instanceof IntType || t1 instanceof LongType || t2 instanceof LongType
|| t1 instanceof UnknownType || t2 instanceof UnknownType;
if (isEssential && t2Int) {
Value v = expr.getOp2();
if (v instanceof IntConstant) {
IntConstant i = (IntConstant) v;
isEssential = (i.value == 0);
} else {
isEssential = true; // could be 0, we don't know
}
}
if (isEssential && t2 instanceof LongType) {
Value v = expr.getOp2();
if (v instanceof LongConstant) {
LongConstant l = (LongConstant) v;
isEssential = (l.value == 0);
} else {
isEssential = true; // could be 0, we don't know
}
}
}
}
}
if (isEssential) {
q.addFirst(s);
}
allEssential &= isEssential;
}
if (checkInvoke || !allEssential) {
// Add all the statements which are used to compute values
// for the essential statements, recursively
final LocalDefs localDefs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(b);
if (!allEssential) {
Set<Unit> essential = new HashSet<Unit>(units.size());
while (!q.isEmpty()) {
Unit s = q.removeFirst();
if (essential.add(s)) {
for (ValueBox box : s.getUseBoxes()) {
Value v = box.getValue();
if (v instanceof Local) {
Local l = (Local) v;
List<Unit> defs = localDefs.getDefsOfAt(l, s);
if (defs != null) {
q.addAll(defs);
}
}
}
}
}
// Remove the dead statements
units.retainAll(essential);
}
if (checkInvoke) {
final LocalUses localUses = LocalUses.Factory.newLocalUses(b, localDefs);
// Eliminate dead assignments from invokes such as x = f(), where
// x is no longer used
List<AssignStmt> postProcess = new ArrayList<AssignStmt>();
for (Unit u : units) {
if (u instanceof AssignStmt) {
AssignStmt s = (AssignStmt) u;
if (s.containsInvokeExpr()) {
// Just find one use of l which is essential
boolean deadAssignment = true;
for (UnitValueBoxPair pair : localUses.getUsesOf(s)) {
if (units.contains(pair.unit)) {
deadAssignment = false;
break;
}
}
if (deadAssignment) {
postProcess.add(s);
}
}
}
}
final Jimple jimple = Jimple.v();
for (AssignStmt s : postProcess) {
// Transform it into a simple invoke.
Stmt newInvoke = jimple.newInvokeStmt(s.getInvokeExpr());
newInvoke.addAllTagsOf(s);
units.swapWith(s, newInvoke);
// If we have a callgraph, we need to fix it
if (Scene.v().hasCallGraph()) {
Scene.v().getCallGraph().swapEdgesOutOf(s, newInvoke);
}
}
}
}
if (soptions.time()) {
Timers.v().deadCodeTimer.end();
}
}
}
| 10,022
| 31.648208
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/DefaultLocalCreation.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import soot.Local;
import soot.Type;
import soot.jimple.Jimple;
/**
* provides an easy interface to handle new var-names. New names are automatically added to the chain, and the provided
* locals are guaranteed to have a unique name.
*/
public class DefaultLocalCreation extends LocalCreation {
/** if no prefix is given, this one's used */
public static final String DEFAULT_PREFIX = "soot";
private final Set<String> locals;
private int counter;
/**
* all actions are done on the given locals-chain. as prefix the <code>DEFAULT-PREFIX</code> will be used.
*
* @param locals
* the locals-chain of a Jimple-body
*/
public DefaultLocalCreation(Collection<Local> locals) {
this(locals, DEFAULT_PREFIX);
}
/**
* whenever <code>newLocal(type)</code> will be called, the given prefix is used.
*
* @param locals
* the locals-chain of a Jimple-body
* @param prefix
* prefix overrides the DEFAULT-PREFIX
*/
public DefaultLocalCreation(Collection<Local> locals, String prefix) {
super(locals, prefix);
this.locals = new HashSet<String>(locals.size());
for (Local l : locals) {
this.locals.add(l.getName());
}
this.counter = 0; // try the first one with suffix 0.
}
@Override
public Local newLocal(Type type) {
return newLocal(this.prefix, type);
}
@Override
public Local newLocal(String prefix, Type type) {
int suffix = prefix.equals(this.prefix) ? this.counter : 0;
while (this.locals.contains(prefix + suffix)) {
suffix++;
}
if (prefix.equals(this.prefix)) {
this.counter = suffix + 1;
}
String newName = prefix + suffix;
Local newLocal = Jimple.v().newLocal(newName, type);
this.localChain.add(newLocal);
this.locals.add(newName);
return newLocal;
}
}
| 2,754
| 28.623656
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/EmptySwitchEliminator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Singletons;
import soot.Unit;
import soot.jimple.Jimple;
import soot.jimple.LookupSwitchStmt;
import soot.util.Chain;
/**
* Removes empty switch statements which always take the default action from a method body, i.e. blocks of the form switch(x)
* { default: ... }. Such blocks are replaced by the code of the default block.
*
* @author Steven Arzt
*/
public class EmptySwitchEliminator extends BodyTransformer {
public EmptySwitchEliminator(Singletons.Global g) {
}
public static EmptySwitchEliminator v() {
return G.v().soot_jimple_toolkits_scalar_EmptySwitchEliminator();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
final Chain<Unit> units = b.getUnits();
for (Iterator<Unit> it = units.snapshotIterator(); it.hasNext();) {
Unit u = it.next();
if (u instanceof LookupSwitchStmt) {
LookupSwitchStmt sw = (LookupSwitchStmt) u;
if (sw.getTargetCount() == 0) {
Unit defaultTarget = sw.getDefaultTarget();
if (defaultTarget != null) {
units.swapWith(sw, Jimple.v().newGotoStmt(defaultTarget));
}
}
}
}
}
}
| 2,155
| 30.246377
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/EqualLocalsAnalysis.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import soot.EquivalentValue;
import soot.Local;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.DefinitionStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.Stmt;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
// EqualLocalsAnalysis written by Richard L. Halpert, 2006-12-04
// Finds equal/equavalent/aliasing locals to a given local at a given statement, on demand
// The answer provided is occasionally suboptimal (but correct) in the event where
// a _re_definition of the given local causes it to become equal to existing locals.
public class EqualLocalsAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Object>> {
protected Local l = null;
protected Stmt s = null;
public EqualLocalsAnalysis(UnitGraph g) {
super(g);
// analysis is done on-demand, not now
}
/** Returns a list of EquivalentValue wrapped Locals and Refs that must always be equal to l at s */
public List<Object> getCopiesOfAt(Local l, Stmt s) {
this.l = l;
this.s = s;
doAnalysis();
FlowSet<Object> fs = (FlowSet<Object>) getFlowBefore(s);
ArrayList<Object> aliasList = new ArrayList<Object>(fs.size());
for (Object o : fs) {
aliasList.add(o);
}
if (!aliasList.contains(new EquivalentValue(l))) {
aliasList.clear();
aliasList.trimToSize();
}
return aliasList;
}
@Override
protected void flowThrough(FlowSet<Object> in, Unit unit, FlowSet<Object> out) {
in.copy(out);
// get list of definitions at this unit
List<EquivalentValue> newDefs = new ArrayList<EquivalentValue>();
for (ValueBox next : unit.getDefBoxes()) {
newDefs.add(new EquivalentValue(next.getValue()));
}
// If the local of interest was defined in this statement, then we must
// generate a new list of aliases to it starting here
if (newDefs.contains(new EquivalentValue(l))) {
List<Stmt> existingDefStmts = new ArrayList<Stmt>();
for (Object o : out) {
if (o instanceof Stmt) {
existingDefStmts.add((Stmt) o);
}
}
out.clear();
for (EquivalentValue next : newDefs) {
out.add(next);
}
if (unit instanceof DefinitionStmt) {
DefinitionStmt du = (DefinitionStmt) unit;
if (!du.containsInvokeExpr() && !(unit instanceof IdentityStmt)) {
out.add(new EquivalentValue(du.getRightOp()));
}
}
for (Stmt def : existingDefStmts) {
List<Value> sNewDefs = new ArrayList<Value>();
for (ValueBox next : def.getDefBoxes()) {
sNewDefs.add(next.getValue());
}
if (def instanceof DefinitionStmt) {
if (out.contains(new EquivalentValue(((DefinitionStmt) def).getRightOp()))) {
for (Value v : sNewDefs) {
out.add(new EquivalentValue(v));
}
} else {
for (Value v : sNewDefs) {
out.remove(new EquivalentValue(v));
}
}
}
}
} else {
if (unit instanceof DefinitionStmt) {
if (out.contains(new EquivalentValue(l))) {
if (out.contains(new EquivalentValue(((DefinitionStmt) unit).getRightOp()))) {
for (EquivalentValue ev : newDefs) {
out.add(ev);
}
} else {
for (EquivalentValue ev : newDefs) {
out.remove(ev);
}
}
} else {
// before finding a def for l, just keep track of all definition statements
// note that if l is redefined, then we'll miss existing values that then
// become equal to l. It is suboptimal but correct to miss these values.
out.add(unit);
}
}
}
}
@Override
protected void merge(FlowSet<Object> in1, FlowSet<Object> in2, FlowSet<Object> out) {
in1.intersection(in2, out);
}
@Override
protected void copy(FlowSet<Object> source, FlowSet<Object> dest) {
source.copy(dest);
}
@Override
protected FlowSet<Object> entryInitialFlow() {
return new ArraySparseSet<Object>();
}
@Override
protected FlowSet<Object> newInitialFlow() {
return new ArraySparseSet<Object>();
}
}
| 5,217
| 30.433735
| 102
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/EqualUsesAnalysis.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
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.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.DefinitionStmt;
import soot.jimple.Stmt;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
// EqualUsesAnalysis written by Richard L. Halpert, 2006-12-04
// Determines if a set of uses of locals all use the same value
// whenever they occur together. Can accept a set of boundary
// statements which define a region which, if exited, counts
//
// The locals being used need not be the same
/**
* @deprecated This class is buggy. Please use soot.jimple.toolkits.pointer.LocalMustAliasAnalysis instead.
*/
@Deprecated
public class EqualUsesAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Object>> {
private static final Logger logger = LoggerFactory.getLogger(EqualUsesAnalysis.class);
protected final EqualLocalsAnalysis el;
// Provided by client
protected Map<Stmt, Local> stmtToLocal = null;
protected Set<Stmt> useStmts = null;
protected Collection<Local> useLocals = null;
protected List<Stmt> boundaryStmts = null;
// Calculated by flow analysis
protected List<Stmt> redefStmts = null;
protected Map<Stmt, List<Object>> firstUseToAliasSet = null;
public EqualUsesAnalysis(UnitGraph g) {
super(g);
this.el = new EqualLocalsAnalysis(g);
// analysis is done on-demand, not now
}
public boolean areEqualUses(Stmt firstStmt, Local firstLocal, Stmt secondStmt, Local secondLocal) {
return areEqualUses(firstStmt, firstLocal, secondStmt, secondLocal, new ArrayList<Stmt>());
}
public boolean areEqualUses(Stmt firstStmt, Local firstLocal, Stmt secondStmt, Local secondLocal,
List<Stmt> boundaryStmts) {
Map<Stmt, Local> stmtToLocal = new HashMap<Stmt, Local>();
stmtToLocal.put(firstStmt, firstLocal);
stmtToLocal.put(secondStmt, secondLocal);
return areEqualUses(stmtToLocal, boundaryStmts);
}
public boolean areEqualUses(Map<Stmt, Local> stmtToLocal) {
return areEqualUses(stmtToLocal, new ArrayList<Stmt>());
}
// You may optionally specify start and end statements... for if
// you're interested only in a certain part of the method
public boolean areEqualUses(Map<Stmt, Local> stmtToLocal, List<Stmt> boundaryStmts) {
this.stmtToLocal = stmtToLocal;
this.useStmts = stmtToLocal.keySet();
this.useLocals = stmtToLocal.values();
this.boundaryStmts = boundaryStmts;
this.redefStmts = new ArrayList<Stmt>();
this.firstUseToAliasSet = new HashMap<Stmt, List<Object>>();
// logger.debug("Checking for Locals " + useLocals + " in these statements: " + useStmts);
doAnalysis();
// If any redefinition reaches any use statement, return false
for (Stmt u : useStmts) {
FlowSet<Object> fs = getFlowBefore(u);
for (Stmt next : redefStmts) {
if (fs.contains(next)) {
// logger.debug("LIF = false ");
return false;
}
}
List<Object> aliases = null;
for (Object o : fs) {
if (o instanceof List) {
aliases = (List<Object>) o;
}
}
if (aliases != null && !aliases.contains(new EquivalentValue(stmtToLocal.get(u)))) {
// logger.debug("LIF = false ");
return false;
}
}
// logger.debug("LIF = true ");
return true;
}
public Map<Stmt, List<Object>> getFirstUseToAliasSet() {
return firstUseToAliasSet;
}
@Override
protected void merge(FlowSet<Object> inSet1, FlowSet<Object> inSet2, FlowSet<Object> outSet) {
inSet1.union(inSet2, outSet);
List<Object> aliases1 = null;
List<Object> aliases2 = null;
for (Object o : outSet) {
if (o instanceof List) {
if (aliases1 == null) {
aliases1 = (List<Object>) o;
} else {
aliases2 = (List<Object>) o;
}
}
}
if (aliases1 != null && aliases2 != null) {
outSet.remove(aliases2);
for (Iterator<Object> aliasIt = aliases1.iterator(); aliasIt.hasNext();) {
Object o = aliasIt.next();
if (!aliases2.contains(o)) {
aliasIt.remove();
}
}
}
}
@Override
protected void flowThrough(FlowSet<Object> in, Unit unit, FlowSet<Object> out) {
Stmt stmt = (Stmt) unit;
in.copy(out);
// get list of definitions at this unit
List<Value> newDefs = new ArrayList<Value>();
for (ValueBox vb : stmt.getDefBoxes()) {
newDefs.add(vb.getValue());
}
// check if any locals of interest were redefined here
for (Local useLocal : useLocals) {
// if a relevant local was (re)def'd here
if (newDefs.contains(useLocal)) {
for (Object o : out) {
if (o instanceof Stmt) {
Stmt s = (Stmt) o;
if (stmtToLocal.get(s) == useLocal) {
redefStmts.add(stmt); // mark this as an active redef stmt
}
}
}
}
}
// if this is a redefinition statement, flow it forwards
if (redefStmts.contains(stmt)) {
out.add(stmt);
}
// if this is a boundary statement, clear everything but aliases from the flow set
if (boundaryStmts.contains(stmt)) {
// find the alias entry in the flow set
/*
* List aliases = null; Iterator outIt = out.iterator(); while(outIt.hasNext()) { Object o = outIt.next(); if( o
* instanceof List ) aliases = (List) o; }
*/
// clear the flow set, and add aliases back in
out.clear();
// if(aliases != null)
// out.add(aliases);
}
// if this is a use statement (of interest), flow it forward
// if it's the first use statement, get an alias list
if (useStmts.contains(stmt)) {
if (out.size() == 0) {
// Add a list of aliases to the used value
Local l = stmtToLocal.get(stmt);
List<Object> aliasList = el.getCopiesOfAt(l, stmt);
if (aliasList.isEmpty()) {
aliasList.add(l); // covers the case of this or a parameter, where getCopiesOfAt doesn't seem to work right now
}
firstUseToAliasSet.put(stmt, new ArrayList<Object>(aliasList));
// logger.debug("Aliases of " + l + " at " + stmt + " are " + aliasList);
out.add(aliasList);
}
out.add(stmt);
}
// update the alias list if this is a definition statement
if (stmt instanceof DefinitionStmt) {
List<EquivalentValue> aliases = null;
for (Object o : out) {
if (o instanceof List) {
aliases = (List<EquivalentValue>) o;
}
}
if (aliases != null) {
if (aliases.contains(new EquivalentValue(((DefinitionStmt) stmt).getRightOp()))) {
for (Value v : newDefs) {
aliases.add(new EquivalentValue(v));
}
} else {
for (Value v : newDefs) {
aliases.remove(new EquivalentValue(v));
}
}
}
}
}
@Override
protected void copy(FlowSet<Object> source, FlowSet<Object> dest) {
source.copy(dest);
}
@Override
protected FlowSet<Object> entryInitialFlow() {
return new ArraySparseSet<Object>();
}
@Override
protected FlowSet<Object> newInitialFlow() {
return new ArraySparseSet<Object>();
}
}
| 8,416
| 30.762264
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/Evaluator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Phong Co
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Value;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArithmeticConstant;
import soot.jimple.BinopExpr;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.Constant;
import soot.jimple.DivExpr;
import soot.jimple.EqExpr;
import soot.jimple.GeExpr;
import soot.jimple.GtExpr;
import soot.jimple.IntConstant;
import soot.jimple.LeExpr;
import soot.jimple.LongConstant;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NullConstant;
import soot.jimple.NumericConstant;
import soot.jimple.OrExpr;
import soot.jimple.RealConstant;
import soot.jimple.RemExpr;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.UnopExpr;
import soot.jimple.UshrExpr;
import soot.jimple.XorExpr;
public class Evaluator {
public static boolean isValueConstantValued(Value op) {
if (op instanceof Constant) {
return true;
} else if (op instanceof UnopExpr) {
Value innerOp = ((UnopExpr) op).getOp();
if (innerOp == NullConstant.v()) {
// operations on null will throw an exception and the operation
// is therefore not considered constant-valued; see posting on Soot list
// on 18 September 2007 14:36
return false;
}
if (isValueConstantValued(innerOp)) {
return true;
}
} else if (op instanceof BinopExpr) {
final BinopExpr binExpr = (BinopExpr) op;
final Value op1 = binExpr.getOp1();
final Value op2 = binExpr.getOp2();
// Only evaluate these checks once, and use the result multiple times
final boolean isOp1Constant = isValueConstantValued(op1);
final boolean isOp2Constant = isValueConstantValued(op2);
/* Handle weird cases. */
if (op instanceof DivExpr || op instanceof RemExpr) {
if (!isOp1Constant || !isOp2Constant) {
return false;
}
/* check for a 0 value. If so, punt. */
Value c2 = getConstantValueOf(op2);
if ((c2 instanceof IntConstant && ((IntConstant) c2).value == 0)
|| (c2 instanceof LongConstant && ((LongConstant) c2).value == 0)) {
return false;
}
}
if (isOp1Constant && isOp2Constant) {
return true;
}
}
return false;
} // isValueConstantValued
/**
* Returns the constant value of <code>op</code> if it is easy to find the constant value; else returns <code>null</code>.
*/
public static Value getConstantValueOf(Value op) {
if (!isValueConstantValued(op)) {
return null;
}
if (op instanceof Constant) {
return op;
} else if (op instanceof UnopExpr) {
Value c = getConstantValueOf(((UnopExpr) op).getOp());
if (op instanceof NegExpr) {
return ((NumericConstant) c).negate();
}
} else if (op instanceof BinopExpr) {
final BinopExpr binExpr = (BinopExpr) op;
final Value c1 = getConstantValueOf(binExpr.getOp1());
final Value c2 = getConstantValueOf(binExpr.getOp2());
if (op instanceof AddExpr) {
return ((NumericConstant) c1).add((NumericConstant) c2);
} else if (op instanceof SubExpr) {
return ((NumericConstant) c1).subtract((NumericConstant) c2);
} else if (op instanceof MulExpr) {
return ((NumericConstant) c1).multiply((NumericConstant) c2);
} else if (op instanceof DivExpr) {
return ((NumericConstant) c1).divide((NumericConstant) c2);
} else if (op instanceof RemExpr) {
return ((NumericConstant) c1).remainder((NumericConstant) c2);
} else if (op instanceof EqExpr || op instanceof NeExpr) {
if (c1 instanceof NumericConstant) {
if (!(c2 instanceof NumericConstant)) {
return IntConstant.v(0);
} else if (op instanceof EqExpr) {
return ((NumericConstant) c1).equalEqual((NumericConstant) c2);
} else if (op instanceof NeExpr) {
return ((NumericConstant) c1).notEqual((NumericConstant) c2);
}
} else if (c1 instanceof StringConstant || c1 instanceof NullConstant || c1 instanceof ClassConstant) {
boolean equality = c1.equals(c2);
boolean truth = (op instanceof EqExpr) ? equality : !equality;
return IntConstant.v(truth ? 1 : 0);
}
throw new RuntimeException("constant neither numeric nor string");
} else if (op instanceof GtExpr) {
return ((NumericConstant) c1).greaterThan((NumericConstant) c2);
} else if (op instanceof GeExpr) {
return ((NumericConstant) c1).greaterThanOrEqual((NumericConstant) c2);
} else if (op instanceof LtExpr) {
return ((NumericConstant) c1).lessThan((NumericConstant) c2);
} else if (op instanceof LeExpr) {
return ((NumericConstant) c1).lessThanOrEqual((NumericConstant) c2);
} else if (op instanceof AndExpr) {
return ((ArithmeticConstant) c1).and((ArithmeticConstant) c2);
} else if (op instanceof OrExpr) {
return ((ArithmeticConstant) c1).or((ArithmeticConstant) c2);
} else if (op instanceof XorExpr) {
return ((ArithmeticConstant) c1).xor((ArithmeticConstant) c2);
} else if (op instanceof ShlExpr) {
return ((ArithmeticConstant) c1).shiftLeft((ArithmeticConstant) c2);
} else if (op instanceof ShrExpr) {
return ((ArithmeticConstant) c1).shiftRight((ArithmeticConstant) c2);
} else if (op instanceof UshrExpr) {
return ((ArithmeticConstant) c1).unsignedShiftRight((ArithmeticConstant) c2);
} else if (op instanceof CmpExpr) {
if ((c1 instanceof LongConstant) && (c2 instanceof LongConstant)) {
return ((LongConstant) c1).cmp((LongConstant) c2);
} else {
throw new IllegalArgumentException("CmpExpr: LongConstant(s) expected");
}
} else if ((op instanceof CmpgExpr) || (op instanceof CmplExpr)) {
if ((c1 instanceof RealConstant) && (c2 instanceof RealConstant)) {
if (op instanceof CmpgExpr) {
return ((RealConstant) c1).cmpg((RealConstant) c2);
} else if (op instanceof CmplExpr) {
return ((RealConstant) c1).cmpl((RealConstant) c2);
}
} else {
throw new IllegalArgumentException("CmpExpr: RealConstant(s) expected");
}
} else {
throw new RuntimeException("unknown binop: " + op);
}
}
throw new RuntimeException("couldn't getConstantValueOf of: " + op);
} // getConstantValueOf
} // Evaluator
| 7,545
| 37.697436
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/FastAvailableExpressions.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.EquivalentValue;
import soot.SideEffectTester;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
import soot.util.HashChain;
/**
* Provides an user-interface for the AvailableExpressionsAnalysis class. Returns, for each statement, the list of
* expressions available before and after it.
*/
public class FastAvailableExpressions implements AvailableExpressions {
private static final Logger logger = LoggerFactory.getLogger(FastAvailableExpressions.class);
protected final Map<Unit, List<UnitValueBoxPair>> unitToPairsAfter;
protected final Map<Unit, List<UnitValueBoxPair>> unitToPairsBefore;
protected final Map<Unit, Chain<EquivalentValue>> unitToEquivsAfter;
protected final Map<Unit, Chain<EquivalentValue>> unitToEquivsBefore;
/** Wrapper for AvailableExpressionsAnalysis. */
public FastAvailableExpressions(Body b, SideEffectTester st) {
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Finding available expressions...");
}
final Chain<Unit> units = b.getUnits();
this.unitToPairsAfter = new HashMap<Unit, List<UnitValueBoxPair>>(units.size() * 2 + 1, 0.7f);
this.unitToPairsBefore = new HashMap<Unit, List<UnitValueBoxPair>>(units.size() * 2 + 1, 0.7f);
this.unitToEquivsAfter = new HashMap<Unit, Chain<EquivalentValue>>(units.size() * 2 + 1, 0.7f);
this.unitToEquivsBefore = new HashMap<Unit, Chain<EquivalentValue>>(units.size() * 2 + 1, 0.7f);
FastAvailableExpressionsAnalysis analysis =
new FastAvailableExpressionsAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b), b.getMethod(), st);
// Build unitToExprs map
for (Unit s : units) {
FlowSet<Value> set = analysis.getFlowBefore(s);
if (set instanceof ToppedSet && ((ToppedSet<Value>) set).isTop()) {
throw new RuntimeException("top! on " + s);
}
{
List<UnitValueBoxPair> pairsBefore = new ArrayList<UnitValueBoxPair>();
Chain<EquivalentValue> equivsBefore = new HashChain<EquivalentValue>();
for (Value v : set) {
Stmt containingStmt = (Stmt) analysis.rhsToContainingStmt.get(v);
pairsBefore.add(new UnitValueBoxPair(containingStmt, ((AssignStmt) containingStmt).getRightOpBox()));
EquivalentValue ev = new EquivalentValue(v);
if (!equivsBefore.contains(ev)) {
equivsBefore.add(ev);
}
}
unitToPairsBefore.put(s, pairsBefore);
unitToEquivsBefore.put(s, equivsBefore);
}
{
List<UnitValueBoxPair> pairsAfter = new ArrayList<UnitValueBoxPair>();
Chain<EquivalentValue> equivsAfter = new HashChain<EquivalentValue>();
for (Value v : analysis.getFlowAfter(s)) {
Stmt containingStmt = (Stmt) analysis.rhsToContainingStmt.get(v);
pairsAfter.add(new UnitValueBoxPair(containingStmt, ((AssignStmt) containingStmt).getRightOpBox()));
EquivalentValue ev = new EquivalentValue(v);
if (!equivsAfter.contains(ev)) {
equivsAfter.add(ev);
}
}
unitToPairsAfter.put(s, pairsAfter);
unitToEquivsAfter.put(s, equivsAfter);
}
}
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Found available expressions...");
}
}
/** Returns a List containing the UnitValueBox pairs corresponding to expressions available before u. */
@Override
public List<UnitValueBoxPair> getAvailablePairsBefore(Unit u) {
return unitToPairsBefore.get(u);
}
/** Returns a Chain containing the EquivalentValue objects corresponding to expressions available before u. */
@Override
public Chain<EquivalentValue> getAvailableEquivsBefore(Unit u) {
return unitToEquivsBefore.get(u);
}
/** Returns a List containing the EquivalentValue corresponding to expressions available after u. */
@Override
public List<UnitValueBoxPair> getAvailablePairsAfter(Unit u) {
return unitToPairsAfter.get(u);
}
/** Returns a List containing the UnitValueBox pairs corresponding to expressions available after u. */
@Override
public Chain<EquivalentValue> getAvailableEquivsAfter(Unit u) {
return unitToEquivsAfter.get(u);
}
}
| 5,472
| 37.542254
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/FastAvailableExpressionsAnalysis.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import soot.SideEffectTester;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.Expr;
import soot.jimple.FieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
/**
* Implements an available expressions analysis on local variables. The current implementation is slow but correct. A better
* implementation would use an implicit universe and the kill rule would be computed on-the-fly for each statement.
*/
public class FastAvailableExpressionsAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Value>> {
protected final FlowSet<Value> emptySet = new ToppedSet<Value>(new ArraySparseSet<Value>());
protected final SideEffectTester st;
/** maps an rhs to its containing stmt. object equality in rhs. */
protected final Map<Value, Unit> rhsToContainingStmt;
protected final Map<Unit, FlowSet<Value>> unitToGenerateSet;
public FastAvailableExpressionsAnalysis(DirectedGraph<Unit> dg, SootMethod m, SideEffectTester st) {
super(dg);
this.st = st;
this.rhsToContainingStmt = new HashMap<Value, Unit>();
this.unitToGenerateSet = new HashMap<Unit, FlowSet<Value>>(dg.size() * 2 + 1, 0.7f);
// Create generate sets
for (Unit s : dg) {
FlowSet<Value> genSet = this.emptySet.clone();
// In Jimple, expressions only occur as the RHS of an
// AssignStmt.
if (s instanceof AssignStmt) {
Value gen = ((AssignStmt) s).getRightOp();
if (gen instanceof Expr || gen instanceof FieldRef) {
this.rhsToContainingStmt.put(gen, s);
if (!(gen instanceof NewExpr || gen instanceof NewArrayExpr || gen instanceof NewMultiArrayExpr
|| gen instanceof InvokeExpr)) {
genSet.add(gen, genSet);
}
}
}
this.unitToGenerateSet.put(s, genSet);
}
doAnalysis();
}
@Override
protected FlowSet<Value> newInitialFlow() {
FlowSet<Value> newSet = emptySet.clone();
((ToppedSet<Value>) newSet).setTop(true);
return newSet;
}
@Override
protected FlowSet<Value> entryInitialFlow() {
return emptySet.clone();
}
@Override
protected void flowThrough(FlowSet<Value> in, Unit u, FlowSet<Value> out) {
in.copy(out);
if (((ToppedSet<Value>) in).isTop()) {
return;
}
// Perform generation
out.union(unitToGenerateSet.get(u), out);
// Perform kill.
if (((ToppedSet<Value>) out).isTop()) {
throw new RuntimeException("trying to kill on topped set!");
}
// iterate over things (avail) in out set.
for (Value avail : new ArrayList<Value>(out.toList())) {
if (avail instanceof FieldRef) {
if (st.unitCanWriteTo(u, avail)) {
out.remove(avail, out);
}
} else {
for (ValueBox vb : avail.getUseBoxes()) {
Value use = vb.getValue();
if (st.unitCanWriteTo(u, use)) {
out.remove(avail, out);
}
}
}
}
}
@Override
protected void merge(FlowSet<Value> inSet1, FlowSet<Value> inSet2, FlowSet<Value> outSet) {
inSet1.intersection(inSet2, outSet);
}
@Override
protected void copy(FlowSet<Value> sourceSet, FlowSet<Value> destSet) {
sourceSet.copy(destSet);
}
}
| 4,431
| 30.211268
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/FieldStaticnessCorrector.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import soot.Body;
import soot.ConflictingFieldRefException;
import soot.G;
import soot.Singletons;
import soot.SootField;
import soot.Unit;
import soot.jimple.AssignStmt;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.Jimple;
/**
* Transformer that checks whether a static field is used like an instance field. If this is the case, all instance
* references are replaced by static field references.
*
* @author Steven Arzt
*/
public class FieldStaticnessCorrector extends AbstractStaticnessCorrector {
public FieldStaticnessCorrector(Singletons.Global g) {
}
public static FieldStaticnessCorrector v() {
return G.v().soot_jimple_toolkits_scalar_FieldStaticnessCorrector();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
// Some apps reference static fields as instance fields. We need to fix
// this for not breaking the client analysis.
for (Unit u : b.getUnits()) {
if (u instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) u;
if (assignStmt.containsFieldRef()) {
FieldRef ref = assignStmt.getFieldRef();
// Make sure that the target class has already been loaded
if (isTypeLoaded(ref.getFieldRef().type())) {
try {
if (ref instanceof InstanceFieldRef) {
SootField fld = ref.getField();
if (fld != null && fld.isStatic()) {
if (assignStmt.getLeftOp() == ref) {
assignStmt.setLeftOp(Jimple.v().newStaticFieldRef(ref.getField().makeRef()));
} else if (assignStmt.getRightOp() == ref) {
assignStmt.setRightOp(Jimple.v().newStaticFieldRef(ref.getField().makeRef()));
}
}
}
} catch (ConflictingFieldRefException ex) {
// That field is broken, just don't touch it
}
}
}
}
}
}
}
| 2,895
| 33.47619
| 115
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/IdentityCastEliminator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Local;
import soot.Singletons;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
/**
* Transformer that removes unnecessary identity casts such as
*
* $i3 = (int) $i3
*
* when $i3 is already of type "int".
*
* @author Steven Arzt
*/
public class IdentityCastEliminator extends BodyTransformer {
public IdentityCastEliminator(Singletons.Global g) {
}
public static IdentityCastEliminator v() {
return G.v().soot_jimple_toolkits_scalar_IdentityCastEliminator();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
for (Iterator<Unit> unitIt = b.getUnits().iterator(); unitIt.hasNext();) {
Unit curUnit = unitIt.next();
if (curUnit instanceof AssignStmt) {
final AssignStmt assignStmt = (AssignStmt) curUnit;
final Value leftOp = assignStmt.getLeftOp();
final Value rightOp = assignStmt.getRightOp();
if (leftOp instanceof Local && rightOp instanceof CastExpr) {
final CastExpr ce = (CastExpr) rightOp;
final Value castOp = ce.getOp();
// If this a cast such as a = (X) a, we can remove the whole line.
// Otherwise, if only the types match, we can replace the typecast
// with a normal assignment.
if (castOp.getType() == ce.getCastType()) {
if (leftOp == castOp) {
unitIt.remove();
} else {
assignStmt.setRightOp(castOp);
}
}
}
}
}
}
}
| 2,546
| 29.686747
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/IdentityOperationEliminator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.DoubleType;
import soot.FloatType;
import soot.G;
import soot.IntType;
import soot.LongType;
import soot.Singletons;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AddExpr;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.FloatConstant;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.MulExpr;
import soot.jimple.OrExpr;
import soot.jimple.SubExpr;
import soot.util.Chain;
/**
* Transformer that eliminates unnecessary logic operations such as
*
* $z0 = a | 0
*
* which can more easily be represented as
*
* $z0 = a
*
* @author Steven Arzt
*/
public class IdentityOperationEliminator extends BodyTransformer {
public IdentityOperationEliminator(Singletons.Global g) {
}
public static IdentityOperationEliminator v() {
return G.v().soot_jimple_toolkits_scalar_IdentityOperationEliminator();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
final Chain<Unit> units = b.getUnits();
for (Unit u : units) {
if (u instanceof AssignStmt) {
final AssignStmt assignStmt = (AssignStmt) u;
final Value rightOp = assignStmt.getRightOp();
if (rightOp instanceof AddExpr) {
// a = b + 0 --> a = b
// a = 0 + b --> a = b
BinopExpr aer = (BinopExpr) rightOp;
if (isConstZero(aer.getOp1())) {
assignStmt.setRightOp(aer.getOp2());
} else if (isConstZero(aer.getOp2())) {
assignStmt.setRightOp(aer.getOp1());
}
} else if (rightOp instanceof SubExpr) {
// a = b - 0 --> a = b
BinopExpr aer = (BinopExpr) rightOp;
if (isConstZero(aer.getOp2())) {
assignStmt.setRightOp(aer.getOp1());
}
} else if (rightOp instanceof MulExpr) {
// a = b * 0 --> a = 0
// a = 0 * b --> a = 0
BinopExpr aer = (BinopExpr) rightOp;
if (isConstZero(aer.getOp1())) {
assignStmt.setRightOp(getZeroConst(assignStmt.getLeftOp().getType()));
} else if (isConstZero(aer.getOp2())) {
assignStmt.setRightOp(getZeroConst(assignStmt.getLeftOp().getType()));
}
} else if (rightOp instanceof OrExpr) {
// a = b | 0 --> a = b
// a = 0 | b --> a = b
OrExpr orExpr = (OrExpr) rightOp;
if (isConstZero(orExpr.getOp1())) {
assignStmt.setRightOp(orExpr.getOp2());
} else if (isConstZero(orExpr.getOp2())) {
assignStmt.setRightOp(orExpr.getOp1());
}
}
}
}
// In a second step, we remove assingments such as <a = a>
for (Iterator<Unit> unitIt = units.iterator(); unitIt.hasNext();) {
Unit u = unitIt.next();
if (u instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) u;
if (assignStmt.getLeftOp() == assignStmt.getRightOp()) {
unitIt.remove();
}
}
}
}
/**
* Gets the constant value 0 with the given type (integer, float, etc.)
*
* @param type
* The type for which to get the constant zero value
* @return The constant zero value of the given type
*/
private static Value getZeroConst(Type type) {
if (type instanceof IntType) {
return IntConstant.v(0);
} else if (type instanceof LongType) {
return LongConstant.v(0);
} else if (type instanceof FloatType) {
return FloatConstant.v(0);
} else if (type instanceof DoubleType) {
return DoubleConstant.v(0);
}
throw new RuntimeException("Unsupported numeric type");
}
/**
* Checks whether the given value is the constant integer 0
*
* @param op
* The value to check
* @return True if the given value is the constant integer 0, otherwise false
*/
private static boolean isConstZero(Value op) {
return (op instanceof IntConstant) && (((IntConstant) op).value == 0);
}
}
| 5,013
| 30.734177
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/LocalCreation.java
|
package soot.jimple.toolkits.scalar;
import java.util.Collection;
import soot.Local;
import soot.Type;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public abstract class LocalCreation {
protected final Collection<Local> localChain;
protected final String prefix;
public LocalCreation(Collection<Local> locals, String prefix) {
this.localChain = locals;
this.prefix = prefix;
}
/**
* returns a new local with the prefix given to the constructor (or the default-prefix if none has been given) and the
* given type.<br>
* The returned local will automatically added to the locals-chain.<br>
* The local will be of the form: <tt>prefix</tt><i>X</i> (where the last <i>X</i> is a number, so the local name is
* unique).
*
* @param type
* the Type of the new local.
* @return a new local with a unique name and the given type.
*/
public abstract Local newLocal(Type type);
/**
* returns a new local with the given prefix and the given type.<br>
* the returned local will automatically added to the locals-chain. The local will be of the form: <tt>prefix</tt><i>X</i>
* (where the last <i>X</i> is a number, so the localname is unique).
*
* @param prefix
* the prefix for the now local.
* @param type
* the Type of the now local.
* @return a local with the given prefix and the given type.
*/
public abstract Local newLocal(String prefix, Type type);
}
| 2,219
| 32.636364
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/LocalNameStandardizer.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.ErroneousType;
import soot.FloatType;
import soot.G;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.NullType;
import soot.PhaseOptions;
import soot.ShortType;
import soot.Singletons;
import soot.StmtAddressType;
import soot.Type;
import soot.UnknownType;
import soot.Value;
import soot.ValueBox;
import soot.util.Chain;
public class LocalNameStandardizer extends BodyTransformer {
public LocalNameStandardizer(Singletons.Global g) {
}
public static LocalNameStandardizer v() {
return G.v().soot_jimple_toolkits_scalar_LocalNameStandardizer();
}
private static int digits(int n) {
int len = String.valueOf(n).length();
return (n < 0) ? len - 1 : len;
}
private static String genName(String prefix, String type, int n, int digits) {
return String.format("%s%s%0" + digits + "d", prefix, type, n);
}
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
/*
* The goal of this option is to ensure that local ordering remains consistent between different iterations of soot. This
* helps to ensure things like stable string representations of instructions and stable jimple representations of a
* methods body when soot is used to load the same code in different iterations.
*
* First sorts the locals alphabetically by the string representation of their type. Then if there are two locals with
* the same type, it uses the only other source of structurally stable information (i.e. the instructions themselves) to
* produce an ordering for the locals that remains consistent between different soot instances. It achieves this by
* determining the position of a local's first occurrence in the instruction's list of definition statements. This
* position is then used to sort the locals with the same type in an ascending order.
*
* The only times that this may not produce a consistent ordering for the locals between different soot instances is if a
* local is never defined in the instructions or if the instructions themselves are changed in some way that effects the
* ordering of the locals. In the first case, if a local is never defined, the other jimple body phases will remove this
* local as it is unused. As such, all we have to do is rerun this LocalNameStandardizer after all other jimple body
* phases to eliminate any ambiguity introduced by these phases and by the removed unused locals. In the second case, if
* the instructions themselves changed then the user would have had to intentionally told soot to modify the instructions
* of the code. Otherwise, the instructions would not have changed because we assume the instructions to always be
* structurally stable between different instances of soot. As such, in this instance, the user should not be expecting
* soot to produce the same output as the input and thus the ordering of the locals does not matter.
*/
final boolean sortLocals = PhaseOptions.getBoolean(options, "sort-locals");
if (sortLocals) {
Chain<Local> locals = body.getLocals();
ArrayList<Local> sortedLocals = new ArrayList<Local>(locals);
Collections.sort(sortedLocals, new Comparator<Local>() {
private Map<Local, Integer> firstOccuranceCache = new HashMap<Local, Integer>();
private final List<ValueBox> defs = body.getDefBoxes();
@Override
public int compare(Local arg0, Local arg1) {
int ret = arg0.getType().toString().compareTo(arg1.getType().toString());
if (ret == 0) {
ret = Integer.compare(getFirstOccurance(arg0), getFirstOccurance(arg1));
}
return ret;
}
private int getFirstOccurance(Local l) {
Integer cur = firstOccuranceCache.get(l);
if (cur != null) {
return cur;
} else {
int count = 0;
int first = -1;
for (ValueBox vb : defs) {
Value v = vb.getValue();
if (v instanceof Local && l.equals(v)) {
first = count;
break;
}
count++;
}
firstOccuranceCache.put(l, first);
return first;
}
}
});
locals.clear();
locals.addAll(sortedLocals);
}
if (!PhaseOptions.getBoolean(options, "only-stack-locals")) {
// Change the names to the standard forms now.
final BooleanType booleanType = BooleanType.v();
final ByteType byteType = ByteType.v();
final ShortType shortType = ShortType.v();
final CharType charType = CharType.v();
final IntType intType = IntType.v();
final LongType longType = LongType.v();
final DoubleType doubleType = DoubleType.v();
final FloatType floatType = FloatType.v();
final ErroneousType erroneousType = ErroneousType.v();
final UnknownType unknownType = UnknownType.v();
final StmtAddressType stmtAddressType = StmtAddressType.v();
final NullType nullType = NullType.v();
final Chain<Local> locals = body.getLocals();
final int maxDigits = sortLocals ? digits(locals.size()) : 1;
int objectCount = 0;
int intCount = 0;
int longCount = 0;
int floatCount = 0;
int doubleCount = 0;
int addressCount = 0;
int errorCount = 0;
int nullCount = 0;
for (Local l : locals) {
final String prefix = l.getName().startsWith("$") ? "$" : "";
final Type type = l.getType();
if (booleanType.equals(type)) {
l.setName(genName(prefix, "z", intCount++, maxDigits));
} else if (byteType.equals(type)) {
l.setName(genName(prefix, "b", longCount++, maxDigits));
} else if (shortType.equals(type)) {
l.setName(genName(prefix, "s", longCount++, maxDigits));
} else if (charType.equals(type)) {
l.setName(genName(prefix, "c", longCount++, maxDigits));
} else if (intType.equals(type)) {
l.setName(genName(prefix, "i", longCount++, maxDigits));
} else if (longType.equals(type)) {
l.setName(genName(prefix, "l", longCount++, maxDigits));
} else if (doubleType.equals(type)) {
l.setName(genName(prefix, "d", doubleCount++, maxDigits));
} else if (floatType.equals(type)) {
l.setName(genName(prefix, "f", floatCount++, maxDigits));
} else if (stmtAddressType.equals(type)) {
l.setName(genName(prefix, "a", addressCount++, maxDigits));
} else if (erroneousType.equals(type) || unknownType.equals(type)) {
l.setName(genName(prefix, "e", errorCount++, maxDigits));
} else if (nullType.equals(type)) {
l.setName(genName(prefix, "n", nullCount++, maxDigits));
} else {
l.setName(genName(prefix, "r", objectCount++, maxDigits));
}
}
}
}
}
| 8,127
| 40.258883
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/MethodStaticnessCorrector.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.Modifier;
import soot.Scene;
import soot.Singletons;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.InvokeExpr;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
/**
* Transformer that checks whether an instance method is used like a static method, and can easily be made static, i.e., does
* not reference any field or method in the "this" object. In this case, we make the method static, so that it complies with
* the invocations.
*
* Attention: This is not really a body transformer. It checks the current body, but modifies the invocation target.
*
* @author Steven Arzt
*/
public class MethodStaticnessCorrector extends AbstractStaticnessCorrector {
private static final Logger logger = LoggerFactory.getLogger(MethodStaticnessCorrector.class);
public MethodStaticnessCorrector(Singletons.Global g) {
}
public static MethodStaticnessCorrector v() {
return G.v().soot_jimple_toolkits_scalar_MethodStaticnessCorrector();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext();) {
Unit u = unitIt.next();
if (u instanceof Stmt) {
Stmt s = (Stmt) u;
if (s.containsInvokeExpr()) {
InvokeExpr iexpr = s.getInvokeExpr();
if (iexpr instanceof StaticInvokeExpr) {
SootMethodRef methodRef = iexpr.getMethodRef();
if (isClassLoaded(methodRef.declaringClass())) {
SootMethod target = Scene.v().grabMethod(methodRef.getSignature());
if (target != null && !target.isStatic()) {
if (canBeMadeStatic(target)) {
// Remove the this-assignment to prevent
// 'this-assignment in a static method!' exception
Body targetBody = target.getActiveBody();
targetBody.getUnits().remove(targetBody.getThisUnit());
target.setModifiers(target.getModifiers() | Modifier.STATIC);
logger.warn(target.getName() + " changed into a static method");
}
}
}
}
}
}
}
}
/**
* Checks whether the given method can be made static, i.e., does not reference the "this" object
*
* @param target
* The method to check
* @return True if the given method can be made static, otherwise false
*/
private boolean canBeMadeStatic(SootMethod target) {
if (!target.hasActiveBody()) {
return false;
}
Body body = target.getActiveBody();
Value thisLocal = body.getThisLocal();
for (Unit u : body.getUnits()) {
for (ValueBox vb : u.getUseBoxes()) {
if (vb.getValue() == thisLocal) {
return false;
}
}
}
return true;
}
}
| 3,931
| 32.896552
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/NopEliminator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.NopUnit;
import soot.Singletons;
import soot.Trap;
import soot.Unit;
import soot.jimple.NopStmt;
import soot.options.Options;
import soot.util.Chain;
public class NopEliminator extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(NopEliminator.class);
public NopEliminator(Singletons.Global g) {
}
public static NopEliminator v() {
return G.v().soot_jimple_toolkits_scalar_NopEliminator();
}
/**
* Removes {@link NopStmt}s from the passed body . Complexity is linear with respect to the statements.
*/
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Removing nops...");
}
final Chain<Trap> traps = b.getTraps();
final Chain<Unit> units = b.getUnits();
// Just do one trivial pass.
for (Iterator<Unit> stmtIt = units.snapshotIterator(); stmtIt.hasNext();) {
Unit u = stmtIt.next();
if (u instanceof NopUnit) {
// Hack: do not remove nop, if is is used for a Trap which
// is at the very end of the code.
boolean keepNop = false;
if (units.getLast() == u) {
for (Trap t : traps) {
if (t.getEndUnit() == u) {
keepNop = true;
}
}
}
if (!keepNop) {
units.remove(u);
}
}
}
}
}
| 2,471
| 28.082353
| 105
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/PessimisticAvailableExpressionsAnalysis.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SideEffectTester;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.FlowSet;
/**
* Implements an available expressions analysis on local variables. pessimistic analysis - for teaching 621
*/
public class PessimisticAvailableExpressionsAnalysis extends SlowAvailableExpressionsAnalysis {
public PessimisticAvailableExpressionsAnalysis(DirectedGraph<Unit> dg, SootMethod m, SideEffectTester st) {
super(dg);
}
@Override
protected FlowSet<Value> newInitialFlow() {
return emptySet.clone();
}
}
| 1,446
| 30.456522
| 109
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/SlowAvailableExpressions.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import soot.Body;
import soot.EquivalentValue;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Stmt;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
import soot.util.HashChain;
/**
* Provides an user-interface for the AvailableExpressionsAnalysis class. Returns, for each statement, the list of
* expressions available before and after it.
*/
public class SlowAvailableExpressions implements AvailableExpressions {
protected final Map<Unit, List<UnitValueBoxPair>> unitToPairsAfter;
protected final Map<Unit, List<UnitValueBoxPair>> unitToPairsBefore;
protected final Map<Unit, Chain<EquivalentValue>> unitToEquivsAfter;
protected final Map<Unit, Chain<EquivalentValue>> unitToEquivsBefore;
/** Wrapper for SlowAvailableExpressionsAnalysis. */
public SlowAvailableExpressions(Body b) {
final Chain<Unit> units = b.getUnits();
this.unitToPairsAfter = new HashMap<Unit, List<UnitValueBoxPair>>(units.size() * 2 + 1, 0.7f);
this.unitToPairsBefore = new HashMap<Unit, List<UnitValueBoxPair>>(units.size() * 2 + 1, 0.7f);
this.unitToEquivsAfter = new HashMap<Unit, Chain<EquivalentValue>>(units.size() * 2 + 1, 0.7f);
this.unitToEquivsBefore = new HashMap<Unit, Chain<EquivalentValue>>(units.size() * 2 + 1, 0.7f);
SlowAvailableExpressionsAnalysis analysis
= new SlowAvailableExpressionsAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b));
for (Unit s : units) {
{
List<UnitValueBoxPair> pairsBefore = new ArrayList<UnitValueBoxPair>();
Chain<EquivalentValue> equivsBefore = new HashChain<EquivalentValue>();
for (Value v : analysis.getFlowBefore(s)) {
Stmt containingStmt = analysis.rhsToContainingStmt.get(v);
pairsBefore.add(new UnitValueBoxPair(containingStmt, ((AssignStmt) containingStmt).getRightOpBox()));
EquivalentValue ev = new EquivalentValue(v);
if (!equivsBefore.contains(ev)) {
equivsBefore.add(ev);
}
}
unitToPairsBefore.put(s, pairsBefore);
unitToEquivsBefore.put(s, equivsBefore);
}
{
List<UnitValueBoxPair> pairsAfter = new ArrayList<UnitValueBoxPair>();
Chain<EquivalentValue> equivsAfter = new HashChain<EquivalentValue>();
for (Value v : analysis.getFlowAfter(s)) {
Stmt containingStmt = analysis.rhsToContainingStmt.get(v);
pairsAfter.add(new UnitValueBoxPair(containingStmt, ((AssignStmt) containingStmt).getRightOpBox()));
EquivalentValue ev = new EquivalentValue(v);
if (!equivsAfter.contains(ev)) {
equivsAfter.add(ev);
}
}
unitToPairsAfter.put(s, pairsAfter);
unitToEquivsAfter.put(s, equivsAfter);
}
}
}
/** Returns a List containing the UnitValueBox pairs corresponding to expressions available before u. */
@Override
public List<UnitValueBoxPair> getAvailablePairsBefore(Unit u) {
return unitToPairsBefore.get(u);
}
/** Returns a List containing the UnitValueBox pairs corresponding to expressions available after u. */
@Override
public List<UnitValueBoxPair> getAvailablePairsAfter(Unit u) {
return unitToPairsAfter.get(u);
}
/** Returns a Chain containing the EquivalentValue objects corresponding to expressions available before u. */
@Override
public Chain<EquivalentValue> getAvailableEquivsBefore(Unit u) {
return unitToEquivsBefore.get(u);
}
/** Returns a Chain containing the EquivalentValue objects corresponding to expressions available after u. */
@Override
public Chain<EquivalentValue> getAvailableEquivsAfter(Unit u) {
return unitToEquivsAfter.get(u);
}
}
| 4,724
| 37.729508
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/SlowAvailableExpressionsAnalysis.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import soot.EquivalentValue;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.Expr;
import soot.jimple.InvokeExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Stmt;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArrayFlowUniverse;
import soot.toolkits.scalar.ArrayPackedSet;
import soot.toolkits.scalar.BoundedFlowSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.FlowUniverse;
import soot.toolkits.scalar.ForwardFlowAnalysis;
import soot.util.Chain;
import soot.util.HashChain;
// future work: fieldrefs.
/**
* Implements an available expressions analysis on local variables. The current implementation is slow but correct. A better
* implementation would use an implicit universe and the kill rule would be computed on-the-fly for each statement.
*/
public class SlowAvailableExpressionsAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Value>> {
protected final Map<Unit, BoundedFlowSet<Value>> unitToGenerateSet;
protected final Map<Unit, BoundedFlowSet<Value>> unitToPreserveSet;
/** maps an rhs to its containing stmt. object equality in rhs. */
protected final Map<Value, Stmt> rhsToContainingStmt;
protected final FlowSet<Value> emptySet;
/** maps a Value to its EquivalentValue */
private final HashMap<Value, EquivalentValue> valueToEquivValue;
public SlowAvailableExpressionsAnalysis(DirectedGraph<Unit> dg) {
super(dg);
this.valueToEquivValue = new HashMap<Value, EquivalentValue>();
this.rhsToContainingStmt = new HashMap<Value, Stmt>();
/* we need a universe of all of the expressions. */
HashSet<Value> exprs = new HashSet<Value>();
// Consider "a + b". containingExprs maps a and b (object equality) both to "a + b" (equivalence).
Map<EquivalentValue, Chain<EquivalentValue>> containingExprs = new HashMap<EquivalentValue, Chain<EquivalentValue>>();
Map<EquivalentValue, Chain<Value>> equivValToSiblingList = new HashMap<EquivalentValue, Chain<Value>>();
// Create the set of all expressions, and a map from values to their containing expressions.
final UnitGraph g = (UnitGraph) dg;
for (Unit u : g.getBody().getUnits()) {
Stmt s = (Stmt) u;
if (s instanceof AssignStmt) {
Value v = ((AssignStmt) s).getRightOp();
rhsToContainingStmt.put(v, s);
EquivalentValue ev = valueToEquivValue.get(v);
if (ev == null) {
valueToEquivValue.put(v, ev = new EquivalentValue(v));
}
Chain<Value> sibList = equivValToSiblingList.get(ev);
if (sibList == null) {
equivValToSiblingList.put(ev, sibList = new HashChain<Value>());
}
if (!sibList.contains(v)) {
sibList.add(v);
}
if (!(v instanceof Expr)) {
continue;
}
if (!exprs.contains(v)) {
exprs.add(v);
// Add map values for contained objects.
for (ValueBox vb : v.getUseBoxes()) {
Value o = vb.getValue();
EquivalentValue eo = valueToEquivValue.get(o);
if (eo == null) {
valueToEquivValue.put(o, eo = new EquivalentValue(o));
}
sibList = equivValToSiblingList.get(eo);
if (sibList == null) {
equivValToSiblingList.put(eo, sibList = new HashChain<Value>());
}
if (!sibList.contains(o)) {
sibList.add(o);
}
Chain<EquivalentValue> l = containingExprs.get(eo);
if (l == null) {
containingExprs.put(eo, l = new HashChain<EquivalentValue>());
}
if (!l.contains(ev)) {
l.add(ev);
}
}
}
}
}
FlowUniverse<Value> exprUniv = new ArrayFlowUniverse<Value>(exprs.toArray(new Value[exprs.size()]));
this.emptySet = new ArrayPackedSet<Value>(exprUniv);
// Create preserve sets.
this.unitToPreserveSet = new HashMap<Unit, BoundedFlowSet<Value>>(g.size() * 2 + 1, 0.7f);
for (Unit s : g) {
BoundedFlowSet<Value> killSet = new ArrayPackedSet<Value>(exprUniv);
// We need to do more! In particular handle invokeExprs, etc.
// For each def (say of x), kill the set of exprs containing x.
for (ValueBox box : s.getDefBoxes()) {
Chain<EquivalentValue> c = containingExprs.get(valueToEquivValue.get(box.getValue()));
if (c != null) {
for (EquivalentValue container : c) {
// Add all siblings of it.next().
for (Value sibVal : equivValToSiblingList.get(container)) {
killSet.add(sibVal);
}
}
}
}
// Store complement
killSet.complement(killSet);
unitToPreserveSet.put(s, killSet);
}
// Create generate sets
this.unitToGenerateSet = new HashMap<Unit, BoundedFlowSet<Value>>(g.size() * 2 + 1, 0.7f);
for (Unit s : g) {
BoundedFlowSet<Value> genSet = new ArrayPackedSet<Value>(exprUniv);
// In Jimple, expressions only occur as the RHS of an AssignStmt.
if (s instanceof AssignStmt) {
AssignStmt as = (AssignStmt) s;
Value gen = as.getRightOp();
if (gen instanceof Expr) {
if (!(gen instanceof NewExpr || gen instanceof NewArrayExpr || gen instanceof NewMultiArrayExpr
|| gen instanceof InvokeExpr)) {
genSet.add(gen);
}
}
}
// remove the kill set
genSet.intersection(unitToPreserveSet.get(s), genSet);
unitToGenerateSet.put(s, genSet);
}
doAnalysis();
}
@Override
protected FlowSet<Value> newInitialFlow() {
BoundedFlowSet<Value> out = (BoundedFlowSet<Value>) emptySet.clone();
out.complement(out);
return out;
}
@Override
protected FlowSet<Value> entryInitialFlow() {
return emptySet.clone();
}
@Override
protected void flowThrough(FlowSet<Value> in, Unit unit, FlowSet<Value> out) {
// Perform kill
in.intersection(unitToPreserveSet.get(unit), out);
// Perform generation
out.union(unitToGenerateSet.get(unit));
}
@Override
protected void merge(FlowSet<Value> inSet1, FlowSet<Value> inSet2, FlowSet<Value> outSet) {
inSet1.intersection(inSet2, outSet);
}
@Override
protected void copy(FlowSet<Value> sourceSet, FlowSet<Value> destSet) {
sourceSet.copy(destSet);
}
}
| 7,442
| 32.527027
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/ToppedSet.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.List;
import soot.toolkits.scalar.AbstractFlowSet;
import soot.toolkits.scalar.BoundedFlowSet;
import soot.toolkits.scalar.FlowSet;
/**
* Represents information for flow analysis, adding a top element to a lattice. A FlowSet is an element of a lattice; this
* lattice might be described by a FlowUniverse. If add, remove, size, isEmpty, toList and contains are implemented, the
* lattice must be the powerset of some set.
*
*/
public class ToppedSet<T> extends AbstractFlowSet<T> {
protected final FlowSet<T> underlyingSet;
protected boolean isTop;
public ToppedSet(FlowSet<T> under) {
underlyingSet = under;
}
@Override
public ToppedSet<T> clone() {
ToppedSet<T> newSet = new ToppedSet<T>(underlyingSet.clone());
newSet.setTop(this.isTop());
return newSet;
}
@Override
public void copy(FlowSet<T> d) {
if (this != d) {
ToppedSet<T> dest = (ToppedSet<T>) d;
dest.isTop = this.isTop;
if (!this.isTop()) {
this.underlyingSet.copy(dest.underlyingSet);
}
}
}
@Override
public FlowSet<T> emptySet() {
return new ToppedSet<T>(underlyingSet.emptySet());
}
@Override
public void clear() {
isTop = false;
underlyingSet.clear();
}
@Override
public void union(FlowSet<T> o, FlowSet<T> d) {
if (o instanceof ToppedSet && d instanceof ToppedSet) {
ToppedSet<T> other = (ToppedSet<T>) o;
ToppedSet<T> dest = (ToppedSet<T>) d;
if (this.isTop()) {
this.copy(dest);
} else if (other.isTop()) {
other.copy(dest);
} else {
underlyingSet.union(other.underlyingSet, dest.underlyingSet);
dest.setTop(false);
}
} else {
super.union(o, d);
}
}
@Override
public void intersection(FlowSet<T> o, FlowSet<T> d) {
if (this.isTop()) {
o.copy(d);
return;
}
ToppedSet<T> other = (ToppedSet<T>) o, dest = (ToppedSet<T>) d;
if (other.isTop()) {
this.copy(dest);
} else {
underlyingSet.intersection(other.underlyingSet, dest.underlyingSet);
dest.setTop(false);
}
}
@Override
public void difference(FlowSet<T> o, FlowSet<T> d) {
ToppedSet<T> other = (ToppedSet<T>) o, dest = (ToppedSet<T>) d;
if (this.isTop()) {
if (other.isTop()) {
dest.clear();
} else if (other.underlyingSet instanceof BoundedFlowSet) {
((BoundedFlowSet<T>) other.underlyingSet).complement(dest);
} else {
throw new RuntimeException("can't take difference!");
}
} else if (other.isTop()) {
dest.clear();
} else {
underlyingSet.difference(other.underlyingSet, dest.underlyingSet);
}
}
@Override
public boolean isEmpty() {
return this.isTop() ? false : underlyingSet.isEmpty();
}
@Override
public int size() {
if (this.isTop()) {
throw new UnsupportedOperationException();
}
return underlyingSet.size();
}
@Override
public void add(T obj) {
if (!this.isTop()) {
underlyingSet.add(obj);
}
}
@Override
public void remove(T obj) {
if (!this.isTop()) {
underlyingSet.remove(obj);
}
}
@Override
public boolean contains(T obj) {
return this.isTop() ? true : underlyingSet.contains(obj);
}
@Override
public List<T> toList() {
if (this.isTop()) {
throw new UnsupportedOperationException();
}
return underlyingSet.toList();
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + this.underlyingSet.hashCode();
hash = 97 * hash + (this.isTop() ? 1 : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
final ToppedSet<?> other = (ToppedSet<?>) obj;
return (this.isTop() == other.isTop()) && this.underlyingSet.equals(other.underlyingSet);
}
@Override
public String toString() {
return isTop() ? "{TOP}" : underlyingSet.toString();
}
@Override
public Iterator<T> iterator() {
if (isTop()) {
throw new UnsupportedOperationException();
}
return underlyingSet.iterator();
}
public void setTop(boolean top) {
isTop = top;
}
public boolean isTop() {
return isTop;
}
}
| 5,197
| 23.752381
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/UnconditionalBranchFolder.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Phong Co
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collections;
import java.util.HashMap;
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.BodyTransformer;
import soot.G;
import soot.Singletons;
import soot.Unit;
import soot.UnitBox;
import soot.Value;
import soot.jimple.ConditionExpr;
import soot.jimple.GotoStmt;
import soot.jimple.IfStmt;
import soot.jimple.Jimple;
import soot.jimple.Stmt;
import soot.jimple.StmtBody;
import soot.jimple.SwitchStmt;
import soot.options.Options;
import soot.shimple.Shimple;
import soot.shimple.ShimpleBody;
import soot.util.Chain;
public class UnconditionalBranchFolder extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(UnconditionalBranchFolder.class);
public UnconditionalBranchFolder(Singletons.Global g) {
}
public static UnconditionalBranchFolder v() {
return G.v().soot_jimple_toolkits_scalar_UnconditionalBranchFolder();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
final boolean verbose = Options.v().verbose();
if (verbose) {
logger.debug("[" + b.getMethod().getName() + "] Folding unconditional branches...");
}
final Transformer transformer = new Transformer((StmtBody) b);
int iter = 0;
Result res;
do {
res = transformer.transform();
if (verbose) {
iter++;
logger.debug("[" + b.getMethod().getName() + "] " + res.getNumFixed(BranchType.TOTAL_COUNT) + " of "
+ res.getNumFound(BranchType.TOTAL_COUNT) + " branches folded in iteration " + iter + ".");
}
} while (res.modified);
}
private static enum BranchType {
TOTAL_COUNT,
GOTO_GOTO,
IF_TO_GOTO,
GOTO_IF,
IF_TO_IF,
IF_SAME_TARGET,
GOTO_SUCCESSOR;
} // BranchType
private static class HandleRes {
final BranchType type;
final boolean fixed;
public HandleRes(BranchType type, boolean fixed) {
this.type = type;
this.fixed = fixed;
}
}
private static class Result {
private final int[] numFound = new int[BranchType.values().length];
private final int[] numFixed = new int[BranchType.values().length];
private boolean modified;
public void updateCounters(HandleRes r) {
updateCounters(r.type, r.fixed);
}
public void updateCounters(BranchType type, boolean fixed) {
final int indexTotal = BranchType.TOTAL_COUNT.ordinal();
final int indexUpdate = type.ordinal();
final boolean updatingTotal = indexUpdate == indexTotal;
if (updatingTotal && fixed) {
throw new IllegalArgumentException("Cannot mark TOTAL as fixed!");
}
numFound[indexTotal]++;
if (!updatingTotal) {
numFound[indexUpdate]++;
}
if (fixed) {
modified = true;
numFixed[indexTotal]++;
numFixed[indexUpdate]++;
}
}
public int getNumFound(BranchType type) {
final int indexCurrType = type.ordinal();
return numFound[indexCurrType];
}
public int getNumFixed(BranchType type) {
final int indexCurrType = type.ordinal();
return numFixed[indexCurrType];
}
} // Result
private static class Transformer {
private final Map<Stmt, Stmt> stmtMap;
private final boolean isShimple;
private final Chain<Unit> units;
public Transformer(StmtBody body) {
this.stmtMap = new HashMap<Stmt, Stmt>();
this.isShimple = body instanceof ShimpleBody;
this.units = body.getUnits();
}
public Result transform() {
stmtMap.clear();// reset in case of multiple passes
Result res = new Result();
NextUnit: for (final Iterator<Unit> stmtIt = units.iterator(); stmtIt.hasNext();) {
Unit stmt = stmtIt.next();
if (stmt instanceof GotoStmt) {
final GotoStmt stmtAsGotoStmt = (GotoStmt) stmt;
final Stmt gotoTarget = (Stmt) stmtAsGotoStmt.getTarget();
// Handle special successor case
if (stmtIt.hasNext()) {
Unit successor = units.getSuccOf(stmt);
// "goto [successor]" -> remove the statement
if (successor == gotoTarget) {
if (!isShimple || removalIsSafeInShimple(stmt)) {
stmtIt.remove();
res.updateCounters(BranchType.GOTO_SUCCESSOR, true);
} else {
res.updateCounters(BranchType.GOTO_SUCCESSOR, false);
}
continue NextUnit;
}
}
// Main handling for GotoStmt
res.updateCounters(handle(stmtAsGotoStmt, gotoTarget));
} else if (stmt instanceof IfStmt) {
final IfStmt stmtAsIfStmt = (IfStmt) stmt;
Stmt ifTarget = stmtAsIfStmt.getTarget();
// Handle special successor cases
if (stmtIt.hasNext()) {
final Unit successor = units.getSuccOf(stmt);
if (successor == ifTarget) {
// "if C goto [successor]" -> remove the IfStmt
if (!isShimple || removalIsSafeInShimple(stmt)) {
stmtIt.remove();
res.updateCounters(BranchType.IF_SAME_TARGET, true);
} else {
res.updateCounters(BranchType.IF_SAME_TARGET, false);
}
continue NextUnit;
} else if (successor instanceof GotoStmt) {
final GotoStmt succAsGoto = (GotoStmt) successor;
final Stmt gotoTarget = (Stmt) succAsGoto.getTarget();
if (gotoTarget == ifTarget) {
// "if C goto X";"goto X" -> remove the IfStmt
if (!isShimple || removalIsSafeInShimple(stmt)) {
stmtIt.remove();
res.updateCounters(BranchType.IF_SAME_TARGET, true);
} else {
res.updateCounters(BranchType.IF_SAME_TARGET, false);
}
continue NextUnit;
} else {
final Unit afterSuccessor = units.getSuccOf(successor);
if (afterSuccessor == ifTarget) {
// "if C goto Y";"goto X";"Y" -> "if !C goto X";"goto Y";"Y"
Value oldCondition = stmtAsIfStmt.getCondition();
assert (oldCondition instanceof ConditionExpr);// JIfStmt forces this
stmtAsIfStmt.setCondition(reverseCondition((ConditionExpr) oldCondition));
succAsGoto.setTarget(ifTarget);
stmtAsIfStmt.setTarget(gotoTarget);
ifTarget = gotoTarget;
// NOTE: No need to remove the goto [successor] because it
// is processed by the next iteration of the main loop.
// NOTE: Nothing is removed here, it is a simple refactoring.
// Thus, it can fall through to the main handler below where
// the condition (and possible removal) will be counted.
}
}
}
}
// Main handling for IfStmt
res.updateCounters(handle(stmtAsIfStmt, ifTarget));
} else if (stmt instanceof SwitchStmt) {
final SwitchStmt stmtAsSwitchStmt = (SwitchStmt) stmt;
for (UnitBox ub : stmtAsSwitchStmt.getUnitBoxes()) { // includes all cases and default
Stmt caseTarget = (Stmt) ub.getUnit();
if (caseTarget instanceof GotoStmt) {
// "goto [goto X]" -> "goto X"
Stmt newTarget = getFinalTarget(caseTarget);
if (newTarget == null || newTarget == caseTarget) {
res.updateCounters(BranchType.GOTO_GOTO, false);
} else {
ub.setUnit(newTarget);
res.updateCounters(BranchType.GOTO_GOTO, true);
}
}
}
}
}
return res;
} // transform
// NOTE: factored out to ensure all cases return a result and thus are counted
private HandleRes handle(GotoStmt gotoStmt, Stmt target) {
assert (gotoStmt.getTarget() == target);// pre-conditions
if (target instanceof GotoStmt) {
// "goto [goto X]" -> "goto X"
if (!isShimple || removalIsSafeInShimple(target)) {
Stmt newTarget = getFinalTarget(target);
if (newTarget == null) {
newTarget = gotoStmt;
}
if (newTarget != target) {
if (isShimple) {
// NOTE: It is safe to redirect all PhiExpr pointers since removalIsSafeInShimple(..) ensures there is a single
// predecessor for 'target' and we know 'gotoStmt' is that predecessor. Hence, 'target' becomes unreachable
// which means any PhiExpr that had 'target' as a predecessor now has 'gotoStmt' as a predecessor instead.
assert (hasNoPointersOrSingleJumpPred(target, gotoStmt));
Shimple.redirectPointers(target, gotoStmt);
}
gotoStmt.setTarget(newTarget);
return new HandleRes(BranchType.GOTO_GOTO, true);
}
}
return new HandleRes(BranchType.GOTO_GOTO, false);
} else if (target instanceof IfStmt) {
// "goto [if ...]" -> no change
return new HandleRes(BranchType.GOTO_IF, false);
} else {
return new HandleRes(BranchType.TOTAL_COUNT, false);
}
}
// NOTE: factored out to ensure all cases return a result and thus are counted
private HandleRes handle(final IfStmt ifStmt, final Stmt target) {
assert (ifStmt.getTarget() == target);// pre-conditions
if (target instanceof GotoStmt) {
// "if C goto [goto X]" -> "if C goto X"
if (!isShimple || removalIsSafeInShimple(target)) {
Stmt newTarget = getFinalTarget(target);
if (newTarget == null) {
newTarget = ifStmt;
}
if (newTarget != target) { // skip if target would not change
if (isShimple) {
// NOTE: It is safe to redirect all PhiExpr pointers since removalIsSafeInShimple(..) ensures there is a single
// predecessor for 'target' and we know 'ifStmt' is that predecessor. Hence, 'target' becomes unreachable which
// means any PhiExpr that had 'target' as a predecessor now has 'ifStmt' as a predecessor instead.
assert (hasNoPointersOrSingleJumpPred(target, ifStmt));
Shimple.redirectPointers(target, ifStmt);
}
ifStmt.setTarget(newTarget);
return new HandleRes(BranchType.IF_TO_GOTO, true);
}
}
return new HandleRes(BranchType.IF_TO_GOTO, false);
} else if (target instanceof IfStmt) {
// "if C goto [if C goto X]" -> "if C goto X"
if (ifStmt != target) { // skip when IfStmt jumps to itself
if (!isShimple || removalIsSafeInShimple(target)) {
final IfStmt targetAsIfStmt = (IfStmt) target;
Stmt newTarget = targetAsIfStmt.getTarget();
if (newTarget != target) { // skip if target would not change
// Perform "jump threading" optimization. If the target IfStmt
// has the same condition as the first IfStmt, then the first
// should jump directly to the target of the target IfStmt.
// TODO: This could also be done when the first condition
// implies the second but that's obviously more complicated
// to check. Could even do something if the first implies
// the negation of the second.
if (ifStmt.getCondition().equivTo(targetAsIfStmt.getCondition())) {
if (isShimple) {
// NOTE: It is safe to redirect all PhiExpr pointers since removalIsSafeInShimple(..)
// ensures there is a single predecessor for 'target' and we know 'ifStmt' is that
// predecessor. Hence, 'target' becomes unreachable which means any PhiExpr that
// had 'target' as a predecessor now has 'ifStmt' as a predecessor instead.
assert (hasNoPointersOrSingleJumpPred(target, ifStmt));
Shimple.redirectPointers(target, ifStmt);
}
ifStmt.setTarget(newTarget);
return new HandleRes(BranchType.IF_TO_IF, true);
}
}
}
}
return new HandleRes(BranchType.IF_TO_IF, false);
} else {
return new HandleRes(BranchType.TOTAL_COUNT, false);
}
}
/**
* @param stmt
* @param stmtMap
*
* @return the given {@link Stmt} if not a {@link GotoStmt}, otherwise, the final transitive target of the
* {@link GotoStmt} or {@code null} if that target is itself
*/
private Stmt getFinalTarget(Stmt stmt) {
// if not a goto, this is the final target
if (!(stmt instanceof GotoStmt)) {
return stmt;
}
// first map this statement to itself, so we can detect cycles
stmtMap.put(stmt, stmt);
Stmt target = (Stmt) ((GotoStmt) stmt).getTarget();
// check if target is in statement map
Stmt finalTarget;
if (stmtMap.containsKey(target)) {
// see if it maps to itself
finalTarget = stmtMap.get(target);
if (finalTarget == target) { // this is part of a cycle
finalTarget = null;
}
} else {
finalTarget = getFinalTarget(target);
}
stmtMap.put(stmt, finalTarget);
return finalTarget;
}
/**
* Checks if removing the given {@link Unit} is "safe" when the body contains {@link soot.shimple.PhiExpr}. Specifically,
* can {@link soot.shimple.Shimple#redirectToPreds(soot.Body, soot.Unit)} properly handle the phi back-reference update
* after the {@link Unit} is removed (removal is trivially safe if there are no phi back-references to the Unit).
*
* For instance, a jump cannot (easily) be removed if the Unit that jumps is the target of a Shimple back-reference and
* has multiple graph predecessors. Removing it would leave the related PhiExpr without a reference for every predecessor
* (i.e. the existing back-reference would move to whatever node is before the removed Unit in the Chain but any other
* predecessor of the Unit would not have a back-reference in the PhiExpr).
*/
private boolean removalIsSafeInShimple(Unit stmt) {
// To check this condition without building a graph, first check if there exist any UnitBox pointing to the Unit such
// that UnitBox.isBranchTarget() is false. That indicates the presence of a PhiExpr back-reference. In that case, count
// the remaining boxes pointing to the Unit and add one (1) if the chain predecessor falls through.
Unit chainPred = units.getPredOf(stmt);
if (chainPred == null) {
// Removing the head of the chain is safe.
return true;
}
List<UnitBox> boxesPointingToThis = stmt.getBoxesPointingToThis();
if (boxesPointingToThis.isEmpty()) {
// Removal is safe when there are no UnitBox that reference the Unit
// (because it implies that no PhiExpr/SUnitBox references the Unit).
return true;
}
// Now, scan all UnitBox pointing to the current Unit and determine if there exists a phi back-reference pointing to
// the current Unit. At the same time, collect the predecessors from the UnitBox references (i.e. jumps).
boolean hasBackref = false;
// NOTE: just counting won't work because fall-through pred could be an IfStmt and shouldn't be counted twice.
HashSet<UnitBox> predBoxes = new HashSet<UnitBox>();
for (UnitBox ub : boxesPointingToThis) {
if (ub.isBranchTarget()) {
assert (stmt == ub.getUnit());// sanity check
predBoxes.add(ub);
} else {
assert (ub instanceof soot.shimple.internal.SUnitBox);// sanity check
hasBackref = true;
}
}
if (!hasBackref) {
// Removal is safe when no PhiExpr/SUnitBox references the Unit.
return true;
}
// Removal is safe if there is exactly one predecessor (either fall-through or jump)
int predecessorCount = predBoxes.size();
if (predecessorCount > 1) {
return false;
}
// Add the fall-through predecessor (if applicable) and check the condition
if (chainPred.fallsThrough()) {
// Avoid counting it twice if the fall-through pred also jumps (i.e. was added above).
if (Collections.disjoint(chainPred.getUnitBoxes(), predBoxes)) {
predecessorCount++;
}
}
return predecessorCount == 1;
}
private boolean hasNoPointersOrSingleJumpPred(Unit toRemove, Unit jumpPred) {
boolean hasBackref = false;
HashSet<UnitBox> predBoxes = new HashSet<UnitBox>();
for (UnitBox ub : toRemove.getBoxesPointingToThis()) {
if (ub.isBranchTarget()) {
assert (toRemove == ub.getUnit());// sanity check
predBoxes.add(ub);
} else {
assert (ub instanceof soot.shimple.internal.SUnitBox);// sanity check
hasBackref = true;
}
}
// Has no Phi pointers
if (!hasBackref) {
return true;
}
// Ensure there exists a single branching predecessor and it is 'jumpPred' itself
if (predBoxes.size() != 1 || !jumpPred.getUnitBoxes().containsAll(predBoxes)) {
return false;
}
// If the unit chain has a predecessor and it falls through, then 'jumpPred' is not the only predecessor
Unit chainPred = units.getPredOf(toRemove);
return chainPred == null || !chainPred.fallsThrough();
}
} // Transformer
public static ConditionExpr reverseCondition(ConditionExpr cond) {
// NOTE: Adapted from the private reverseCondition(..) method in JimpleBodyBuilder.
ConditionExpr newExpr;
if (cond instanceof soot.jimple.EqExpr) {
newExpr = Jimple.v().newNeExpr(cond.getOp1(), cond.getOp2());
} else if (cond instanceof soot.jimple.NeExpr) {
newExpr = Jimple.v().newEqExpr(cond.getOp1(), cond.getOp2());
} else if (cond instanceof soot.jimple.GtExpr) {
newExpr = Jimple.v().newLeExpr(cond.getOp1(), cond.getOp2());
} else if (cond instanceof soot.jimple.GeExpr) {
newExpr = Jimple.v().newLtExpr(cond.getOp1(), cond.getOp2());
} else if (cond instanceof soot.jimple.LtExpr) {
newExpr = Jimple.v().newGeExpr(cond.getOp1(), cond.getOp2());
} else if (cond instanceof soot.jimple.LeExpr) {
newExpr = Jimple.v().newGtExpr(cond.getOp1(), cond.getOp2());
} else {
throw new RuntimeException("Unknown ConditionExpr");
}
newExpr.getOp1Box().addAllTagsOf(cond.getOp1Box());
newExpr.getOp2Box().addAllTagsOf(cond.getOp2Box());
return newExpr;
}
}
| 19,798
| 39.406122
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/UnreachableCodeEliminator.java
|
package soot.jimple.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Phong Co
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.PhaseOptions;
import soot.Scene;
import soot.Singletons;
import soot.Trap;
import soot.Unit;
import soot.options.Options;
import soot.toolkits.exceptions.PedanticThrowAnalysis;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.util.Chain;
public class UnreachableCodeEliminator extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(UnreachableCodeEliminator.class);
protected ThrowAnalysis throwAnalysis = null;
public static UnreachableCodeEliminator v() {
return G.v().soot_jimple_toolkits_scalar_UnreachableCodeEliminator();
}
public UnreachableCodeEliminator(Singletons.Global g) {
}
public UnreachableCodeEliminator(ThrowAnalysis ta) {
this.throwAnalysis = ta;
}
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
final boolean verbose = Options.v().verbose();
if (verbose) {
logger.debug("[" + body.getMethod().getName() + "] Eliminating unreachable code...");
}
// Force a conservative ExceptionalUnitGraph() which
// necessarily includes an edge from every trapped Unit to
// its handler, so that we retain Traps in the case where
// trapped units remain, but the default ThrowAnalysis
// says that none of them can throw the caught exception.
if (this.throwAnalysis == null) {
boolean opt = PhaseOptions.getBoolean(options, "remove-unreachable-traps", true);
this.throwAnalysis = opt ? Scene.v().getDefaultThrowAnalysis() : PedanticThrowAnalysis.v();
}
final Chain<Unit> units = body.getUnits();
final int origSize = units.size();
final Set<Unit> reachable = origSize == 0 ? Collections.emptySet()
: reachable(units.getFirst(), ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis, false));
// Now eliminate empty traps. (and unreachable handlers)
//
// For the most part, this is an atavism, an an artifact of
// pre-ExceptionalUnitGraph code, when the only way for a trap to
// become unreachable was if all its trapped units were removed, and
// the stmtIt loop did not remove Traps as it removed handler units.
// We've left this separate test for empty traps here, even though
// most such traps would already have been eliminated by the preceding
// loop, because in arbitrary bytecode you could have
// handler unit that was still reachable by normal control flow, even
// though it no longer trapped any units (though such code is unlikely to
// occur in practice, and certainly no in code generated from Java source.
final Chain<Trap> traps = body.getTraps();
for (Iterator<Trap> it = traps.iterator(); it.hasNext();) {
Trap trap = it.next();
if ((trap.getBeginUnit() == trap.getEndUnit()) || !reachable.contains(trap.getHandlerUnit())) {
it.remove();
}
}
// We must make sure that the end units of all traps which are still alive are kept in the code
{
final Unit lastUnit = units.getLast();
for (Trap t : traps) {
if (t.getEndUnit() == lastUnit) {
reachable.add(lastUnit);
break;
}
}
}
Set<Unit> notReachable = null;
if (verbose) {
notReachable = new HashSet<Unit>();
for (Unit u : units) {
if (!reachable.contains(u)) {
notReachable.add(u);
}
}
}
units.retainAll(reachable);
if (verbose) {
final String name = body.getMethod().getName();
logger.debug("[" + name + "] Removed " + (origSize - units.size()) + " statements: ");
for (Unit u : notReachable) {
logger.debug("[" + name + "] " + u);
}
}
}
// Used to be: "mark first statement and all its successors, recursively"
// Bad idea! Some methods are extremely long. It broke because the recursion reached the
// 3799th level.
private <T> Set<T> reachable(T first, DirectedGraph<T> g) {
if (first == null || g == null) {
return Collections.emptySet();
}
Set<T> visited = new HashSet<T>(g.size());
Deque<T> q = new ArrayDeque<T>();
q.addFirst(first);
do {
T t = q.removeFirst();
if (visited.add(t)) {
q.addAll(g.getSuccsOf(t));
}
} while (!q.isEmpty());
return visited;
}
}
| 5,550
| 33.69375
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/BusyCodeMotion.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.EquivalentValue;
import soot.G;
import soot.Local;
import soot.Scene;
import soot.SideEffectTester;
import soot.Singletons;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.Jimple;
import soot.jimple.NaiveSideEffectTester;
import soot.jimple.toolkits.graph.CriticalEdgeRemover;
import soot.jimple.toolkits.pointer.PASideEffectTester;
import soot.jimple.toolkits.scalar.LocalCreation;
import soot.options.BCMOptions;
import soot.options.Options;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.util.Chain;
import soot.util.UnitMap;
/**
* Performs a partial redundancy elimination (= code motion). This is done, by moving <b>every</b>computation as high as
* possible (it is easy to show, that they are computationally optimal), and then replacing the original computation by a
* reference to this new high computation. This implies, that we introduce <b>many</b> new helper-variables (that can easily
* be eliminated afterwards).<br>
* In order to catch every redundant expression, this transformation must be done on a graph without critical edges.
* Therefore the first thing we do, is removing them. A subsequent pass can then easily remove the synthetic nodes we have
* introduced.<br>
* The term "busy" refers to the fact, that we <b>always</b> move computations as high as possible. Even, if this is not
* necessary.
*
* @see soot.jimple.toolkits.graph.CriticalEdgeRemover
*/
public class BusyCodeMotion extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(BusyCodeMotion.class);
private static final String PREFIX = "$bcm";
public BusyCodeMotion(Singletons.Global g) {
}
public static BusyCodeMotion v() {
return G.v().soot_jimple_toolkits_scalar_pre_BusyCodeMotion();
}
/**
* performs the busy code motion.
*/
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> opts) {
final BCMOptions options = new BCMOptions(opts);
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] performing Busy Code Motion...");
}
CriticalEdgeRemover.v().transform(b, phaseName + ".cer");
UnitGraph graph = new BriefUnitGraph(b);
/* Map each unit to its RHS. Take only BinopExpr and ConcreteRef */
Map<Unit, EquivalentValue> unitToEquivRhs = new UnitMap<EquivalentValue>(b, graph.size() + 1, 0.7f) {
@Override
protected EquivalentValue mapTo(Unit unit) {
Value tmp = SootFilter.noInvokeRhs(unit);
Value tmp2 = SootFilter.binop(tmp);
if (tmp2 == null) {
tmp2 = SootFilter.concreteRef(tmp);
}
return SootFilter.equiVal(tmp2);
}
};
/* Same as before, but without exception-throwing expressions */
Map<Unit, EquivalentValue> unitToNoExceptionEquivRhs = new UnitMap<EquivalentValue>(b, graph.size() + 1, 0.7f) {
@Override
protected EquivalentValue mapTo(Unit unit) {
return SootFilter.equiVal(SootFilter.noExceptionThrowing(SootFilter.binopRhs(unit)));
}
};
final Scene sc = Scene.v();
/* if a more precise sideeffect-tester comes out, please change it here! */
final SideEffectTester sideEffect;
if (sc.hasCallGraph() && !options.naive_side_effect()) {
sideEffect = new PASideEffectTester();
} else {
sideEffect = new NaiveSideEffectTester();
}
sideEffect.newMethod(b.getMethod());
final UpSafetyAnalysis upSafe = new UpSafetyAnalysis(graph, unitToEquivRhs, sideEffect);
final DownSafetyAnalysis downSafe = new DownSafetyAnalysis(graph, unitToNoExceptionEquivRhs, sideEffect);
final EarliestnessComputation earliest = new EarliestnessComputation(graph, upSafe, downSafe, sideEffect);
final LocalCreation localCreation = sc.createLocalCreation(b.getLocals(), PREFIX);
final HashMap<EquivalentValue, Local> expToHelper = new HashMap<EquivalentValue, Local>();
Chain<Unit> unitChain = b.getUnits();
/* insert the computations at the earliest positions */
for (Iterator<Unit> unitIt = unitChain.snapshotIterator(); unitIt.hasNext();) {
Unit currentUnit = unitIt.next();
for (EquivalentValue equiVal : earliest.getFlowBefore(currentUnit)) {
/* get the unic helper-name for this expression */
Local helper = expToHelper.get(equiVal);
if (helper == null) {
helper = localCreation.newLocal(equiVal.getType());
expToHelper.put(equiVal, helper);
}
// Make sure not to place any stuff inside the identity block at
// the beginning of the method
if (currentUnit instanceof IdentityStmt) {
currentUnit = getFirstNonIdentityStmt(b);
}
/* insert a new Assignment-stmt before the currentUnit */
Value insertValue = Jimple.cloneIfNecessary(equiVal.getValue());
Unit firstComp = Jimple.v().newAssignStmt(helper, insertValue);
unitChain.insertBefore(firstComp, currentUnit);
}
}
/* replace old computations by the helper-vars */
for (Unit currentUnit : unitChain) {
EquivalentValue rhs = unitToEquivRhs.get(currentUnit);
if (rhs != null) {
Local helper = expToHelper.get(rhs);
if (helper != null) {
((AssignStmt) currentUnit).setRightOp(helper);
}
}
}
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Busy Code Motion done!");
}
}
private Unit getFirstNonIdentityStmt(Body b) {
for (Unit u : b.getUnits()) {
if (!(u instanceof IdentityStmt)) {
return u;
}
}
return null;
}
}
| 6,757
| 35.728261
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/DelayabilityAnalysis.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import soot.EquivalentValue;
import soot.Unit;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ArrayPackedSet;
import soot.toolkits.scalar.BoundedFlowSet;
import soot.toolkits.scalar.CollectionFlowUniverse;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
/**
* Performs a Delayability-analysis on the given graph. This analysis is the third analysis in the PRE (lazy code motion) and
* has little (no?) sense if used alone. Basically it tries to push the computations we would insert in the Busy Code Motion
* as far down as possible, to decrease life-time ranges (clearly this is not true, if the computation "uses" two variables
* and produces only one temporary).
*/
public class DelayabilityAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<EquivalentValue>> {
private final EarliestnessComputation earliest;
private final Map<Unit, EquivalentValue> unitToKillValue;
private final BoundedFlowSet<EquivalentValue> set;
/**
* this constructor should not be used, and will throw a runtime-exception!
*/
@Deprecated
public DelayabilityAnalysis(DirectedGraph<Unit> dg) {
/* we have to add super(dg). otherwise Javac complains. */
super(dg);
throw new RuntimeException("Don't use this Constructor!");
}
/**
* Automatically performs the Delayability-analysis on the graph <code>dg</code> and the Earliest-computation
* <code>earliest</code>.<br>
* the <code>equivRhsMap</code> is only here to avoid doing these things again...
*
* @param dg
* a ExceptionalUnitGraph
* @param earliest
* the earliest-computation of the <b>same</b> graph.
* @param equivRhsMap
* the rhs of each unit (if assignment-stmt).
*/
public DelayabilityAnalysis(DirectedGraph<Unit> dg, EarliestnessComputation earliest,
Map<Unit, EquivalentValue> equivRhsMap) {
this(dg, earliest, equivRhsMap,
new ArrayPackedSet<EquivalentValue>(new CollectionFlowUniverse<EquivalentValue>(equivRhsMap.values())));
}
/**
* Automatically performs the Delayability-analysis on the graph <code>dg</code> and the Earliest-computation
* <code>earliest</code>.<br>
* the <code>equivRhsMap</code> is only here to avoid doing these things again...<br>
* as set-operations are usually more efficient, if the sets come from one source, sets should be shared around analyses,
* if the analyses are to be combined.
*
* @param dg
* a ExceptionalUnitGraph
* @param earliest
* the earliest-computation of the <b>same</b> graph.
* @param equivRhsMap
* the rhs of each unit (if assignment-stmt).
* @param set
* the shared set.
*/
public DelayabilityAnalysis(DirectedGraph<Unit> dg, EarliestnessComputation earliest,
Map<Unit, EquivalentValue> equivRhsMap, BoundedFlowSet<EquivalentValue> set) {
super(dg);
this.set = set;
this.unitToKillValue = equivRhsMap;
this.earliest = earliest;
doAnalysis();
// finally add the genSet to each BeforeFlow
for (Unit currentUnit : dg) {
getFlowBefore(currentUnit).union(earliest.getFlowBefore(currentUnit));
}
}
@Override
protected FlowSet<EquivalentValue> newInitialFlow() {
return set.topSet();
}
@Override
protected FlowSet<EquivalentValue> entryInitialFlow() {
return set.emptySet();
}
@Override
protected void flowThrough(FlowSet<EquivalentValue> in, Unit u, FlowSet<EquivalentValue> out) {
in.copy(out);
// Perform generation
out.union(earliest.getFlowBefore(u));
/* Perform kill */
EquivalentValue equiVal = (EquivalentValue) unitToKillValue.get(u);
if (equiVal != null) {
out.remove(equiVal);
}
}
@Override
protected void merge(FlowSet<EquivalentValue> inSet1, FlowSet<EquivalentValue> inSet2, FlowSet<EquivalentValue> outSet) {
inSet1.intersection(inSet2, outSet);
}
protected void copy(FlowSet<EquivalentValue> sourceSet, FlowSet<EquivalentValue> destSet) {
sourceSet.copy(destSet);
}
}
| 4,938
| 34.532374
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/DownSafetyAnalysis.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* based on FastAvailableExpressionsAnalysis from Patrick Lam.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.EquivalentValue;
import soot.SideEffectTester;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.FieldRef;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ArrayPackedSet;
import soot.toolkits.scalar.BackwardFlowAnalysis;
import soot.toolkits.scalar.BoundedFlowSet;
import soot.toolkits.scalar.CollectionFlowUniverse;
import soot.toolkits.scalar.FlowSet;
/**
* Performs an DownSafe-analysis on the given graph. An expression is downsafe, if the computation will occur on every path
* from the current point down to the END.
*/
public class DownSafetyAnalysis extends BackwardFlowAnalysis<Unit, FlowSet<EquivalentValue>> {
private final SideEffectTester sideEffect;
private final Map<Unit, EquivalentValue> unitToGenerateMap;
private final BoundedFlowSet<EquivalentValue> set;
/**
* This constructor should not be used, and will throw a runtime-exception!
*/
@Deprecated
public DownSafetyAnalysis(DirectedGraph<Unit> dg) {
/* we have to add super(dg). otherwise Javac complains. */
super(dg);
throw new RuntimeException("Don't use this Constructor!");
}
/**
* This constructor automatically performs the DownSafety-analysis.<br>
* the result of the analysis is as usual in FlowBefore (getFlowBefore()) and FlowAfter (getFlowAfter()).<br>
*
* @param dg
* a ExceptionalUnitGraph.
* @param unitToGen
* the equivalentValue of each unit.
* @param sideEffect
* the SideEffectTester that performs kills.
*/
public DownSafetyAnalysis(DirectedGraph<Unit> dg, Map<Unit, EquivalentValue> unitToGen, SideEffectTester sideEffect) {
this(dg, unitToGen, sideEffect,
new ArrayPackedSet<EquivalentValue>(new CollectionFlowUniverse<EquivalentValue>(unitToGen.values())));
}
/**
* This constructor automatically performs the DownSafety-analysis.<br>
* the result of the analysis is as usual in FlowBefore (getFlowBefore()) and FlowAfter (getFlowAfter()).<br>
* as sets-operations are usually more efficient, if the original set comes from the same source, this allows to share
* sets.
*
* @param dg
* a ExceptionalUnitGraph.
* @param unitToGen
* the equivalentValue of each unit.
* @param sideEffect
* the SideEffectTester that performs kills.
* @param set
* the shared set.
*/
public DownSafetyAnalysis(DirectedGraph<Unit> dg, Map<Unit, EquivalentValue> unitToGen, SideEffectTester sideEffect,
BoundedFlowSet<EquivalentValue> set) {
super(dg);
this.sideEffect = sideEffect;
this.set = set;
this.unitToGenerateMap = unitToGen;
doAnalysis();
}
@Override
protected FlowSet<EquivalentValue> newInitialFlow() {
return set.topSet();
}
@Override
protected FlowSet<EquivalentValue> entryInitialFlow() {
return set.emptySet();
}
@Override
protected void flowThrough(FlowSet<EquivalentValue> in, Unit u, FlowSet<EquivalentValue> out) {
in.copy(out);
/* Perform kill */
// iterate over things (avail) in out set.
for (Iterator<EquivalentValue> outIt = out.iterator(); outIt.hasNext();) {
EquivalentValue equiVal = outIt.next();
Value avail = equiVal.getValue();
if (avail instanceof FieldRef) {
if (sideEffect.unitCanWriteTo(u, avail)) {
outIt.remove();
}
} else {
// iterate over uses in each avail.
for (ValueBox next : avail.getUseBoxes()) {
Value use = next.getValue();
if (sideEffect.unitCanWriteTo(u, use)) {
outIt.remove();
break;
}
}
}
}
// Perform generation
EquivalentValue add = unitToGenerateMap.get(u);
if (add != null) {
out.add(add, out);
}
}
@Override
protected void merge(FlowSet<EquivalentValue> in1, FlowSet<EquivalentValue> in2, FlowSet<EquivalentValue> out) {
in1.intersection(in2, out);
}
@Override
protected void copy(FlowSet<EquivalentValue> source, FlowSet<EquivalentValue> dest) {
source.copy(dest);
}
}
| 5,076
| 31.967532
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/EarliestnessComputation.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.EquivalentValue;
import soot.SideEffectTester;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.FieldRef;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
/**
* Computes the earliest points for the given expressions.<br>
* This basically finds the highest point in the flow-graph where we can put each computation, without introducing new
* computations on any path.<br>
* More technically: A computation is earliest, if at the current point the computation is down-safe, and if either:
* <ul>
* <li>any of the predecessors is not transparent, or
* <li>if any predecessors is not "safe" (ie. the insertion of this computation would insert it on a path, where it was not
* before).
* </ul>
* <br>
* Intuitively: If the one predecessor is not transparent, we can't push the computation further up. If one of the
* predecessor is not safe, we would introduce a new computation on its path. Hence we can't push further up.
* <p>
* Note that this computation is linear in the number of units, as we don't need to find any fixed-point.
*
* @see UpSafetyAnalysis
* @see DownSafetyAnalysis
*/
public class EarliestnessComputation {
private final Map<Unit, FlowSet<EquivalentValue>> unitToEarliest;
/**
* given an UpSafetyAnalysis and a DownSafetyAnalysis, performs the earliest-computation.<br>
*
* @param unitGraph
* the Unitgraph we'll work on.
* @param upSafe
* a UpSafetyAnalysis of <code>unitGraph</code>
* @param downSafe
* a DownSafetyAnalysis of <code>unitGraph</code>
* @param sideEffect
* the SideEffectTester that will tell if a node is transparent or not.
*/
public EarliestnessComputation(UnitGraph unitGraph, UpSafetyAnalysis upSafe, DownSafetyAnalysis downSafe,
SideEffectTester sideEffect) {
this(unitGraph, upSafe, downSafe, sideEffect, new ArraySparseSet<EquivalentValue>());
}
/**
* given an UpSafetyAnalysis and a DownSafetyAnalysis, performs the earliest-computation.<br>
* allows to share sets over multiple analyses (set-operations are usually more efficient, if the sets come from the same
* source).
*
* @param unitGraph
* the Unitgraph we'll work on.
* @param upSafe
* a UpSafetyAnalysis of <code>unitGraph</code>
* @param downSafe
* a DownSafetyAnalysis of <code>unitGraph</code>
* @param sideEffect
* the SideEffectTester that will tell if a node is transparent or not.
* @param set
* the shared set.
*/
public EarliestnessComputation(UnitGraph unitGraph, UpSafetyAnalysis upSafe, DownSafetyAnalysis downSafe,
SideEffectTester sideEffect, FlowSet<EquivalentValue> set) {
this.unitToEarliest = new HashMap<Unit, FlowSet<EquivalentValue>>(unitGraph.size() + 1, 0.7f);
for (Unit currentUnit : unitGraph) {
/* create a new Earliest-list for each unit */
FlowSet<EquivalentValue> earliest = set.emptySet();
unitToEarliest.put(currentUnit, earliest);
/* get a copy of the downSafe-set at the current unit */
FlowSet<EquivalentValue> downSafeSet = downSafe.getFlowBefore(currentUnit).clone();
List<Unit> predList = unitGraph.getPredsOf(currentUnit);
if (predList.isEmpty()) { // no predecessor
/*
* we are obviously at the earliest position for any downsafe computation
*/
earliest.union(downSafeSet);
} else {
for (Unit predecessor : predList) {
{ /*
* if a predecessor is not transparent for a certain computation, that is downsafe here, we can't push the
* computation further up, and the earliest computation is before the current point.
*/
/*
* for each element in the downSafe-set, look if it passes through the predecessor
*/
for (Iterator<EquivalentValue> downSafeIt = downSafeSet.iterator(); downSafeIt.hasNext();) {
EquivalentValue equiVal = downSafeIt.next();
Value avail = equiVal.getValue();
if (avail instanceof FieldRef) {
if (sideEffect.unitCanWriteTo(predecessor, avail)) {
earliest.add(equiVal);
downSafeIt.remove();
}
} else {
// iterate over uses in each avail.
for (ValueBox useBox : avail.getUseBoxes()) {
Value use = useBox.getValue();
if (sideEffect.unitCanWriteTo(predecessor, use)) {
earliest.add(equiVal);
downSafeIt.remove();
break;
}
}
}
}
}
{ /*
* look if one of the expressions is not upsafe and not downsafe in one of the predecessors
*/
for (Iterator<EquivalentValue> downSafeIt = downSafeSet.iterator(); downSafeIt.hasNext();) {
EquivalentValue equiVal = downSafeIt.next();
FlowSet<EquivalentValue> preDown = downSafe.getFlowBefore(predecessor);
FlowSet<EquivalentValue> preUp = upSafe.getFlowBefore(predecessor);
if (!preDown.contains(equiVal) && !preUp.contains(equiVal)) {
earliest.add(equiVal);
downSafeIt.remove();
}
}
}
}
}
}
}
/**
* returns the FlowSet of expressions, that have their earliest computation just before <code>node</code>.
*
* @param node
* a Object of the flow-graph (in our case always a Unit).
* @return a FlowSet containing the expressions.
*/
public FlowSet<EquivalentValue> getFlowBefore(Object node) {
return unitToEarliest.get(node);
}
}
| 6,830
| 37.8125
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/LatestComputation.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import soot.EquivalentValue;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArrayPackedSet;
import soot.toolkits.scalar.BoundedFlowSet;
import soot.toolkits.scalar.CollectionFlowUniverse;
import soot.toolkits.scalar.FlowSet;
/**
* Performs a Latest-Computation on the given graph. a computation is latest, when we can't delay it anymore. This uses the
* Delayability-analysis. More precise: The delayability-analysis says us already until which point we can delay a
* computation from the earliest computation-point. We just have to search for points, where there's a computation, or, where
* we can't delay the computation to one of the successors.
*/
public class LatestComputation {
private final Map<Unit, FlowSet<EquivalentValue>> unitToLatest;
/**
* given a DelayabilityAnalysis and the computations of each unit, calculates the latest computation-point for each
* expression. the <code>equivRhsMap</code> could be calculated on the fly, but it is <b>very</b> likely that it already
* exists (as similar maps are used for calculating Earliestness, Delayed,...
*
* @param unitGraph
* a UnitGraph
* @param delayed
* the delayability-analysis of the same graph.
* @param equivRhsMap
* all computations of the graph
*/
public LatestComputation(UnitGraph unitGraph, DelayabilityAnalysis delayed, Map<Unit, EquivalentValue> equivRhsMap) {
this(unitGraph, delayed, equivRhsMap,
new ArrayPackedSet<EquivalentValue>(new CollectionFlowUniverse<EquivalentValue>(equivRhsMap.values())));
}
/**
* given a DelayabilityAnalysis and the computations of each unit, calculates the latest computation-point for each
* expression.<br>
* the <code>equivRhsMap</code> could be calculated on the fly, but it is <b>very</b> likely that it already exists (as
* similar maps are used for calculating Earliestness, Delayed,...<br>
* the shared set allows more efficient set-operations, when they the computation is merged with other
* analyses/computations.
*
* @param unitGraph
* a UnitGraph
* @param delayed
* the delayability-analysis of the same graph.
* @param equivRhsMap
* all computations of the graph
* @param set
* the shared flowSet
*/
public LatestComputation(UnitGraph unitGraph, DelayabilityAnalysis delayed, Map<Unit, EquivalentValue> equivRhsMap,
BoundedFlowSet<EquivalentValue> set) {
this.unitToLatest = new HashMap<Unit, FlowSet<EquivalentValue>>(unitGraph.size() + 1, 0.7f);
for (Unit currentUnit : unitGraph) {
/* create a new Earliest-list for each unit */
/*
* basically the latest-set is: (delayed) INTERSECT (comp UNION (UNION_successors ~Delayed)) = (delayed) MINUS
* ((INTERSECTION_successors Delayed) MINUS comp).
*/
FlowSet<EquivalentValue> delaySet = delayed.getFlowBefore(currentUnit);
/* Calculate (INTERSECTION_successors Delayed) */
FlowSet<EquivalentValue> succCompSet = set.topSet();
for (Unit successor : unitGraph.getSuccsOf(currentUnit)) {
succCompSet.intersection(delayed.getFlowBefore(successor), succCompSet);
}
/*
* remove the computation of this set: succCompSet is then: ((INTERSECTION_successors Delayed) MINUS comp)
*/
if (equivRhsMap.get(currentUnit) != null) {
succCompSet.remove(equivRhsMap.get(currentUnit));
}
/* make the difference: */
FlowSet<EquivalentValue> latest = delaySet.emptySet();
delaySet.difference(succCompSet, latest);
unitToLatest.put(currentUnit, latest);
}
}
/**
* returns the set of expressions, that have their latest computation just before <code>node</code>.
*
* @param node
* an Object of the flow-graph (in our case always a Unit).
* @return a FlowSet containing the expressions.
*/
public FlowSet<EquivalentValue> getFlowBefore(Object node) {
return unitToLatest.get(node);
}
}
| 4,937
| 38.822581
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/LazyCodeMotion.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.EquivalentValue;
import soot.G;
import soot.Local;
import soot.Scene;
import soot.SideEffectTester;
import soot.Singletons;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
import soot.jimple.NaiveSideEffectTester;
import soot.jimple.toolkits.graph.CriticalEdgeRemover;
import soot.jimple.toolkits.graph.LoopConditionUnroller;
import soot.jimple.toolkits.pointer.PASideEffectTester;
import soot.jimple.toolkits.scalar.LocalCreation;
import soot.options.LCMOptions;
import soot.options.Options;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArrayPackedSet;
import soot.toolkits.scalar.BoundedFlowSet;
import soot.toolkits.scalar.CollectionFlowUniverse;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.FlowUniverse;
import soot.util.Chain;
import soot.util.UnitMap;
/**
* Performs a partial redundancy elimination (= code motion). This is done, by introducing helper-vars, that store an already
* computed value, or if a computation only arrives partially (not from all predecessors) inserts a new computation on these
* paths afterwards).
* <p>
*
* In order to catch every redundant expression, this transformation must be done on a graph without critical edges.
* Therefore the first thing we do, is removing them. A subsequent pass can then easily remove the synthetic nodes we have
* introduced.
* <p>
*
* The term "lazy" refers to the fact, that we move computations only if necessary.
*
* @see soot.jimple.toolkits.graph.CriticalEdgeRemover
*/
public class LazyCodeMotion extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(LazyCodeMotion.class);
private static final String PREFIX = "$lcm";
public LazyCodeMotion(Singletons.Global g) {
}
public static LazyCodeMotion v() {
return G.v().soot_jimple_toolkits_scalar_pre_LazyCodeMotion();
}
/**
* performs the lazy code motion.
*/
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> opts) {
LCMOptions options = new LCMOptions(opts);
HashMap<EquivalentValue, Local> expToHelper = new HashMap<EquivalentValue, Local>();
Chain<Unit> unitChain = b.getUnits();
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Performing Lazy Code Motion...");
}
if (options.unroll()) {
new LoopConditionUnroller().transform(b, phaseName + ".lcu");
}
CriticalEdgeRemover.v().transform(b, phaseName + ".cer");
UnitGraph graph = new BriefUnitGraph(b);
/* Map each unit to its RHS. Take only BinopExpr and ConcreteRef */
Map<Unit, EquivalentValue> unitToEquivRhs = new UnitMap<EquivalentValue>(b, graph.size() + 1, 0.7f) {
@Override
protected EquivalentValue mapTo(Unit unit) {
Value tmp = SootFilter.noInvokeRhs(unit);
Value tmp2 = SootFilter.binop(tmp);
if (tmp2 == null) {
tmp2 = SootFilter.concreteRef(tmp);
}
return SootFilter.equiVal(tmp2);
}
};
/* Same as before, but without exception-throwing expressions */
Map<Unit, EquivalentValue> unitToNoExceptionEquivRhs = new UnitMap<EquivalentValue>(b, graph.size() + 1, 0.7f) {
@Override
protected EquivalentValue mapTo(Unit unit) {
return SootFilter.equiVal(SootFilter.noExceptionThrowing(SootFilter.binopRhs(unit)));
}
};
FlowUniverse<EquivalentValue> universe = new CollectionFlowUniverse<EquivalentValue>(unitToEquivRhs.values());
BoundedFlowSet<EquivalentValue> set = new ArrayPackedSet<EquivalentValue>(universe);
/* if a more precise sideeffect-tester comes out, please change it here! */
final SideEffectTester sideEffect;
final Scene sc = Scene.v();
if (sc.hasCallGraph() && !options.naive_side_effect()) {
sideEffect = new PASideEffectTester();
} else {
sideEffect = new NaiveSideEffectTester();
}
sideEffect.newMethod(b.getMethod());
final UpSafetyAnalysis upSafe;
if (options.safety() == LCMOptions.safety_safe) {
upSafe = new UpSafetyAnalysis(graph, unitToNoExceptionEquivRhs, sideEffect, set);
} else {
upSafe = new UpSafetyAnalysis(graph, unitToEquivRhs, sideEffect, set);
}
final DownSafetyAnalysis downSafe;
if (options.safety() == LCMOptions.safety_unsafe) {
downSafe = new DownSafetyAnalysis(graph, unitToEquivRhs, sideEffect, set);
} else {
downSafe = new DownSafetyAnalysis(graph, unitToNoExceptionEquivRhs, sideEffect, set);
/* we include the exception-throwing expressions at their uses */
for (Unit currentUnit : unitChain) {
EquivalentValue rhs = unitToEquivRhs.get(currentUnit);
if (rhs != null) {
downSafe.getFlowBefore(currentUnit).add(rhs);
}
}
}
final EarliestnessComputation earliest = new EarliestnessComputation(graph, upSafe, downSafe, sideEffect, set);
final DelayabilityAnalysis delay = new DelayabilityAnalysis(graph, earliest, unitToEquivRhs, set);
final LatestComputation latest = new LatestComputation(graph, delay, unitToEquivRhs, set);
final NotIsolatedAnalysis notIsolated = new NotIsolatedAnalysis(graph, latest, unitToEquivRhs, set);
final LocalCreation localCreation = sc.createLocalCreation(b.getLocals(), PREFIX);
/* debug */
/*
* { logger.debug("========" + b.getMethod().getName()); Iterator unitIt = unitChain.iterator(); while (unitIt.hasNext())
* { Unit currentUnit = (Unit) unitIt.next(); Value equiVal = (Value)unitToEquivRhs.get(currentUnit); FlowSet latestSet =
* (FlowSet)latest.getFlowBefore(currentUnit); FlowSet notIsolatedSet = (FlowSet)notIsolated.getFlowAfter(currentUnit);
* FlowSet delaySet = (FlowSet)delay.getFlowBefore(currentUnit); FlowSet earlySet =
* ((FlowSet)earliest.getFlowBefore(currentUnit)); FlowSet upSet = (FlowSet)upSafe.getFlowBefore(currentUnit); FlowSet
* downSet = (FlowSet)downSafe.getFlowBefore(currentUnit); logger.debug(""+currentUnit); logger.debug(" rh: " + equiVal);
* logger.debug(" up: " + upSet); logger.debug(" do: " + downSet); logger.debug(" is: " + notIsolatedSet); logger.debug(
* " ea: " + earlySet); logger.debug(" db: " + delaySet); logger.debug(" la: " + latestSet); } }
*/
/* insert the computations */
for (Iterator<Unit> unitIt = unitChain.snapshotIterator(); unitIt.hasNext();) {
Unit currentUnit = unitIt.next();
FlowSet<EquivalentValue> latestSet = latest.getFlowBefore(currentUnit);
FlowSet<EquivalentValue> notIsolatedSet = notIsolated.getFlowAfter(currentUnit);
FlowSet<EquivalentValue> insertHere = latestSet.clone();
insertHere.intersection(notIsolatedSet);
for (EquivalentValue equiVal : insertHere) {
/* get the unique helper-name for this expression */
Local helper = expToHelper.get(equiVal);
if (helper == null) {
helper = localCreation.newLocal(equiVal.getType());
expToHelper.put(equiVal, helper);
}
/* insert a new Assignment-stmt before the currentUnit */
Value insertValue = Jimple.cloneIfNecessary(equiVal.getValue());
Unit firstComp = Jimple.v().newAssignStmt(helper, insertValue);
unitChain.insertBefore(firstComp, currentUnit);
}
}
/* replace old computations by the helper-vars */
for (Unit currentUnit : unitChain) {
EquivalentValue rhs = unitToEquivRhs.get(currentUnit);
if (rhs != null) {
FlowSet<EquivalentValue> latestSet = latest.getFlowBefore(currentUnit);
FlowSet<EquivalentValue> notIsolatedSet = notIsolated.getFlowAfter(currentUnit);
if (!latestSet.contains(rhs) && notIsolatedSet.contains(rhs)) {
Local helper = expToHelper.get(rhs);
if (helper != null) {
try {
((AssignStmt) currentUnit).setRightOp(helper);
} catch (RuntimeException e) {
logger.debug("Error on " + b.getMethod().getName());
logger.debug(currentUnit.toString());
logger.debug(String.valueOf(latestSet));
logger.debug(String.valueOf(notIsolatedSet));
throw e;
}
}
}
}
}
if (Options.v().verbose()) {
logger.debug("[" + b.getMethod().getName() + "] Lazy Code Motion done.");
}
}
}
| 9,458
| 39.771552
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/NotIsolatedAnalysis.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import soot.EquivalentValue;
import soot.Unit;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ArrayPackedSet;
import soot.toolkits.scalar.BackwardFlowAnalysis;
import soot.toolkits.scalar.BoundedFlowSet;
import soot.toolkits.scalar.CollectionFlowUniverse;
import soot.toolkits.scalar.FlowSet;
/**
* Performs a Not-Isolated-analysis on the given graph, which is basically the same as an Isolated-analysis (we just return
* the complement, as it's easier to calculate it). A computation is isolated, if it can only be used at the current
* computation-point. In other words: if the result of the computation will not be used later on the computation is isolated.
* <br>
* The Latest-analysis helps us in finding isolated computations, as they show us points, where a precedent computation can't
* be used anymore. In completely other words: we search the interval "latest"-"computation". a computation in this interval
* would not be isolated.
*/
public class NotIsolatedAnalysis extends BackwardFlowAnalysis<Unit, FlowSet<EquivalentValue>> {
private final LatestComputation unitToLatest;
private final Map<Unit, EquivalentValue> unitToGen;
private final FlowSet<EquivalentValue> set;
/**
* Automatically performs the Isolation-analysis on the graph <code>dg</code> using the Latest-computation
* <code>latest</code>.<br>
* the <code>equivRhsMap</code> is only here to avoid doing these things again...
*
* @param dg
* a ExceptionalUnitGraph
* @param latest
* the latest-computation of the same graph.
* @param equivRhsMap
* the rhs of each unit (if assignment-stmt).
*/
public NotIsolatedAnalysis(DirectedGraph<Unit> dg, LatestComputation latest, Map<Unit, EquivalentValue> equivRhsMap) {
this(dg, latest, equivRhsMap,
new ArrayPackedSet<EquivalentValue>(new CollectionFlowUniverse<EquivalentValue>(equivRhsMap.values())));
}
/**
* Automatically performs the Isolation-analysis on the graph <code>dg</code> using the Latest-computation
* <code>latest</code>.<br>
* the <code>equivRhsMap</code> is only here to avoid doing these things again...<br>
* the shared set allows more efficient set-operations, when this analysis is joined with other analyses/computations.
*
* @param dg
* a ExceptionalUnitGraph
* @param latest
* the latest-computation of the same graph.
* @param equivRhsMap
* the rhs of each unit (if assignment-stmt).
* @param set
* the shared set.
*/
public NotIsolatedAnalysis(DirectedGraph<Unit> dg, LatestComputation latest, Map<Unit, EquivalentValue> equivRhsMap,
BoundedFlowSet<EquivalentValue> set) {
super(dg);
this.set = set;
this.unitToGen = equivRhsMap;
this.unitToLatest = latest;
doAnalysis();
}
@Override
protected FlowSet<EquivalentValue> newInitialFlow() {
return set.emptySet();
}
@Override
protected FlowSet<EquivalentValue> entryInitialFlow() {
return newInitialFlow();
}
@Override
protected void flowThrough(FlowSet<EquivalentValue> in, Unit unit, FlowSet<EquivalentValue> out) {
in.copy(out);
// Perform generation
EquivalentValue rhs = (EquivalentValue) unitToGen.get(unit);
if (rhs != null) {
out.add(rhs);
}
// perform kill
FlowSet<EquivalentValue> latest = unitToLatest.getFlowBefore(unit);
out.difference(latest);
}
@Override
protected void merge(FlowSet<EquivalentValue> inSet1, FlowSet<EquivalentValue> inSet2, FlowSet<EquivalentValue> outSet) {
inSet1.union(inSet2, outSet);
}
@Override
protected void copy(FlowSet<EquivalentValue> sourceSet, FlowSet<EquivalentValue> destSet) {
sourceSet.copy(destSet);
}
}
| 4,634
| 35.496063
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/SootFilter.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.EquivalentValue;
import soot.Local;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.ConcreteRef;
import soot.jimple.DivExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.RemExpr;
/**
* Allows easy filtering/wrapping of Soot objects. Operations that are done very often are grouped here.
*/
public class SootFilter {
/**
* wraps a value into a EquivalentValue. returns <code>null</code> if <code>val</code> is null.
*
* @param val
* the Value to wrap.
* @return the EquivalentValue containing val.
*/
public static EquivalentValue equiVal(Value val) {
return (val != null) ? new EquivalentValue(val) : null;
}
/**
* filters out the RHS of an assignmentStmt.
*
* @param unit
* a Unit from which to extract the RHS.
* @return the RHS-Value of <code>unit</code> or <code>null</code> if <code>unit</code> wasn't an assignment-stmt.
*/
public static Value rhs(Unit unit) {
return (unit instanceof AssignStmt) ? ((AssignStmt) unit).getRightOp() : null;
}
/**
* only lets binary expression through.
*
* @param val
* the Value to test for.
* @return <code>val</code> if it is a binary expression. otherwise <code>null</code>.
*/
public static Value binop(Value val) {
return (val instanceof BinopExpr) ? val : null;
}
/**
* only lets binary RHS through.
*
* @param unit
* the Unit to test for.
* @return the rhs of the current unit, if <code>unit</code> is an AssigStmt and its RHS is a binary expression. otherwise
* <code>null</code>.
*/
public static Value binopRhs(Unit unit) {
return binop(rhs(unit));
}
/**
* only lets concrete references through. A concrete reference is either an array-ref or a field-ref.<br>
* returns <code>null</code> if <code>val</code> already was null.
*
* @param val
* the Value to test for.
* @return the <code>val</code> if it was a concrete reference. otherwise <code>null</code>.
*/
public static Value concreteRef(Value val) {
return (val instanceof ConcreteRef) ? val : null;
}
/**
* filters out Exception-throwing Values. This method is perhaps conservative.<br>
* returns <code>null</code> if <code>val</code> is null.
*
* @param val
* the Value to test for.
* @return <code>val</code> if val doesn't throw any exception, or <code>null</code> otherwise.
*/
public static Value noExceptionThrowing(Value val) {
return (val != null && !throwsException(val)) ? val : null;
}
/**
* filters out RHS that don't throw any exception.
*
* @param unit
* the Unit to test.
* @return the rhs, if <code>unit</code> is an assignment-stmt and can't throw any exception.
*/
public static Value noExceptionThrowingRhs(Unit unit) {
return noExceptionThrowing(rhs(unit));
}
/**
* filters out RHS that aren't invokes.
*
* @param unit
* the Unit to look at.
* @return the RHS of <code>unit</code> if it is an assignment-stmt, and its RHS is not an invoke.
*/
public static Value noInvokeRhs(Unit unit) {
return noInvoke(rhs(unit));
}
/**
* returns true, if <code>val</code> is an invoke.
*
* @param val
* the Value to inspect.
* @return true if <code>val</code> is an invoke.
*/
public static boolean isInvoke(Value val) {
val = getEquivalentValueRoot(val);
return (val instanceof InvokeExpr);
}
/**
* filters out Invokes.<br>
* returns <code>null</code> if <code>val</code> is null.
*
* @param val
* the Value to inspect
* @return <code>val</code>, if val is not an invoke, <code>null</code> otherwise.
*/
public static Value noInvoke(Value val) {
return (val != null && !isInvoke(val)) ? val : null;
}
/**
* filters out Locals.<br>
* returns <code>null</code> if <code>val</code> is null.
*
* @param val
* the Value to look at.
* @return <code>val</code>, if it is a Local, <code>null</code> otherwise.
*/
public static Value local(Value val) {
return (val != null && isLocal(val)) ? val : null;
}
/**
* only lets non-Locals through.<br>
* returns <code>null</code> if <code>val</code> is null.
*
* @param val
* the Value to look at.
* @return <code>val</code>, if it is not a Local, <code>null</code> otherwise.
*/
public static Value noLocal(Value val) {
return (val != null && !isLocal(val)) ? val : null;
}
/**
* returns true, if <code>val</code> is a Local.
*/
public static boolean isLocal(Value val) {
return (getEquivalentValueRoot(val) instanceof Local);
}
/**
* returns the Value of an EquivalentValue. If there are several EquivalentValues stacked one into another, gets the
* deepest Value.<br>
* returns <code>null</code> if <code>val</code> is null.
*
* @param val
* the Value to inspect.
* @return val, if val is not an EquivalentValue, or the deepest Value otherwise.
*/
public static Value getEquivalentValueRoot(Value val) {
/*
* extract the Value, if val is an EquivalentValue. One of the reasons, why testing for "instanceof" is sometimes not a
* good idea.
*/
while (val instanceof EquivalentValue) {
val = ((EquivalentValue) val).getValue();
}
return val;
}
/**
* a (probably) conservative way of telling if a Value throws an exception or not.
*/
public static boolean throwsException(Value val) {
val = getEquivalentValueRoot(val);
/* i really hope i did not forget any... */
return val instanceof DivExpr || val instanceof RemExpr || val instanceof LengthExpr;
}
}
| 6,668
| 29.732719
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/scalar/pre/UpSafetyAnalysis.java
|
package soot.jimple.toolkits.scalar.pre;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* based on FastAvailableExpressionsAnalysis from Patrick Lam.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.EquivalentValue;
import soot.SideEffectTester;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.FieldRef;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ArrayPackedSet;
import soot.toolkits.scalar.BoundedFlowSet;
import soot.toolkits.scalar.CollectionFlowUniverse;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
/**
* Performs an UpSafe-analysis on the given graph. An expression is upsafe, if the computation already has been performed on
* every path from START to the given program-point.
*/
public class UpSafetyAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<EquivalentValue>> {
private final SideEffectTester sideEffect;
private final Map<Unit, EquivalentValue> unitToGenerateMap;
private final BoundedFlowSet<EquivalentValue> set;
/**
* This constructor should not be used, and will throw a runtime-exception!
*/
@Deprecated
public UpSafetyAnalysis(DirectedGraph<Unit> dg) {
/* we have to add super(dg). otherwise Javac complains. */
super(dg);
throw new RuntimeException("Don't use this Constructor!");
}
/**
* This constructor automatically performs the UpSafety-analysis.<br>
* the result of the analysis is as usual in FlowBefore (getFlowBefore()) and FlowAfter (getFlowAfter()).<br>
*
* @param dg
* a ExceptionalUnitGraph
* @param unitToGen
* the EquivalentValue of each unit.
* @param sideEffect
* the SideEffectTester that will be used to perform kills.
*/
public UpSafetyAnalysis(DirectedGraph<Unit> dg, Map<Unit, EquivalentValue> unitToGen, SideEffectTester sideEffect) {
this(dg, unitToGen, sideEffect,
new ArrayPackedSet<EquivalentValue>(new CollectionFlowUniverse<EquivalentValue>(unitToGen.values())));
}
/**
* This constructor automatically performs the UpSafety-analysis.<br>
* the result of the analysis is as usual in FlowBefore (getFlowBefore()) and FlowAfter (getFlowAfter()).<br>
* As usually flowset-operations are more efficient if shared, this allows to share sets over several analyses.
*
* @param dg
* a ExceptionalUnitGraph
* @param unitToGen
* the EquivalentValue of each unit.
* @param sideEffect
* the SideEffectTester that will be used to perform kills.
* @param set
* a bounded flow-set.
*/
public UpSafetyAnalysis(DirectedGraph<Unit> dg, Map<Unit, EquivalentValue> unitToGen, SideEffectTester sideEffect,
BoundedFlowSet<EquivalentValue> set) {
super(dg);
this.sideEffect = sideEffect;
this.set = set;
this.unitToGenerateMap = unitToGen;
doAnalysis();
}
@Override
protected FlowSet<EquivalentValue> newInitialFlow() {
return set.topSet();
}
@Override
protected FlowSet<EquivalentValue> entryInitialFlow() {
return set.emptySet();
}
@Override
protected void flowThrough(FlowSet<EquivalentValue> in, Unit u, FlowSet<EquivalentValue> out) {
in.copy(out);
// Perform generation
EquivalentValue add = unitToGenerateMap.get(u);
if (add != null) {
out.add(add, out);
}
/* Perform kill */
// iterate over things (avail) in out set.
for (Iterator<EquivalentValue> outIt = out.iterator(); outIt.hasNext();) {
EquivalentValue equiVal = outIt.next();
Value avail = equiVal.getValue();
if (avail instanceof FieldRef) {
if (sideEffect.unitCanWriteTo(u, avail)) {
outIt.remove();
}
} else {
// iterate over uses in each avail.
for (ValueBox useBox : avail.getUseBoxes()) {
Value use = useBox.getValue();
if (sideEffect.unitCanWriteTo(u, use)) {
outIt.remove();
break;
}
}
}
}
}
@Override
protected void merge(FlowSet<EquivalentValue> inSet1, FlowSet<EquivalentValue> inSet2, FlowSet<EquivalentValue> outSet) {
inSet1.intersection(inSet2, outSet);
}
@Override
protected void copy(FlowSet<EquivalentValue> sourceSet, FlowSet<EquivalentValue> destSet) {
sourceSet.copy(destSet);
}
}
| 5,121
| 32.477124
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/AbstractRuntimeThread.java
|
package soot.jimple.toolkits.thread;
/*-
* #%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.SootMethod;
import soot.jimple.Stmt;
/**
* AbstractRuntimeThread written by Richard L. Halpert 2007-03-04 Acts as a container for the thread information collected by
* UnsynchronizedMhpAnalysis. A set of threads started from the same location will be represented by one
* AbstractRuntimeThread, with runsMany set to true.
*/
public class AbstractRuntimeThread {
// Where thread is started/joined
Stmt startStmt;
SootMethod startStmtMethod;
Stmt joinStmt;
// What methods are in the thread
List<Object> methods;
List<Object> runMethods; // meant to be a subset of methods
// What kind of parallelism
boolean runsMany;
boolean runsOnce;
boolean runsOneAtATime;
// How we determined the parallelism
boolean startStmtHasMultipleReachingObjects;
boolean startStmtMayBeRunMultipleTimes;
// boolean hasJoinStmt; // just check if joinStmt is null or not
boolean startMethodIsReentrant;
boolean startMethodMayHappenInParallel;
// Just for kicks
boolean isMainThread;
public AbstractRuntimeThread() {
startStmt = null;
startStmtMethod = null;
methods = new ArrayList<Object>();
runMethods = new ArrayList<Object>();
// What kind of parallelism - this is set unsafely, so analysis MUST set it correctly
runsMany = false;
runsOnce = false;
runsOneAtATime = false;
// How we determined the parallelism - this is set unsafely, so analysis MUST set it correctly
startStmtHasMultipleReachingObjects = false;
startStmtMayBeRunMultipleTimes = false;
startMethodIsReentrant = false;
startMethodMayHappenInParallel = false;
// Just for kicks
isMainThread = false;
}
public void setStartStmt(Stmt startStmt) {
this.startStmt = startStmt;
}
public void setJoinStmt(Stmt joinStmt) {
this.joinStmt = joinStmt;
}
public void setStartStmtMethod(SootMethod startStmtMethod) {
this.startStmtMethod = startStmtMethod;
}
public SootMethod getStartStmtMethod() {
return startStmtMethod;
}
public boolean containsMethod(Object method) {
return methods.contains(method);
}
public void addMethod(Object method) {
methods.add(method);
}
public void addRunMethod(Object method) {
runMethods.add(method);
}
public List<Object> getRunMethods() {
return runMethods;
}
public int methodCount() {
return methods.size();
}
public Object getMethod(int methodNum) {
return methods.get(methodNum);
}
public void setStartStmtHasMultipleReachingObjects() {
startStmtHasMultipleReachingObjects = true;
}
public void setStartStmtMayBeRunMultipleTimes() {
startStmtMayBeRunMultipleTimes = true;
}
public void setStartMethodIsReentrant() {
startMethodIsReentrant = true;
}
// Does this ever happen? Should run a test to see if this situation would
// already be caught by StartStmtMayBeRunMultipleTimes
public void setStartMethodMayHappenInParallel() {
startMethodMayHappenInParallel = true;
}
public void setRunsMany() {
runsMany = true;
runsOnce = false;
runsOneAtATime = false;
}
public void setRunsOnce() {
runsMany = false;
runsOnce = true;
runsOneAtATime = false;
}
public void setRunsOneAtATime() {
runsMany = false;
runsOnce = false;
runsOneAtATime = true;
}
public void setIsMainThread() {
isMainThread = true;
}
public String toString() {
String ret = (isMainThread ? "Main Thread" : "User Thread") + " ("
+ (runsMany ? "Multi, " : (runsOnce ? "Single, " : (runsOneAtATime ? "At-Once," : "ERROR")));
if (startStmtHasMultipleReachingObjects) {
ret = ret + "MRO,"; // Multiple Reaching Objects
if (startMethodIsReentrant) {
ret = ret + "SMR"; // Start Method is Reentrant
} else if (startMethodMayHappenInParallel) {
ret = ret + "MSP"; // May be Started in Parallel
} else if (startStmtMayBeRunMultipleTimes) {
ret = ret + "RMT"; // Run Multiple Times
} else {
ret = ret + "ROT"; // Run One Time
}
} else {
if (isMainThread) {
ret = ret + "---,---"; // no start stmt...
} else {
ret = ret + "SRO,---"; // Single Reaching Object
}
}
ret = ret + "): ";
if (!isMainThread) {
ret = ret + "Started in " + startStmtMethod + " by " + startStmt + "\n";
} else {
ret = ret + "\n";
}
if (joinStmt != null) {
ret = ret + " " + "Joined in " + startStmtMethod + " by " + joinStmt + "\n";
}
ret = ret + methods.toString();
return ret;
}
}
| 5,526
| 26.361386
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/EncapsulatedMethodAnalysis.java
|
package soot.jimple.toolkits.thread;
/*-
* #%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 soot.IntType;
import soot.RefLikeType;
import soot.Type;
import soot.jimple.FieldRef;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.toolkits.graph.UnitGraph;
// EncapsulatedMethodAnalysis written by Richard L. Halpert, 2006-12-26
public class EncapsulatedMethodAnalysis // extends ForwardFlowAnalysis
{
boolean isMethodPure;
boolean isMethodConditionallyPure;
public EncapsulatedMethodAnalysis(UnitGraph g) {
isMethodPure = true; // innocent until proven guilty :-)
isMethodConditionallyPure = true;
// Check if accesses any static object
Iterator stmtIt = g.iterator();
while (stmtIt.hasNext()) {
Stmt s = (Stmt) stmtIt.next();
if (s.containsFieldRef()) {
FieldRef ref = s.getFieldRef();
if ((ref instanceof StaticFieldRef)
&& (Type.toMachineType(((StaticFieldRef) ref).getType()) instanceof RefLikeType)) {
isMethodPure = false; // kills purity
isMethodConditionallyPure = false; // kills conditional purity
return;
}
}
}
// Check if takes any object parameters
Iterator paramTypesIt = g.getBody().getMethod().getParameterTypes().iterator();
while (paramTypesIt.hasNext()) {
Type paramType = (Type) paramTypesIt.next();
if (Type.toMachineType(paramType) != IntType.v()) {
isMethodPure = false; // kills purity
return;
}
}
// If neither of the above, it may be object-pure
// if this is an <init> function, it's definitely object-pure
// if all called functions in the class may be object-pure, then they all are object-pure
// This is conservative... many "may-be-pure" functions can be proven pure if we track what fields are object-pure
// Also, if we do this, we should be able to track what fields refer to object-local objects, which will allow
// lock assignment to work when inner objects are read/written (because they can be ignored for read/write sets).
}
public boolean isPure() {
return isMethodPure;
}
public boolean isConditionallyPure() {
return isMethodConditionallyPure;
}
/*
* protected void merge(Object in1, Object in2, Object out) { FlowSet inSet1 = (FlowSet) in1; FlowSet inSet2 = (FlowSet)
* in2; FlowSet outSet = (FlowSet) out;
*
* inSet1.intersection(inSet2, outSet); }
*
* protected void flowThrough(Object inValue, Object unit, Object outValue) { FlowSet in = (FlowSet) inValue; FlowSet out =
* (FlowSet) outValue; Stmt stmt = (Stmt) unit;
*
* in.copy(out); }
*
* protected void copy(Object source, Object dest) {
*
* FlowSet sourceSet = (FlowSet) source; FlowSet destSet = (FlowSet) dest;
*
* sourceSet.copy(destSet); }
*
* protected Object entryInitialFlow() { return new ArraySparseSet(); }
*
* protected Object newInitialFlow() { return new ArraySparseSet(); } //
*/
}
| 3,796
| 33.834862
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/EncapsulatedObjectAnalysis.java
|
package soot.jimple.toolkits.thread;
/*-
* #%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.Collection;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.SootMethod;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
// EncapsulatedObjectAnalysis written by Richard L. Halpert, 2006-12-26
// Checks if all methods of a class are "object-pure", meaning that
// they read and write only themselves and new local objects
public class EncapsulatedObjectAnalysis // extends ForwardFlowAnalysis
{
private static final Logger logger = LoggerFactory.getLogger(EncapsulatedObjectAnalysis.class);
List cachedClasses;
List<SootMethod> objectPureMethods;
List<SootMethod> objectPureInitMethods;
public EncapsulatedObjectAnalysis() {
cachedClasses = new ArrayList();
objectPureMethods = new ArrayList<SootMethod>();
objectPureInitMethods = new ArrayList<SootMethod>();
}
public boolean isMethodPureOnObject(SootMethod sm) {
if (!cachedClasses.contains(sm.getDeclaringClass()) && sm.isConcrete()) // NOT A COMPLETE SOLUTION (ignores subclassing)
{
SootMethod initMethod = null;
Collection methods = sm.getDeclaringClass().getMethods();
Iterator methodsIt = methods.iterator();
List<SootMethod> mayBePureMethods = new ArrayList<SootMethod>(methods.size());
while (methodsIt.hasNext()) {
SootMethod method = (SootMethod) methodsIt.next();
if (method.isConcrete()) {
if (method.getSubSignature().startsWith("void <init>")) {
initMethod = method;
}
Body b = method.retrieveActiveBody();
EncapsulatedMethodAnalysis ema
= new EncapsulatedMethodAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b));
if (ema.isPure()) {
mayBePureMethods.add(method);
}
}
}
if (mayBePureMethods.size() == methods.size()) {
objectPureMethods.addAll(mayBePureMethods);
} else if (initMethod != null) {
objectPureMethods.add(initMethod);
}
if (initMethod != null) {
objectPureInitMethods.add(initMethod);
}
}
return objectPureMethods.contains(sm);
}
public boolean isInitMethodPureOnObject(SootMethod sm) {
// logger.debug("Testing Init Method Encapsulation: " + sm + " Encapsulated: ");
if (isMethodPureOnObject(sm)) {
boolean ret = objectPureInitMethods.contains(sm);
// logger.debug(""+ret);
return ret;
}
// logger.debug("false");
return false;
}
public List<SootMethod> getObjectPureMethodsSoFar() {
return objectPureMethods;
}
}
| 3,524
| 32.894231
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/IThreadLocalObjectsAnalysis.java
|
package soot.jimple.toolkits.thread;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2007 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.Value;
/**
* Abstract interface for thread local object analyses.
*
* @author Eric Bodden
*/
public interface IThreadLocalObjectsAnalysis {
public boolean isObjectThreadLocal(Value localOrRef, SootMethod sm);
}
| 1,097
| 27.894737
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/ThreadLocalObjectsAnalysis.java
|
package soot.jimple.toolkits.thread;
/*-
* #%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.Collection;
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.EquivalentValue;
import soot.SootClass;
import soot.SootMethod;
import soot.Value;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.Ref;
import soot.jimple.toolkits.infoflow.CallLocalityContext;
import soot.jimple.toolkits.infoflow.ClassInfoFlowAnalysis;
import soot.jimple.toolkits.infoflow.ClassLocalObjectsAnalysis;
import soot.jimple.toolkits.infoflow.InfoFlowAnalysis;
import soot.jimple.toolkits.infoflow.LocalObjectsAnalysis;
import soot.jimple.toolkits.infoflow.SmartMethodInfoFlowAnalysis;
import soot.jimple.toolkits.infoflow.SmartMethodLocalObjectsAnalysis;
import soot.jimple.toolkits.infoflow.UseFinder;
import soot.jimple.toolkits.thread.mhp.MhpTester;
// ThreadLocalObjectsAnalysis written by Richard L. Halpert, 2007-03-05
// Runs LocalObjectsAnalysis for the special case where we want to know
// if a reference is local to all threads from which it is reached.
public class ThreadLocalObjectsAnalysis extends LocalObjectsAnalysis implements IThreadLocalObjectsAnalysis {
private static final Logger logger = LoggerFactory.getLogger(ThreadLocalObjectsAnalysis.class);
MhpTester mhp;
List<AbstractRuntimeThread> threads;
InfoFlowAnalysis primitiveDfa;
static boolean printDebug = false;
Map valueCache;
Map fieldCache;
Map invokeCache;
public ThreadLocalObjectsAnalysis(MhpTester mhp) // must include main class
{
super(new InfoFlowAnalysis(false, true, printDebug)); // ref-only, with inner fields
this.mhp = mhp;
this.threads = mhp.getThreads();
this.primitiveDfa = new InfoFlowAnalysis(true, true, printDebug); // ref+primitive, with inner fields
valueCache = new HashMap();
fieldCache = new HashMap();
invokeCache = new HashMap();
}
// Forces the majority of computation to take place immediately, rather than on-demand
// might occasionally compute more than is necessary
public void precompute() {
for (AbstractRuntimeThread thread : threads) {
for (Object item : thread.getRunMethods()) {
SootMethod runMethod = (SootMethod) item;
if (runMethod.getDeclaringClass().isApplicationClass()) {
getClassLocalObjectsAnalysis(runMethod.getDeclaringClass());
}
}
}
}
// override
protected ClassLocalObjectsAnalysis newClassLocalObjectsAnalysis(LocalObjectsAnalysis loa, InfoFlowAnalysis dfa,
UseFinder uf, SootClass sc) {
// find the right run methods to use for threads of type sc
List<SootMethod> runMethods = new ArrayList<SootMethod>();
Iterator<AbstractRuntimeThread> threadsIt = threads.iterator();
while (threadsIt.hasNext()) {
AbstractRuntimeThread thread = threadsIt.next();
Iterator<Object> runMethodsIt = thread.getRunMethods().iterator();
while (runMethodsIt.hasNext()) {
SootMethod runMethod = (SootMethod) runMethodsIt.next();
if (runMethod.getDeclaringClass() == sc) {
runMethods.add(runMethod);
}
}
}
return new ClassLocalObjectsAnalysis(loa, dfa, primitiveDfa, uf, sc, runMethods);
}
// Determines if a RefType Local or a FieldRef is Thread-Local
public boolean isObjectThreadLocal(Value localOrRef, SootMethod sm) {
if (threads.size() <= 1) {
return true;
// Pair cacheKey = new Pair(new EquivalentValue(localOrRef), sm);
// if(valueCache.containsKey(cacheKey))
// {
// return ((Boolean) valueCache.get(cacheKey)).booleanValue();
// }
}
if (printDebug) {
logger.debug("- " + localOrRef + " in " + sm + " is...");
}
Collection<AbstractRuntimeThread> mhpThreads = mhp.getThreads();
if (mhpThreads != null) {
for (AbstractRuntimeThread thread : mhpThreads) {
for (Object meth : thread.getRunMethods()) {
SootMethod runMethod = (SootMethod) meth;
if (runMethod.getDeclaringClass().isApplicationClass() && !isObjectLocalToContext(localOrRef, sm, runMethod)) {
if (printDebug) {
logger.debug(" THREAD-SHARED (simpledfa " + ClassInfoFlowAnalysis.methodCount + " smartdfa "
+ SmartMethodInfoFlowAnalysis.counter + " smartloa " + SmartMethodLocalObjectsAnalysis.counter + ")");
}
// valueCache.put(cacheKey, Boolean.FALSE);
// escapesThrough(localOrRef, sm);
return false;
}
}
}
}
if (printDebug) {
logger.debug(" THREAD-LOCAL (simpledfa " + ClassInfoFlowAnalysis.methodCount + " smartdfa "
+ SmartMethodInfoFlowAnalysis.counter + " smartloa " + SmartMethodLocalObjectsAnalysis.counter + ")");// (" +
// localOrRef
// + " in " +
// sm + ")");
}
// valueCache.put(cacheKey, Boolean.TRUE);
return true;
}
/*
* public boolean isFieldThreadLocal(SootField sf, SootMethod sm) // this is kind of meaningless..., if we're looking in a
* particular method, we'd use isObjectThreadLocal { logger.debug("- Checking if " + sf + " in " + sm +
* " is thread-local"); Iterator threadClassesIt = threadClasses.iterator(); while(threadClassesIt.hasNext()) { SootClass
* threadClass = (SootClass) threadClassesIt.next(); if(!isFieldLocalToContext(sf, sm, threadClass)) {
* logger.debug(" THREAD-SHARED"); return false; } } logger.debug(" THREAD-LOCAL");// (" + sf + " in " + sm + ")");
* return true; }
*/
public boolean hasNonThreadLocalEffects(SootMethod containingMethod, InvokeExpr ie) {
if (threads.size() <= 1) {
return true;
}
return true;
/*
* Pair cacheKey = new Pair(new EquivalentValue(ie), containingMethod); if(invokeCache.containsKey(cacheKey)) { return
* ((Boolean) invokeCache.get(cacheKey)).booleanValue(); }
*
* logger.debug("- " + ie + " in " + containingMethod + " has "); Iterator threadsIt = threads.iterator();
* while(threadsIt.hasNext()) { AbstractRuntimeThread thread = (AbstractRuntimeThread) threadsIt.next(); Iterator
* runMethodsIt = thread.getRunMethods().iterator(); while(runMethodsIt.hasNext()) { SootMethod runMethod = (SootMethod)
* runMethodsIt.next(); if( runMethod.getDeclaringClass().isApplicationClass() && hasNonLocalEffects(containingMethod,
* ie, runMethod)) { logger.debug("THREAD-VISIBLE (simpledfa " + ClassInfoFlowAnalysis.methodCount + " smartdfa " +
* SmartMethodInfoFlowAnalysis.counter + " smartloa " + SmartMethodLocalObjectsAnalysis.counter + ")");// (" + ie + " in
* " + containingMethod + ")"); invokeCache.put(cacheKey, Boolean.TRUE); return true; } } } logger.debug("THREAD-PRIVATE
* (simpledfa " + ClassInfoFlowAnalysis.methodCount + " smartdfa " + SmartMethodInfoFlowAnalysis.counter + " smartloa " +
* SmartMethodLocalObjectsAnalysis.counter + ")");// (" + ie + " in " + containingMethod + ")");
* invokeCache.put(cacheKey, Boolean.FALSE); return false; //
*/
}
/**
* Returns a list of thread-shared sources and sinks. Returns empty list if not actually a shared value.
*/
public List escapesThrough(Value sharedValue, SootMethod containingMethod) {
List ret = new ArrayList();
// The containingMethod might be called from multiple threads
// It is possible for interestingValue to be thread-shared from some threads but not others,
// so we must look at each thread separately.
for (AbstractRuntimeThread thread : mhp.getThreads()) {
// Each "abstract thread" from the MHP analysis actually represents a "Thread.start()" statement that could
// be starting one of several different kinds of threads. We must consider each kind separately.
for (Object meth : thread.getRunMethods()) {
SootMethod runMethod = (SootMethod) meth;
// We can only analyze application classes for TLO
if (runMethod.getDeclaringClass().isApplicationClass()
&& !isObjectLocalToContext(sharedValue, containingMethod, runMethod)) {
// This is one of the threads for which sharedValue is thread-shared
// so now we will look for which object it escapes through
ClassLocalObjectsAnalysis cloa = getClassLocalObjectsAnalysis(containingMethod.getDeclaringClass());
CallLocalityContext clc = cloa.getMergedContext(containingMethod);
// Get the method info flow analysis object
SmartMethodInfoFlowAnalysis smifa = dfa.getMethodInfoFlowAnalysis(containingMethod);
// Get an IFA node for our sharedValue
EquivalentValue sharedValueEqVal;
if (sharedValue instanceof InstanceFieldRef) {
sharedValueEqVal = InfoFlowAnalysis.getNodeForFieldRef(containingMethod, ((FieldRef) sharedValue).getField());
} else {
sharedValueEqVal = new EquivalentValue(sharedValue);
}
// Get the sources of our interesting value
List<EquivalentValue> sources = smifa.sourcesOf(sharedValueEqVal);
for (EquivalentValue source : sources) {
if (source.getValue() instanceof Ref) {
if (clc != null && !clc.isFieldLocal(source)) // (bail out if clc is null)
{
ret.add(source);
// System.out.println(sharedValue + " in " + containingMethod + " escapes through " + source);
}
}
}
}
}
}
return ret;
}
}
| 10,772
| 44.264706
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/CheckMSet.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.tagkit.Tag;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class CheckMSet {
CheckMSet(Map m1, Map m2) {
checkKeySet(m1, m2);
check(m1, m2);
}
private void checkKeySet(Map m1, Map m2) {
Iterator keySetIt2 = m2.keySet().iterator();
FlowSet temp = new ArraySparseSet();
while (keySetIt2.hasNext()) {
Object key2 = keySetIt2.next();
if (key2 instanceof List) {
Iterator it = ((List) key2).iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof List) {
Iterator itit = ((List) obj).iterator();
while (itit.hasNext()) {
Object o = itit.next();
temp.add(o);
if (!m1.containsKey(o)) {
throw new RuntimeException("1--before compacting map does not contains key " + o);
}
}
} else {
temp.add(obj);
if (!m1.containsKey(obj)) {
throw new RuntimeException("2--before compacting map does not contains key " + obj);
}
}
}
} else {
if (!(key2 instanceof JPegStmt)) {
throw new RuntimeException("key error: " + key2);
}
temp.add(key2);
if (!m1.containsKey(key2)) {
throw new RuntimeException("3--before compacting map does not contains key " + key2);
}
}
}
Iterator keySetIt1 = m1.keySet().iterator();
while (keySetIt1.hasNext()) {
Object key1 = keySetIt1.next();
if (!temp.contains(key1)) {
throw new RuntimeException("after compacting map does not contains key " + key1);
}
}
}
private void check(Map m1, Map m2) {
Iterator keySetIt = m2.keySet().iterator();
while (keySetIt.hasNext()) {
Object key = keySetIt.next();
if (key instanceof JPegStmt) {
Tag tag1 = (Tag) ((JPegStmt) key).getTags().get(0);
// System.out.println("check key: "+tag1+" "+key);
}
// System.out.println("check key: "+key);
FlowSet mSet2 = (FlowSet) m2.get(key);
if (key instanceof List) {
Iterator it = ((List) key).iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof List) {
Iterator itit = ((List) obj).iterator();
while (itit.hasNext()) {
Object oo = itit.next();
FlowSet mSet11 = (FlowSet) m1.get(oo);
if (mSet11 == null) {
throw new RuntimeException("1--mSet of " + obj + " is null!");
}
if (!compare(mSet11, mSet2)) {
throw new RuntimeException("1--mSet before and after are NOT the same!");
}
}
} else {
FlowSet mSet1 = (FlowSet) m1.get(obj);
if (mSet1 == null) {
throw new RuntimeException("2--mSet of " + obj + " is null!");
}
if (!compare(mSet1, mSet2)) {
throw new RuntimeException("2--mSet before and after are NOT the same!");
}
}
}
} else {
FlowSet mSet1 = (FlowSet) m1.get(key);
if (!compare(mSet1, mSet2)) {
throw new RuntimeException("3--mSet before and after are NOT the same!");
}
}
}
// System.err.println("---mSet before and after are the same!---");
}
private boolean compare(FlowSet mSet1, FlowSet mSet2) {
{
Iterator it = mSet2.iterator();
FlowSet temp = new ArraySparseSet();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof List) {
Iterator listIt = ((List) obj).iterator();
while (listIt.hasNext()) {
Object o = listIt.next();
if (o instanceof List) {
Iterator itit = ((List) o).iterator();
while (itit.hasNext()) {
temp.add(itit.next());
}
} else {
temp.add(o);
}
}
} else {
temp.add(obj);
}
}
Iterator it1 = mSet1.iterator();
while (it1.hasNext()) {
Object o = it1.next();
if (!temp.contains(o)) {
System.out.println("mSet2: \n" + mSet2);
System.err.println("mSet2 does not contains " + o);
return false;
}
}
}
{
Iterator it = mSet2.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof List) {
Iterator listIt = ((List) obj).iterator();
while (listIt.hasNext()) {
Object o = listIt.next();
if (o instanceof List) {
Iterator itit = ((List) o).iterator();
while (itit.hasNext()) {
Object oo = itit.next();
if (!mSet1.contains(oo)) {
System.err.println("1--mSet1 does not contains " + oo);
return false;
}
}
} else {
if (!mSet1.contains(o)) {
System.err.println("2--mSet1 does not contains " + o);
return false;
}
}
}
}
else {
if (!mSet1.contains(obj)) {
System.err.println("3--mSet1 does not contains " + obj);
return false;
}
}
}
}
return true;
}
}
| 6,919
| 29.218341
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/CompactSequentNodes.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.ListIterator;
import java.util.Map;
import java.util.Set;
import soot.toolkits.scalar.FlowSet;
import soot.util.Chain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class CompactSequentNodes {
long compactNodes = 0;
long add = 0;
public CompactSequentNodes(PegGraph pg) {
Chain mainPegChain = pg.getMainPegChain();
compactGraph(mainPegChain, pg);
compactStartChain(pg);
// PegToDotFile printer = new PegToDotFile(pg, false, "sequence");
System.err.println("compact seq. node: " + compactNodes);
System.err.println("number of compacting seq. nodes: " + add);
}
private void compactGraph(Chain chain, PegGraph peg) {
Set canNotBeCompacted = peg.getCanNotBeCompacted();
List<List<Object>> list = computeSequentNodes(chain, peg);
// printSeq(list);
Iterator<List<Object>> it = list.iterator();
while (it.hasNext()) {
List s = it.next();
if (!checkIfContainsElemsCanNotBeCompacted(s, canNotBeCompacted)) {
add++;
compact(s, chain, peg);
}
}
}
private void compactStartChain(PegGraph graph) {
Set maps = graph.getStartToThread().entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
List runMethodChainList = (List) entry.getValue();
Iterator it = runMethodChainList.iterator();
while (it.hasNext()) {
Chain chain = (Chain) it.next();
compactGraph(chain, graph);
}
}
}
private List<List<Object>> computeSequentNodes(Chain chain, PegGraph pg) {
Set<Object> gray = new HashSet<Object>();
List<List<Object>> sequentNodes = new ArrayList<List<Object>>();
Set canNotBeCompacted = pg.getCanNotBeCompacted();
TopologicalSorter ts = new TopologicalSorter(chain, pg);
ListIterator<Object> it = ts.sorter().listIterator();
while (it.hasNext()) {
Object node = it.next();
List<Object> list = new ArrayList<Object>();
if (!gray.contains(node)) {
visitNode(pg, node, list, canNotBeCompacted, gray);
if (list.size() > 1) {
gray.addAll(list);
sequentNodes.add(list);
}
}
}
return sequentNodes;
}
private void visitNode(PegGraph pg, Object node, List<Object> list, Set canNotBeCompacted, Set<Object> gray) {
// System.out.println("node is: "+node);
if (pg.getPredsOf(node).size() == 1 && pg.getSuccsOf(node).size() == 1 && !canNotBeCompacted.contains(node)
&& !gray.contains(node)) {
list.add(node);
Iterator it = pg.getSuccsOf(node).iterator();
while (it.hasNext()) {
Object o = it.next();
visitNode(pg, o, list, canNotBeCompacted, gray);
}
}
return;
}
private boolean checkIfContainsElemsCanNotBeCompacted(List list, Set canNotBeCompacted) {
Iterator sccIt = list.iterator();
while (sccIt.hasNext()) {
Object node = sccIt.next();
if (canNotBeCompacted.contains(node)) {
// System.out.println("find a syn method!!");
return true;
}
}
return false;
}
private void compact(List list, Chain chain, PegGraph peg) {
Iterator it = list.iterator();
FlowSet allNodes = peg.getAllNodes();
HashMap unitToSuccs = peg.getUnitToSuccs();
HashMap unitToPreds = peg.getUnitToPreds();
List<Object> newPreds = new ArrayList<Object>();
List<Object> newSuccs = new ArrayList<Object>();
while (it.hasNext()) {
Object s = it.next();
{
Iterator predsIt = peg.getPredsOf(s).iterator();
while (predsIt.hasNext()) {
Object pred = predsIt.next();
List succsOfPred = peg.getSuccsOf(pred);
succsOfPred.remove(s);
if (!list.contains(pred)) {
newPreds.add(pred);
succsOfPred.add(list);
}
}
}
{
Iterator succsIt = peg.getSuccsOf(s).iterator();
while (succsIt.hasNext()) {
Object succ = succsIt.next();
List predsOfSucc = peg.getPredsOf(succ);
predsOfSucc.remove(s);
if (!list.contains(succ)) {
newSuccs.add(succ);
predsOfSucc.add(list);
}
}
}
}
unitToSuccs.put(list, newSuccs);
// System.out.println("put list"+list+"\n"+ "newSuccs: "+newSuccs);
unitToPreds.put(list, newPreds);
allNodes.add(list);
chain.add(list);
updateMonitor(peg, list);
{
it = list.iterator();
while (it.hasNext()) {
Object s = it.next();
chain.remove(s);
allNodes.remove(s);
unitToSuccs.remove(s);
unitToPreds.remove(s);
}
}
// System.out.println("inside compactSCC");
// testListSucc(peg);
compactNodes += list.size();
}
// The compacted nodes may inside some monitors. We need to update monitor objects.
private void updateMonitor(PegGraph pg, List list) {
// System.out.println("=======update monitor===");
// add list to corresponding monitor objects sets
Set maps = pg.getMonitor().entrySet();
// System.out.println("---test list----");
// testList(list);
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
FlowSet fs = (FlowSet) entry.getValue();
Iterator it = list.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (fs.contains(obj)) {
fs.add(list);
// flag = true;
break;
// System.out.println("add list to monitor: "+entry.getKey());
}
}
}
// System.out.println("=======update monitor==end====");
}
}
| 7,080
| 29.131915
| 112
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/CompactStronglyConnectedComponents.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.toolkits.scalar.FlowSet;
import soot.util.Chain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class CompactStronglyConnectedComponents {
long compactNodes = 0;
long add = 0;
public CompactStronglyConnectedComponents(PegGraph pg) {
Chain mainPegChain = pg.getMainPegChain();
compactGraph(mainPegChain, pg);
compactStartChain(pg);
// PegToDotFile printer = new PegToDotFile(pg, false, "compact");
System.err.println("compact SCC nodes: " + compactNodes);
System.err.println(" number of compacting scc nodes: " + add);
}
private void compactGraph(Chain chain, PegGraph peg) {
Set canNotBeCompacted = peg.getCanNotBeCompacted();
// testCan(speg.getMainPegChain(), canNotBeCompacted);
// SCC scc = new SCC(chain, peg);
SCC scc = new SCC(chain.iterator(), peg);
List<List<Object>> sccList = scc.getSccList();
// testSCC(sccList);
Iterator<List<Object>> sccListIt = sccList.iterator();
while (sccListIt.hasNext()) {
List s = sccListIt.next();
if (s.size() > 1) {
// printSCC(s);
if (!checkIfContainsElemsCanNotBeCompacted(s, canNotBeCompacted)) {
add++;
compact(s, chain, peg);
}
}
}
// testListSucc(peg);
}
private void compactStartChain(PegGraph graph) {
Set maps = graph.getStartToThread().entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
List runMethodChainList = (List) entry.getValue();
Iterator it = runMethodChainList.iterator();
while (it.hasNext()) {
Chain chain = (Chain) it.next();
compactGraph(chain, graph);
}
}
}
private boolean checkIfContainsElemsCanNotBeCompacted(List list, Set canNotBeCompacted) {
Iterator sccIt = list.iterator();
// System.out.println("sccList: ");
while (sccIt.hasNext()) {
JPegStmt node = (JPegStmt) sccIt.next();
// System.out.println("elem of scc:");
if (canNotBeCompacted.contains(node)) {
// System.out.println("find a syn method!!");
return true;
}
}
return false;
}
private void compact(List list, Chain chain, PegGraph peg) {
Iterator it = list.iterator();
FlowSet allNodes = peg.getAllNodes();
HashMap unitToSuccs = peg.getUnitToSuccs();
HashMap unitToPreds = peg.getUnitToPreds();
List<Object> newPreds = new ArrayList<Object>();
List<Object> newSuccs = new ArrayList<Object>();
while (it.hasNext()) {
JPegStmt s = (JPegStmt) it.next();
// Replace the SCC with a list node.
{
Iterator predsIt = peg.getPredsOf(s).iterator();
while (predsIt.hasNext()) {
Object pred = predsIt.next();
List succsOfPred = peg.getSuccsOf(pred);
succsOfPred.remove(s);
if (!list.contains(pred)) {
newPreds.add(pred);
succsOfPred.add(list);
}
}
}
{
Iterator succsIt = peg.getSuccsOf(s).iterator();
while (succsIt.hasNext()) {
Object succ = succsIt.next();
List predsOfSucc = peg.getPredsOf(succ);
predsOfSucc.remove(s);
if (!list.contains(succ)) {
newSuccs.add(succ);
predsOfSucc.add(list);
}
}
}
}
unitToSuccs.put(list, newSuccs);
// System.out.println("put list"+list+"\n"+ "newSuccs: "+newSuccs);
unitToPreds.put(list, newPreds);
allNodes.add(list);
chain.add(list);
updateMonitor(peg, list);
{
it = list.iterator();
while (it.hasNext()) {
JPegStmt s = (JPegStmt) it.next();
chain.remove(s);
allNodes.remove(s);
unitToSuccs.remove(s);
unitToPreds.remove(s);
}
}
// System.out.println("inside compactSCC");
// testListSucc(peg);
// add for get experimental results
compactNodes += list.size();
}
private void updateMonitor(PegGraph pg, List list) {
// System.out.println("=======update monitor===");
// add list to corresponding monitor objects sets
Set maps = pg.getMonitor().entrySet();
// System.out.println("---test list----");
// testList(list);
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
FlowSet fs = (FlowSet) entry.getValue();
Iterator it = list.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (fs.contains(obj)) {
fs.add(list);
break;
// System.out.println("add list to monitor: "+entry.getKey());
}
}
}
// System.out.println("=======update monitor==end====");
}
}
| 6,206
| 28.841346
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/Counter.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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%
*/
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class Counter {
private static int tagNo = 0;
private static int objNo = 0;
private static int threadNo = 0;
Counter() {
}
protected static int getTagNo() {
return tagNo++;
}
protected static int getObjNo() {
return objNo++;
}
protected static int getThreadNo() {
return threadNo++;
}
}
| 1,646
| 27.894737
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/DfsForBackEdge.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.tagkit.Tag;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.FlowSet;
import soot.util.Chain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class DfsForBackEdge {
private final Map<Object, Object> backEdges = new HashMap<Object, Object>();
private final Set<Object> gray = new HashSet<Object>();
private final Set<Object> black = new HashSet<Object>();
private final DominatorsFinder domFinder;
DfsForBackEdge(Chain chain, DirectedGraph peg) {
domFinder = new DominatorsFinder(chain, peg);
Iterator it = chain.iterator();
dfs(it, peg);
testBackEdge();
}
private void dfs(Iterator it, DirectedGraph g) {
// Visit each node
{
while (it.hasNext()) {
Object s = it.next();
if (!gray.contains(s)) {
visitNode(g, s);
}
}
}
}
private void visitNode(DirectedGraph g, Object s) {
// System.out.println("s is: "+ s);
gray.add(s);
Iterator it = g.getSuccsOf(s).iterator();
if (g.getSuccsOf(s).size() > 0) {
while (it.hasNext()) {
Object succ = it.next();
if (!gray.contains(succ)) {
visitNode(g, succ);
} else {
// if the color of the node is gray, then we found a retreating edge
if (gray.contains(succ) && !black.contains(succ)) {
/*
* If succ is in s's dominator list, then this retreating edge is a back edge.
*/
FlowSet dominators = domFinder.getDominatorsOf(s);
if (dominators.contains(succ)) {
System.out.println("s is " + s);
System.out.println("succ is " + succ);
backEdges.put(s, succ);
}
}
}
}
}
black.add(s);
}
protected Map<Object, Object> getBackEdges() {
return backEdges;
}
private void testBackEdge() {
System.out.println("===test backEdges==");
Set maps = backEdges.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
JPegStmt key = (JPegStmt) entry.getKey();
Tag tag = (Tag) key.getTags().get(0);
System.out.println("---key= " + tag + " " + key);
JPegStmt value = (JPegStmt) entry.getValue();
Tag tag1 = (Tag) value.getTags().get(0);
System.out.println("---value= " + tag1 + " " + value);
}
System.out.println("===test backEdges==end==");
}
}
| 3,908
| 28.613636
| 90
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/DominatorsFinder.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.util.Chain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class DominatorsFinder {
private final Map<Object, FlowSet> unitToDominators;
private final DirectedGraph peg;
DominatorsFinder(Chain chain, DirectedGraph pegGraph) {
unitToDominators = new HashMap<Object, FlowSet>();
peg = pegGraph;
find(chain);
// testUnitToDominators();
}
private void find(Chain chain) {
boolean change = true;
Iterator chainIt;
FlowSet fullSet = new ArraySparseSet();
FlowSet temp = new ArraySparseSet();
{
chainIt = chain.iterator();
while (chainIt.hasNext()) {
fullSet.add(chainIt.next());
}
}
List heads = peg.getHeads();
if (heads.size() != 1) {
throw new RuntimeException("The size of heads of peg is not equal to 1!");
} else {
FlowSet dominators = new ArraySparseSet();
Object head = heads.get(0);
dominators.add(head);
unitToDominators.put(head, dominators);
}
{
chainIt = chain.iterator();
while (chainIt.hasNext()) {
Object n = chainIt.next();
if (heads.contains(n)) {
continue;
}
FlowSet domin = new ArraySparseSet();
fullSet.copy(domin);
unitToDominators.put(n, domin);
}
}
System.out.println("===finish init unitToDominators===");
System.err.println("===finish init unitToDominators===");
// testUnitToDominators();
do {
change = false;
Iterator it = chain.iterator();
while (it.hasNext()) {
Object n = it.next();
if (heads.contains(n)) {
continue;
} else {
fullSet.copy(temp);
Iterator predsIt = peg.getPredsOf(n).iterator();
while (predsIt.hasNext()) {
Object p = predsIt.next();
FlowSet dom = getDominatorsOf(p);
temp.intersection(dom);
}
FlowSet d = new ArraySparseSet();
FlowSet nSet = new ArraySparseSet();
nSet.add(n);
nSet.union(temp, d);
FlowSet dominN = getDominatorsOf(n);
if (!d.equals(dominN)) {
change = true;
dominN = d;
}
}
}
} while (!change);
}
public FlowSet getDominatorsOf(Object s) {
if (!unitToDominators.containsKey(s)) {
throw new RuntimeException("Invalid stmt" + s);
}
return unitToDominators.get(s);
}
}
| 3,936
| 26.921986
| 80
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/LoopBodyFinder.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import soot.toolkits.graph.DirectedGraph;
import soot.util.FastStack;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class LoopBodyFinder {
private final FastStack<Object> stack = new FastStack<Object>();
private final Set<Set<Object>> loops = new HashSet<Set<Object>>();
LoopBodyFinder(Map<Object, Object> backEdges, DirectedGraph g) {
findLoopBody(backEdges, g);
}
private void findLoopBody(Map<Object, Object> backEdges, DirectedGraph g) {
Set maps = backEdges.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object tail = entry.getKey();
// Tag tag = (Tag)key.getTags().get(0);
// System.out.println("---key= "+tag+" "+key);
Object head = entry.getValue();
Set<Object> loopBody = finder(tail, head, g);
loops.add(loopBody);
}
}
private Set<Object> finder(Object tail, Object head, DirectedGraph g) {
Set<Object> loop = new HashSet<Object>();
loop.add(head);
insert(tail, loop);
while (!stack.empty()) {
Object p = stack.pop();
Iterator predsListIt = g.getPredsOf(p).iterator();
while (predsListIt.hasNext()) {
Object pred = predsListIt.next();
insert(pred, loop);
}
}
return loop;
}
private void insert(Object m, Set<Object> loop) {
if (!loop.contains(m)) {
loop.add(m);
stack.push(m);
}
}
public Set<Set<Object>> getLoopBody() {
return loops;
}
}
| 2,865
| 29.817204
| 77
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/LoopFinder.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.tagkit.Tag;
import soot.util.Chain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class LoopFinder {
private final Map<Chain, Set<Set<Object>>> chainToLoop = new HashMap<Chain, Set<Set<Object>>>();
LoopFinder(PegGraph peg) {
Chain chain = peg.getMainPegChain();
DfsForBackEdge dfsForBackEdge = new DfsForBackEdge(chain, peg);
Map<Object, Object> backEdges = dfsForBackEdge.getBackEdges();
LoopBodyFinder lbf = new LoopBodyFinder(backEdges, peg);
Set<Set<Object>> loopBody = lbf.getLoopBody();
testLoops(loopBody);
chainToLoop.put(chain, loopBody);
}
private void testLoops(Set<Set<Object>> loopBody) {
System.out.println("====loops===");
Iterator<Set<Object>> it = loopBody.iterator();
while (it.hasNext()) {
Set loop = it.next();
Iterator loopIt = loop.iterator();
System.out.println("---loop---");
while (loopIt.hasNext()) {
JPegStmt o = (JPegStmt) loopIt.next();
Tag tag = (Tag) o.getTags().get(0);
System.out.println(tag + " " + o);
}
}
System.out.println("===end===loops===");
}
}
| 2,541
| 32.447368
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/MethodExtentBuilder.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import soot.Body;
import soot.SootMethod;
import soot.Value;
import soot.jimple.InvokeExpr;
import soot.jimple.MonitorStmt;
import soot.jimple.Stmt;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.thread.mhp.pegcallgraph.CheckRecursiveCalls;
import soot.jimple.toolkits.thread.mhp.pegcallgraph.PegCallGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class MethodExtentBuilder {
// private List inlineSites = new ArrayList();
private final Set<Object> methodsNeedingInlining = new HashSet<Object>();
public MethodExtentBuilder(Body unitBody, PegCallGraph pcg, CallGraph cg) {
// testCallGraph(cg);
build(pcg, cg);
// checkMethodNeedExtent();
CheckRecursiveCalls crc = new CheckRecursiveCalls(pcg, methodsNeedingInlining);
// testMap();
// checkSccList(sccList, cg);
propagate(pcg);
// checkMethodNeedExtent();
}
public Set<Object> getMethodsNeedingInlining() {
return methodsNeedingInlining;
}
private void build(PegCallGraph pcg, CallGraph cg) {
Iterator it = pcg.iterator();
while (it.hasNext()) {
SootMethod method = (SootMethod) it.next();
computeForMethodInlining(method, cg);
}
}
private void computeForMethodInlining(SootMethod targetMethod, CallGraph cg) {
// System.out.println("method: "+targetMethod);
if (targetMethod.isSynchronized()) {
methodsNeedingInlining.add(targetMethod);
return;
}
Body mBody = targetMethod.getActiveBody();
Iterator bodyIt = mBody.getUnits().iterator();
while (bodyIt.hasNext()) {
Stmt stmt = (Stmt) bodyIt.next();
if (stmt instanceof MonitorStmt) {
// methodsNeedingInlining.put(targetMethod, new Boolean(true));
methodsNeedingInlining.add(targetMethod);
// System.out.println("put: "+targetMethod);
return;
// return true;
} else {
if (stmt.containsInvokeExpr()) {
// System.out.println("stmt is: "+stmt);
Value invokeExpr = (stmt).getInvokeExpr();
SootMethod method = ((InvokeExpr) invokeExpr).getMethod();
String name = method.getName();
if (name.equals("wait") || name.equals("notify") || name.equals("notifyAll")
|| ((name.equals("start") || name.equals("join") || name.equals("suspend") || name.equals("resume")
|| name.equals("destroy") || name.equals("stop"))
&& method.getDeclaringClass().getName().equals("java.lang.Thread"))) {
methodsNeedingInlining.add(targetMethod);
return;
} else {
if (method.isConcrete() && !method.getDeclaringClass().isLibraryClass()) {
Iterator it = cg.edgesOutOf(stmt);
TargetMethodsFinder tmd = new TargetMethodsFinder();
Iterator<SootMethod> targetIt = (tmd.find(stmt, cg, true, false)).iterator();
while (targetIt.hasNext()) {
SootMethod target = targetIt.next();
if (target.isSynchronized()) {
// System.out.println("method is synchronized: "+method);
methodsNeedingInlining.add(targetMethod);
return;
}
}
}
}
}
}
}
return;
}
protected void propagate(PegCallGraph cg) {
/*
* if a method is not in methodsNeedingInlining, use DFS to find out if it's parents need inlining. If so, add it to
* methodsNeedingInlining
*/
Set<Object> gray = new HashSet<Object>();
Iterator it = cg.iterator();
while (it.hasNext()) {
Object o = it.next();
if (methodsNeedingInlining.contains(o)) {
continue;
} else if (!gray.contains(o)) {
// System.out.println("visit: "+o);
if (visitNode(o, gray, cg)) {
methodsNeedingInlining.add(o);
// System.out.println("put: "+o+"in pro");
}
}
}
// System.out.println("======after pro========");
}
private boolean visitNode(Object o, Set<Object> gray, PegCallGraph cg) {
// System.out.println("visit(in visit): "+o);
gray.add(o);
Iterator childIt = (cg.getSuccsOf(o)).iterator();
while (childIt.hasNext()) {
Object child = childIt.next();
if (methodsNeedingInlining.contains(child)) {
gray.add(child);
// methodsNeedingInlining.add(child);
// System.out.println("return true for: "+child);
return true;
} else {
if (!gray.contains(child)) {
if (visitNode(child, gray, cg)) {
methodsNeedingInlining.add(child);
// System.out.println("put: "+child+"in pro");
// System.out.println("return true for: "+child);
return true;
}
}
}
}
return false;
}
}
| 6,181
| 31.536842
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/MethodInliner.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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 soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.util.Chain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class MethodInliner {
// private ArrayList inlineSite;
MethodInliner() {
// inlineSite = new ArrayList();
}
public static void inline(ArrayList sites) {
Iterator it = sites.iterator();
while (it.hasNext()) {
ArrayList element = (ArrayList) it.next();
JPegStmt stmt = (JPegStmt) element.get(0);
Chain chain = (Chain) element.get(1);
PegGraph p1 = (PegGraph) element.get(2);
PegGraph p2 = (PegGraph) element.get(3);
// testHeads(p2);
// System.out.println("before inlining: stmt:"+stmt);
// System.out.println(p1);
inline(stmt, chain, p1, p2);
// System.out.println("after inlining: stmt:"+stmt);
// System.out.println(p1);
}
}
private static void inline(JPegStmt invokeStmt, Chain chain, PegGraph container, PegGraph inlinee) {
// System.out.println("==inside inline===");
// PegToDotFile printer = new PegToDotFile(inlinee, false, "before_addPeg_inlinee"+invokeStmt.getName());
if (!container.addPeg(inlinee, chain)) {
throw new RuntimeException("heads >1 stm: " + invokeStmt);
}
// printer = new PegToDotFile(container, false, "after_addPeg_"+invokeStmt);
container.buildSuccsForInlining(invokeStmt, chain, inlinee);
// printer = new PegToDotFile(container, false, "after_bu_succ_"+invokeStmt.getName());
// System.out.println(container);
container.buildMaps(inlinee);
container.buildPreds();
// container.testStartToThread();
}
}
| 2,943
| 32.454545
| 109
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/MhpAnalysis.java
|
/*0815 use complete graph, success
*0801 add the special treatment for waitng->notified-entry,--- and localSucc(n)
*0730 add MSym set for each node to store the nodes added to the m set during symmetry step.
*/
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.jimple.toolkits.thread.mhp.stmt.BeginStmt;
import soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.jimple.toolkits.thread.mhp.stmt.JoinStmt;
import soot.jimple.toolkits.thread.mhp.stmt.MonitorEntryStmt;
import soot.jimple.toolkits.thread.mhp.stmt.NotifiedEntryStmt;
import soot.jimple.toolkits.thread.mhp.stmt.NotifyAllStmt;
import soot.jimple.toolkits.thread.mhp.stmt.NotifyStmt;
import soot.jimple.toolkits.thread.mhp.stmt.StartStmt;
import soot.jimple.toolkits.thread.mhp.stmt.WaitingStmt;
import soot.tagkit.Tag;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.util.Chain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
/**
* @author Lin Li This is a synchronization-aware May Happen in Parallel (MHP) analysis. It works by analyzing a PegGraph
* (simplified whole-program control flow graph that includes thread executions and synchronization).
*/
class MhpAnalysis {
private PegGraph g;
private final Map<Object, FlowSet> unitToGen;
private final Map<Object, FlowSet> unitToKill;
private final Map<Object, FlowSet> unitToM;
// private Map unitToMSym;
private final Map<Object, FlowSet> unitToOut;
private final Map<Object, FlowSet> notifySucc;
private final Map<String, FlowSet> monitor;
private final Map<JPegStmt, Set<JPegStmt>> notifyPred;
FlowSet fullSet = new ArraySparseSet();
LinkedList<Object> workList = new LinkedList<Object>();
MhpAnalysis(PegGraph g) {
// System.out.println("******entering MhpAnalysis");
this.g = g;
int size = g.size();
Map startToThread = g.getStartToThread();
unitToGen = new HashMap<Object, FlowSet>(size * 2 + 1, 0.7f);
unitToKill = new HashMap<Object, FlowSet>(size * 2 + 1, 0.7f);
unitToM = new HashMap<Object, FlowSet>(size * 2 + 1, 0.7f);
// unitToMSym = new HashMap(size*2+1, 0.7f);
unitToOut = new HashMap<Object, FlowSet>(size * 2 + 1, 0.7f);
notifySucc = new HashMap<Object, FlowSet>(size * 2 + 1, 0.7f);
// notifyEdge = new HashMap(size*2+1,0.7f);
notifyPred = new HashMap<JPegStmt, Set<JPegStmt>>(size * 2 + 1, 0.7f);
// monitor = new HashMap(size*2+1,0.7f);
monitor = g.getMonitor();
// testMap(monitor, "monitor");
/*
* Initialize the KILL, GEN, M, and OUT set to empty set for all nodes.
*/
Iterator it = g.iterator();
while (it.hasNext()) {
Object stmt = it.next();
FlowSet genSet = new ArraySparseSet();
FlowSet killSet = new ArraySparseSet();
FlowSet mSet = new ArraySparseSet();
FlowSet outSet = new ArraySparseSet();
// stupidly add notifySucc for every node
FlowSet notifySuccSet = new ArraySparseSet();
unitToGen.put(stmt, genSet);
unitToKill.put(stmt, killSet);
unitToM.put(stmt, mSet);
unitToOut.put(stmt, outSet);
notifySucc.put(stmt, notifySuccSet);
}
// System.out.println("before init worklist");
// testM();
// System.err.println("finish initializing kill,gen,m,out to empty set");
/*
* Initialize the worklist to include all start nodes in the main thread that are reachable from the begin node of the
* main thread
*/
Set keys = startToThread.keySet();
Iterator keysIt = keys.iterator();
while (keysIt.hasNext()) {
JPegStmt stmt = (JPegStmt) keysIt.next();
if (!workList.contains(stmt)) {
workList.addLast(stmt);
}
// System.out.println("add"+stmt+"to worklist");
}
// System.err.println("finish initializing worklist");
// testWorkList();
/*
* computer gen-set, and kill-set for each node
*/
it = g.iterator();
while (it.hasNext()) {
FlowSet genSet = new ArraySparseSet();
FlowSet killSet = new ArraySparseSet();
Object o = it.next();
// System.err.println(s);
if (o instanceof JPegStmt) {
JPegStmt s = (JPegStmt) o;
if (s instanceof JoinStmt) {
// if (s.getName().equals("join")){
// If specialJoin of Peg contains s, skip this node.
// Otherwise,compute kill set for (t,join,*).
if (g.getSpecialJoin().contains(s)) {
// System.out.println("==specialJoin contains: "+s);
continue;
} else {
// compute kill set for (t,join,*)
Chain chain = (g.getJoinStmtToThread().get(s));
Iterator nodesIt = chain.iterator();
if (nodesIt.hasNext()) {
while (nodesIt.hasNext()) {
killSet.add(nodesIt.next());
}
}
}
unitToGen.put(s, genSet);
unitToKill.put(s, killSet);
} else if (s instanceof MonitorEntryStmt || s instanceof NotifiedEntryStmt) {
// else if (s.getName().equals("entry") || s.getName().equals("notified-entry")){
Iterator It = g.iterator();
if (monitor.containsKey(s.getObject())) {
killSet = monitor.get(s.getObject());
}
unitToGen.put(s, genSet);
unitToKill.put(s, killSet);
} else if (s instanceof NotifyAllStmt) {
Map<String, FlowSet> waitingNodes = g.getWaitingNodes();
if (waitingNodes.containsKey(s.getObject())) {
// System.out.println("******find object:"+s.getObject());
FlowSet killNodes = waitingNodes.get(s.getObject());
Iterator nodesIt = killNodes.iterator();
while (nodesIt.hasNext()) {
killSet.add(nodesIt.next());
}
}
unitToGen.put(s, genSet);
unitToKill.put(s, killSet);
// stem.out.println("put "+s+"into set");
} else if (s instanceof NotifyStmt) {
// else if (s.getName().equals("notify")){
Map<String, FlowSet> waitingNodes = g.getWaitingNodes();
if (waitingNodes.containsKey(s.getObject())) {
FlowSet killNodes = waitingNodes.get(s.getObject());
if (killNodes.size() == 1) {
Iterator nodesIt = killNodes.iterator();
while (nodesIt.hasNext()) {
killSet.add(nodesIt.next());
}
}
}
unitToGen.put(s, genSet);
unitToKill.put(s, killSet);
// System.out.println("put "+s+"into set");
} else if ((s instanceof StartStmt) && g.getStartToThread().containsKey(s)) {
// modify Feb 5
Iterator chainIt = g.getStartToThread().get(s).iterator();
while (chainIt.hasNext()) {
PegChain chain = (PegChain) chainIt.next();
Iterator beginNodesIt = chain.getHeads().iterator();
while (beginNodesIt.hasNext()) {
genSet.add(beginNodesIt.next());
}
}
/*
* Iterator localSuccIt =((List)g.getSuccsOf(s)).iterator();
*
* while (localSuccIt.hasNext()){
*
* Object localSucc = localSuccIt.next(); genSet.add(localSucc); }
*/
unitToGen.put(s, genSet);
unitToKill.put(s, killSet);
}
}
} // end while
// System.err.println("finish compute genset and kill set for each nodes");
// testmaps();
// testGen();
// testKill();
doAnalysis();
// testNotifySucc();
// -----------
long beginTime = System.currentTimeMillis();
// testM();
computeMPairs();
computeMSet();
long buildPegDuration = (System.currentTimeMillis() - beginTime);
System.err.println("compute parir + mset: " + buildPegDuration);
// ------------
}
protected void doAnalysis() {
while (workList.size() > 0) {
// get the head of the worklist and remove the head
Object currentObj = workList.removeFirst();
// System.out.println("curObj: "+currentObj);
/*
* if (currentObj instanceof JPegStmt){ Tag tag = (Tag)((JPegStmt)currentObj).getTags().get(0);
* System.out.println("=====current node is:==="+tag+" "+currentObj); } else{
* System.out.println("===current node is: list==="); Iterator listIt = ((List)currentObj).iterator();
*
* while (listIt.hasNext()){ Object oo = listIt.next(); if (oo instanceof JPegStmt){ JPegStmt unit = (JPegStmt)oo; Tag
* tag = (Tag)unit.getTags().get(0); System.out.println(tag+" "+unit); } else System.out.println(oo); }
* System.out.println("===list==end=="); }
*/
// get kill, gen, m and out set.
FlowSet killSet = unitToKill.get(currentObj);
FlowSet genSet = unitToGen.get(currentObj);
// FlowSet mSet = (FlowSet)unitToM.get(currentNode);
FlowSet mSet = new ArraySparseSet();
FlowSet outSet = unitToOut.get(currentObj);
FlowSet notifySuccSet = notifySucc.get(currentObj);
/*
* if (unitToMSym.containsKey(currentObj)){ FlowSet mSetSym = (FlowSet)unitToMSym.get(currentObj);
* //test("mSetSym",mSetSym);
*
* mSet.union(mSetSym);
*
* }
*/
FlowSet mOld = unitToM.get(currentObj);
FlowSet outOld = outSet.clone();
FlowSet notifySuccSetOld = notifySuccSet.clone();
FlowSet genNotifyAllSet = new ArraySparseSet();
JPegStmt waitingPred = null;
// testSet(mOld, "mOld");
// testSet(outOld, "outOld");
// testSet(genSet, "genSet");
// testWorkList();
if (!(currentObj instanceof JPegStmt)) {
// compute M Set
Iterator localPredIt = (g.getPredsOf(currentObj)).iterator();
while (localPredIt.hasNext()) {
Object tempStmt = localPredIt.next();
FlowSet out = unitToOut.get(tempStmt);
// testSet(out,"out of localPred");
if (out != null) {
mSet.union(out);
}
}
/*
* if (unitToMSym.containsKey(currentObj)){ FlowSet mSetSym = (FlowSet)unitToMSym.get(currentObj);
* mSet.union(mSetSym); //testSet(mSetSym,"mSetSyn");
*
* }
*/
mSet.union(mOld);
unitToM.put(currentObj, mSet);
// end compute M(n) set
/*
* compute out set
*/
mSet.union(genSet, outSet);
if (killSet.size() > 0) {
Iterator killIt = killSet.iterator();
while (killIt.hasNext()) {
Object tempStmt = killIt.next();
if (outSet.contains(tempStmt)) {
outSet.remove(tempStmt);
}
}
}
// end compute out set
/*
* do the symmetry step for all new nodes in M(n)
*/
// test("######mSet old:",mOld);
// test("######mSet:",mSet);
// System.out.println("======entering symmetry====");
if (!mOld.equals(mSet)) {
// System.out.println("entering mold <> mset");
Iterator mSetIt = mSet.iterator();
while (mSetIt.hasNext()) {
Object tempM = mSetIt.next();
if (!mOld.contains(tempM)) {
if (!unitToM.containsKey(tempM)) {
// System.out.println("unitToM does not contain: "+tempM);
} else {
FlowSet mSetMSym = unitToM.get(tempM);
if (!(mSetMSym.size() == 0)) {
if (!mSetMSym.contains(currentObj)) {
mSetMSym.add(currentObj);
/*
* Tag tag1 = (Tag)((JPegStmt)tempM).getTags().get(0); System.out.println("add "+tag+" "+currentNode
* +"to the mset of "+tag1+" "+tempM); testSet((FlowSet)unitToM.get(tempM), "mset of "+tag1+" "+tempM);
*/
}
} else {
mSetMSym.add(currentObj);
}
/*
* ADD ======== FlowSet mSetMSym=null; if (unitToMSym.containsKey(tempM)){ mSetMSym =
* (FlowSet)unitToMSym.get(tempM);
*
* } else{ mSetMSym = new ArraySparseSet(); } if (!mSetMSym.contains(currentObj)){
*
* mSetMSym.add(currentObj);
*
* //Tag tag1 = (Tag)tempM.getTags().get(0); //System.out.println("add "+currentObj
* +"to the mset of "+tempM); } else{ //System.out.println("the mset of "+tempM+" contains "+currentNode); }
* unitToMSym.put(tempM, mSetMSym);
*/
}
}
/*
* add m to the worklist because the change in M(m) may lead to a change in OUT(m)
*/
if (!workList.contains(tempM)) {
workList.addLast(tempM);
}
// System.out.println("add in symmetry"+tempM+"to worklist");
}
} // System.out.println("======end symmetry====");
// end do the symmetry step for all new nodes in M(n)
/*
* if new nodes has been addedd to the OUT set of n, add n's successors to the worklist
*/
if (!outOld.equals(outSet)) {
// compute LocalSucc(n)
Iterator localSuccIt = (g.getSuccsOf(currentObj)).iterator();
while (localSuccIt.hasNext()) {
Object localSucc = localSuccIt.next();
// System.out.println("localSucc: "+localSucc);
if (localSucc instanceof JPegStmt) {
if ((JPegStmt) localSucc instanceof NotifiedEntryStmt) {
// if (((JPegStmt)localSucc).getName().equals("notified-entry")){
continue;
}
else if (!workList.contains(localSucc)) {
workList.addLast(localSucc);
// System.out.println("add "+localSucc+"to worklist---local succ");
}
} else {
if (!workList.contains(localSucc)) {
workList.addLast(localSucc);
// System.out.println("add to worklist---local succ");
/*
* Iterator it = ((List)localSucc).iterator(); while (it.hasNext()){ JPegStmt ss = (JPegStmt)it.next(); Tag
* tag1 = (Tag)ss.getTags().get(0); System.out.println(tag1+" "+ss); }
* System.out.println("--------------------");
*/ }
}
}
}
// System.out.println("===========after=============");
// testSet(mSet, "mSet:");
// testSet(genSet, "genSet");
// test("######killSet:",killSet);
// testSet(outSet, "outSet:");
// testWorkList();
// System.out.print("c");
}
// if the current node is JPegStmt
else {
JPegStmt currentNode = (JPegStmt) currentObj;
Tag tag = (Tag) currentNode.getTags().get(0);
if (currentNode instanceof NotifyStmt || currentNode instanceof NotifyAllStmt) {
// if (currentNode.getName().equals("notify") ||currentNode.getName().equals("notifyAll") ){
Map<String, FlowSet> waitingNodes = g.getWaitingNodes();
if (waitingNodes.containsKey(currentNode.getObject())) {
FlowSet waitingNodeSet = waitingNodes.get(currentNode.getObject());
// test("waitingNodeSet",waitingNodeSet);
Iterator waitingNodesIt = waitingNodeSet.iterator();
while (waitingNodesIt.hasNext()) {
JPegStmt tempNode = (JPegStmt) waitingNodesIt.next();
// test("mSet",mSet);
// System.out.println("tempNode: "+tempNode);
if (mOld.contains(tempNode)) {
// System.out.println("mSet contains waiting node");
List waitingSuccList = g.getSuccsOf(tempNode);
Iterator waitingSuccIt = waitingSuccList.iterator();
while (waitingSuccIt.hasNext()) {
JPegStmt waitingSucc = (JPegStmt) waitingSuccIt.next();
notifySuccSet.add(waitingSucc);
if (waitingSucc instanceof NotifiedEntryStmt) {
// build notifySucc Map
FlowSet notifySet = notifySucc.get(currentNode);
notifySet.add(waitingSucc);
notifySucc.put(currentNode, notifySet);
// end build notifySucc Map
// build notifyPred Map
// Apr 12 Fix bug notifyPredSet.add(waitingSucc)->Pred.get(waitingSucc);
if (notifyPred.containsKey(waitingSucc)) {
Set<JPegStmt> notifyPredSet = notifyPred.get(waitingSucc);
notifyPredSet.add(currentNode);
notifyPred.put(waitingSucc, notifyPredSet);
} else {
Set<JPegStmt> notifyPredSet = new HashSet<JPegStmt>();
notifyPredSet.add(currentNode);
// notifyPredSet.add(waitingSucc);
notifyPred.put(waitingSucc, notifyPredSet);
}
// end modify April 12
// end build notifyPred Map
// testMap(notifyPred,"notifyPred of: "+waitingSucc);
}
}
}
}
} else {
// System.out.println("waitingNodes "+waitingNodes);
throw new RuntimeException("Fail to find waiting node for: " + currentObj);
}
} // end if notifynodes
// testNotifySucc();
/*
* if new notify edges were added from this node, add all notify successors of this node to the worklist
*/
if (!notifySuccSetOld.equals(notifySuccSet)) {
Iterator notifySuccIt = notifySuccSet.iterator();
while (notifySuccIt.hasNext()) {
Object notifySuccNode = notifySuccIt.next();
if (!workList.contains(notifySuccNode)) {
workList.addLast(notifySuccNode);
}
// System.out.println("add"+notifySuccNode+"to worklist");
}
}
// compute GENnotifyAll(n) for (obj, notified-entry,*)
// if (currentNode.getName().equals("notified-entry")){
if (currentNode instanceof NotifiedEntryStmt) {
Iterator waitingPredIt = (g.getPredsOf(currentNode)).iterator();
while (waitingPredIt.hasNext()) {
waitingPred = (JPegStmt) waitingPredIt.next();
if ((waitingPred instanceof WaitingStmt) && waitingPred.getObject().equals(currentNode.getObject())
&& waitingPred.getCaller().equals(currentNode.getCaller())) {
break;
}
} // end while
/*
* compute the notified-entry set for "obj" in (obj, notified-entry, *) because notified-entry nodes always follow
* the corresponding waiting nodes, we can find waitingNodes for obj, then find the notified-entry nodes.
*/
Map<String, FlowSet> waitingNodes = g.getWaitingNodes();
FlowSet notifyEntrySet = new ArraySparseSet();
if (waitingNodes.containsKey(currentNode.getObject())) {
FlowSet waitingNodesSet = waitingNodes.get(currentNode.getObject());
Iterator waitingNodesIt = waitingNodesSet.iterator();
while (waitingNodesIt.hasNext()) {
List waitingNodesSucc = g.getSuccsOf(waitingNodesIt.next());
Iterator waitingNodesSuccIt = waitingNodesSucc.iterator();
while (waitingNodesSuccIt.hasNext()) {
JPegStmt notifyEntry = (JPegStmt) waitingNodesSuccIt.next();
if (notifyEntry instanceof NotifiedEntryStmt) {
notifyEntrySet.add(notifyEntry);
}
}
}
}
/*
* compute the m set for WaitingPred(notifyEntry node)
*/
Iterator notifyEntrySetIt = notifyEntrySet.iterator();
while (notifyEntrySetIt.hasNext()) {
JPegStmt notifyEntry = (JPegStmt) notifyEntrySetIt.next();
Iterator waitingPredIterator = (g.getPredsOf(notifyEntry)).iterator();
JPegStmt waitingPredNode = null;
// find the WaitingPred(notified-entry node)
while (waitingPredIterator.hasNext()) {
waitingPredNode = (JPegStmt) waitingPredIterator.next();
if ((waitingPredNode instanceof WaitingStmt) && waitingPredNode.getObject().equals(currentNode.getObject())
&& waitingPredNode.getCaller().equals(currentNode.getCaller())) {
break;
}
}
if (!unitToM.containsKey(waitingPredNode)) {
} else {
FlowSet mWaitingPredM = unitToM.get(waitingPredNode);
if (mWaitingPredM.contains(waitingPred)) {
// get r: r is (obj,notifyAll,*)
Map<String, Set<JPegStmt>> notifyAll = g.getNotifyAll();
if (notifyAll.containsKey(currentNode.getObject())) {
Set notifyAllSet = notifyAll.get(currentNode.getObject());
Iterator notifyAllIt = notifyAllSet.iterator();
while (notifyAllIt.hasNext()) {
JPegStmt notifyAllStmt = (JPegStmt) notifyAllIt.next();
if (unitToM.containsKey(waitingPred)) {
FlowSet mWaitingPredN = unitToM.get(waitingPred);
if (mWaitingPredM.contains(notifyAllStmt) && mWaitingPredN.contains(notifyAllStmt)) {
genNotifyAllSet.add(notifyEntry);
}
}
}
}
}
}
}
} // end compute GENnotifyAll(n)
// compute M(n) set
FlowSet notifyPredUnion = new ArraySparseSet();
if (currentNode instanceof NotifiedEntryStmt) {
// System.out.println("===notified-entry stmt== \n"+((JPegStmt)currentNode).getTags().get(0)+" "+currentNode);
if (!unitToOut.containsKey(waitingPred)) {
throw new RuntimeException("unitToOut does not contains " + waitingPred);
} else {
FlowSet mSetOfNotifyEntry = new ArraySparseSet();
// compute the Union of out(NotifyPred(n))
Set notifyPredSet = notifyPred.get(currentNode);
// System.out.println("notifyPredSet: "+notifyPredSet);
if (notifyPredSet == null) {
// System.out.println(currentNode+"has no notifyPredset");
} else {
Iterator notifyPredSetIt = notifyPredSet.iterator();
while (notifyPredSetIt.hasNext()) {
JPegStmt notifyPred = (JPegStmt) notifyPredSetIt.next();
// System.out.println("notifyPred: "+notifyPred.getTags().get(0)+" "+notifyPred);
FlowSet outWaitingPredTemp = unitToOut.get(notifyPred);
// testSet(outWaitingPredTemp, "out of notifyPred");
outWaitingPredTemp.copy(notifyPredUnion);
}
// testSet(notifyPredUnion, "Union of out of notifyPred");
// compute OUT(waitingPred(n)) waitingPred=waitingPred(n)
FlowSet outWaitingPredSet = unitToOut.get(waitingPred);
// testSet(outWaitingPredSet, "out of WaitingPred");
// compute the intersection of (the Union of out(NotifyPred(n)) ) and (OUT(waitingPred(n)))
notifyPredUnion.intersection(outWaitingPredSet, mSetOfNotifyEntry);
// testSet(mSetOfNotifyEntry, "intersection of notify and waiting");
// compute the union of above and GENnotifyAll(n)
// testSet(genNotifyAllSet, "GenNotifyAll(n)");
mSetOfNotifyEntry.union(genNotifyAllSet, mSet);
}
}
} else if (currentNode instanceof BeginStmt) {
// compute StartPred(n)
// modify Feb 6
mSet = new ArraySparseSet();
Map<JPegStmt, List> startToThread = g.getStartToThread();
Set<JPegStmt> keySet = startToThread.keySet();
Iterator<JPegStmt> it = keySet.iterator();
while (it.hasNext()) {
JPegStmt tempStmt = it.next();
Iterator chainListIt = startToThread.get(tempStmt).iterator();
while (chainListIt.hasNext()) {
List beginNodes = ((PegChain) chainListIt.next()).getHeads();
if (beginNodes.contains(currentNode)) {
// compute OUT(p)
Iterator outStartPredIt = unitToOut.get(tempStmt).iterator();
while (outStartPredIt.hasNext()) {
Object startPred = outStartPredIt.next();
// System.out.println("add startPred to mSet: "+startPred);
mSet.add(startPred);
}
}
}
}
// remove N(t) from m set
Iterator iter = startToThread.keySet().iterator();
while (iter.hasNext()) {
JPegStmt tempStmt = (JPegStmt) iter.next();
Iterator chainListIt = startToThread.get(tempStmt).iterator();
while (chainListIt.hasNext()) {
Chain chain = (Chain) chainListIt.next();
if (chain.contains(currentNode)) {
Iterator nodesIt = chain.iterator();
while (nodesIt.hasNext()) {
Object stmt = nodesIt.next();
if (mSet.contains(stmt)) {
mSet.remove(stmt);
}
}
}
}
}
}
else {
// System.out.println("=======entering");
Iterator localPredIt = (g.getPredsOf(currentNode)).iterator();
if (!(currentNode instanceof NotifiedEntryStmt)) {
while (localPredIt.hasNext()) {
Object tempStmt = localPredIt.next();
FlowSet out = unitToOut.get(tempStmt);
// testSet(out,"out of localPred");
if (out != null) {
mSet.union(out);
}
}
}
// testSet(mSet, "mSet");
// System.out.println("after compute mset");
// testSet(mSet, "mSet");
}
// System.out.println("before add msetNew");
// testSet(mSet, "mSet");
/*
* if (mSetNew != null){ Iterator mSetNewIt = mSetNew.iterator(); while(mSetNewIt.hasNext()){ JPegStmt mNew =
* (JPegStmt)mSetNewIt.next(); if(!mSet.contains(mNew)){ mSet.add(mNew); } } }
*/
// else System.out.println("null mSetNew for :"+currentNode);
/*
* modify July 6 2004 if (unitToMSym.containsKey(currentNode)){ FlowSet mSetSym =
* (FlowSet)unitToMSym.get(currentNode); mSet.union(mSetSym); }
*/
mSet.union(mOld);
unitToM.put(currentNode, mSet);
// end compute M(n) set
/*
* compute GEN(n) set for notify and notifyAll nodes GEN(n) = NotifySucc(n)
*/
if (currentNode instanceof NotifyStmt || currentNode instanceof NotifyAllStmt) {
notifySuccSet.copy(genSet);
// test("===notifySuccSet:",notifySuccSet);
unitToGen.put(currentNode, genSet);
}
// end compute GEN(n) set for notify and notifyAll nodes
/*
* compute out set
*/
mSet.union(genSet, outSet);
if (killSet.size() > 0) {
Iterator killIt = killSet.iterator();
while (killIt.hasNext()) {
Object tempStmt = killIt.next();
if (outSet.contains(tempStmt)) {
outSet.remove(tempStmt);
}
}
}
// testSet(outSet, "outSet");
// end compute out set
/*
* do the symmetry step for all new nodes in M(n)
*/
// test("######mSet old:",mOld);
// test("######mSet:",mSet);
// testSet(mOld, "oldMset");
// testSet(mSet, "mSet");
if (!mOld.equals(mSet)) {
// System.out.println("entering mold <> mset");
Iterator mSetIt = mSet.iterator();
while (mSetIt.hasNext()) {
Object tempM = mSetIt.next();
if (!mOld.contains(tempM)) {
if (!unitToM.containsKey(tempM)) {
throw new RuntimeException("unitToM does not contain: " + tempM);
} else {
FlowSet mSetMSym = unitToM.get(tempM);
if (!(mSetMSym.size() == 0)) {
if (!mSetMSym.contains(currentNode)) {
mSetMSym.add(currentNode);
/*
* Tag tag1 = (Tag)((JPegStmt)tempM).getTags().get(0); System.out.println("add "+tag+" "+currentNode
* +"to the mset of "+tag1+" "+tempM); testSet((FlowSet)unitToM.get(tempM), "mset of "+tag1+" "+tempM);
*/
}
} else {
mSetMSym.add(currentNode);
/*
* Tag tag1 = (Tag)((JPegStmt)tempM).getTags().get(0); System.out.println("add "+tag+" "+currentNode
* +"to the mset of "+tag1+" "+tempM); testSet((FlowSet)unitToM.get(tempM), "mset of "+tag1+" "+tempM);
*/
}
/*
* FlowSet mSetMSym=null; if (unitToMSym.containsKey(tempM)){ mSetMSym = (FlowSet)unitToMSym.get(tempM);
*
* } else{ mSetMSym = new ArraySparseSet(); } if (!mSetMSym.contains(currentNode)){
*
* mSetMSym.add(currentNode);
*
* //Tag tag1 = (Tag)tempM.getTags().get(0); //System.out.println("add "+currentNode
* +"to the mset of "+tag1+" "+tempM); } else{
* //System.out.println("the mset of "+tempM+" contains "+currentNode); } unitToMSym.put(tempM, mSetMSym);
*/
}
}
/*
* add m to the worklist because the change in M(m) may lead to a change in OUT(m)
*/
if (!workList.contains(tempM)) {
workList.addLast(tempM);
}
// System.out.println("add"+tempM+"to worklist");
}
}
// end do the symmetry step for all new nodes in M(n)
/*
* if new nodes has been addedd to the OUT set of n, add n's successors to the worklist
*/
if (!outOld.equals(outSet)) {
// compute LocalSucc(n)
Iterator localSuccIt = (g.getSuccsOf(currentNode)).iterator();
while (localSuccIt.hasNext()) {
Object localSucc = localSuccIt.next();
if (localSucc instanceof JPegStmt) {
if ((JPegStmt) localSucc instanceof NotifiedEntryStmt) {
continue;
} else {
if (!workList.contains(localSucc)) {
workList.addLast(localSucc);
}
}
}
else if (!workList.contains(localSucc)) {
workList.addLast(localSucc);
/*
* System.out.println("add to worklist---local succ"); Iterator it = ((List)localSucc).iterator(); while
* (it.hasNext()){ Object obj = it.next(); if (obj instanceof JPegStmt){ JPegStmt ss = (JPegStmt)obj; Tag tag1
* = (Tag)ss.getTags().get(0); System.out.println(tag1+" "+ss); } else System.out.println(obj); }
* System.out.println("--------------------");
*/
}
}
// compute StartSucc(n)
if (currentNode instanceof StartStmt) {
// if (currentNode.getName().equals("start")){
Map<JPegStmt, List> startToThread = g.getStartToThread();
if (!startToThread.containsKey(currentNode)) {
} else {
Iterator it = startToThread.get(currentNode).iterator();
while (it.hasNext()) {
Iterator chainIt = ((Chain) it.next()).iterator();
while (chainIt.hasNext()) {
// JPegStmt tempStmt = (JPegStmt)chainIt.next();
Object tempStmt = chainIt.next();
if (tempStmt instanceof JPegStmt) {
if ((JPegStmt) tempStmt instanceof BeginStmt) {
// if (((JPegStmt)tempStmt).getName().equals("begin")){
if (!workList.contains(tempStmt)) {
workList.addLast(tempStmt);
}
break;
}
}
}
}
}
}
}
// testSet(mSet, "mSet");
// test("######genSet",genSet);
// test("######killSet:",killSet);
// test("######outSet:",outSet);
// testWorkList();
// System.out.print("c");
}
} // end while
}
protected Object entryInitialFlow() {
return new ArraySparseSet();
}
protected Object newInitialFlow() {
return fullSet.clone();
}
// add for debug
protected Map<Object, FlowSet> getUnitToM() {
return unitToM;
}
// end add for debug
private void computeMPairs() {
Set<Set<Object>> mSetPairs = new HashSet<Set<Object>>();
Set maps = unitToM.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object obj = entry.getKey();
FlowSet fs = (FlowSet) entry.getValue();
Iterator it = fs.iterator();
while (it.hasNext()) {
/*
* for test Object a = it.next(); Set s1 = new HashSet(); s1.add(a); s1.add(obj); mSetPairs.add(s1); Set s2 = new
* HashSet(); s2.add(obj); s2.add(a); System.out.println("equals: "+s1.equals(s2));
* System.out.println("contains: "+mSetPairs.contains(s2)); System.exit(1);
*/
Object m = it.next();
Set<Object> pair = new HashSet<Object>();
pair.add(obj);
pair.add(m);
if (!mSetPairs.contains(pair)) {
mSetPairs.add(pair);
}
}
}
System.err.println("Number of pairs: " + mSetPairs.size());
}
private void computeMSet() {
long min = 0;
long max = 0;
long nodes = 0;
long totalNodes = 0;
Set maps = unitToM.entrySet();
boolean first = true;
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object obj = entry.getKey();
FlowSet fs = (FlowSet) entry.getValue();
if (fs.size() > 0) {
totalNodes += fs.size();
nodes++;
if (fs.size() > max) {
max = fs.size();
}
if (first) {
min = fs.size();
first = false;
} else {
if (fs.size() < min) {
min = fs.size();
}
}
}
}
System.err.println("average: " + totalNodes / nodes);
System.err.println("min: " + min);
System.err.println("max: " + max);
}
}
| 36,713
| 35.278656
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/MhpTester.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.thread.AbstractRuntimeThread;
/**
* MhpTester written by Richard L. Halpert 2007-03-15 An interface for any object that can provide May-Happen-in-Parallel
* info and a list of the program's threads (List of AbstractRuntimeThreads)
*/
public interface MhpTester {
public boolean mayHappenInParallel(SootMethod m1, SootMethod m2); // method level MHP
public boolean mayHappenInParallel(SootMethod m1, Unit u1, SootMethod m2, Unit u2); // stmt level MHP
public void printMhpSummary();
public List<AbstractRuntimeThread> getThreads();
}
| 1,503
| 32.422222
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/MhpTransformer.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.Map;
import soot.G;
import soot.SceneTransformer;
import soot.Singletons;
/**
*
*/
public class MhpTransformer extends SceneTransformer {
public MhpTransformer(Singletons.Global g) {
}
public static MhpTransformer v() {
return G.v().soot_jimple_toolkits_thread_mhp_MhpTransformer();
}
MhpTester mhpTester;
protected void internalTransform(String phaseName, Map options) {
getMhpTester().printMhpSummary();
}
public MhpTester getMhpTester() {
if (mhpTester == null) {
mhpTester = new SynchObliviousMhpAnalysis();
}
return mhpTester;
}
public void setMhpTester(MhpTester mhpTester) {
this.mhpTester = mhpTester;
}
}
| 1,554
| 24.491803
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/MonitorAnalysis.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Timers;
import soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.tagkit.Tag;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
//STEP 1: What are we computing?
//SETS OF STMTS INSIDE MONITORS => Use MonitorSet.
//
//STEP 2: Precisely define what we are computing.
//Set of objects inside a monitor reaches a program point.
//
//STEP 3: Decide whether it is a backwards or forwards analysis.
//FORWARDS
//
public class MonitorAnalysis extends ForwardFlowAnalysis {
private static final Logger logger = LoggerFactory.getLogger(MonitorAnalysis.class);
private PegGraph g;
private final HashMap<String, FlowSet> monitor = new HashMap<String, FlowSet>();
private final Vector<Object> nodes = new Vector<Object>();
private final Vector<Object> valueBefore = new Vector<Object>();
private final Vector<Object> valueAfter = new Vector<Object>();
public MonitorAnalysis(PegGraph g) {
super(g);
this.g = g;
doAnalysis();
// computeSynchNodes();
g.setMonitor(monitor);
// testMonitor();
}
protected void doAnalysis() {
LinkedList<Object> changedUnits = new LinkedList<Object>();
HashSet<Object> changedUnitsSet = new HashSet<Object>();
int numNodes = graph.size();
int numComputations = 0;
// Set initial values and nodes to visit.
createWorkList(changedUnits, changedUnitsSet);
// testWorkList(changedUnits);
// Set initial values for entry points
{
Iterator it = graph.getHeads().iterator();
while (it.hasNext()) {
Object s = it.next();
// unitToBeforeFlow.put(s, entryInitialFlow());
nodes.add(s);
valueBefore.add(entryInitialFlow());
}
}
// Perform fixed point flow analysis
{
Object previousAfterFlow = newInitialFlow();
while (!changedUnits.isEmpty()) {
Object beforeFlow;
Object afterFlow;
Object s = changedUnits.removeFirst();
// Tag tag = (Tag)((JPegStmt)s).getTags().get(0);
// System.out.println("===unit is: "+tag+" "+s);
changedUnitsSet.remove(s);
// copy(unitToAfterFlow.get(s), previousAfterFlow);
// add for debug april 6
int pos = nodes.indexOf(s);
copy(valueAfter.elementAt(pos), previousAfterFlow);
// end add for debug april
// Compute and store beforeFlow
{
List preds = graph.getPredsOf(s);
// beforeFlow = unitToBeforeFlow.get(s);
beforeFlow = valueBefore.elementAt(pos);
if (preds.size() == 1) {
// copy(unitToAfterFlow.get(preds.get(0)), beforeFlow);
copy(valueAfter.elementAt(nodes.indexOf(preds.get(0))), beforeFlow);
}
else if (preds.size() != 0) {
Iterator predIt = preds.iterator();
Object obj = predIt.next();
// copy(unitToAfterFlow.get(obj), beforeFlow);
copy(valueAfter.elementAt(nodes.indexOf(obj)), beforeFlow);
while (predIt.hasNext()) {
JPegStmt stmt = (JPegStmt) predIt.next();
if (stmt.equals(obj)) {
// System.out.println("!!!same object!!!");
continue;
}
// Tag tag1 = (Tag)stmt.getTags().get(0);
// System.out.println("pred: "+tag1+" "+stmt);
// Object otherBranchFlow = unitToAfterFlow.get(stmt);
if (nodes.indexOf(stmt) >= 0) // RLH
{
Object otherBranchFlow = valueAfter.elementAt(nodes.indexOf(stmt));
merge(beforeFlow, otherBranchFlow, beforeFlow);
}
}
}
}
// Compute afterFlow and store it.
{
// afterFlow = unitToAfterFlow.get(s);
afterFlow = valueAfter.elementAt(nodes.indexOf(s));
flowThrough(beforeFlow, s, afterFlow);
// unitToAfterFlow.put(s, afterFlow);
valueAfter.set(nodes.indexOf(s), afterFlow);
// System.out.println("update afterFlow nodes: "+s);
// System.out.println("afterFlow: "+afterFlow);
// ((MonitorSet)unitToAfterFlow.get(s)).test();
numComputations++;
}
// Update queue appropriately
if (!afterFlow.equals(previousAfterFlow)) {
Iterator succIt = graph.getSuccsOf(s).iterator();
while (succIt.hasNext()) {
Object succ = succIt.next();
if (!changedUnitsSet.contains(succ)) {
changedUnits.addLast(succ);
changedUnitsSet.add(succ);
/*
* if (succ instanceof JPegStmt){ Tag tag1 = (Tag)((JPegStmt)succ).getTags().get(0);
*
* System.out.println("add to worklist: "+tag1+" "+succ); } else System.out.println("add to worklist: "+succ);
*/
}
}
}
}
}
// logger.debug(""+graph.getBody().getMethod().getSignature() + " numNodes: " + numNodes +
// " numComputations: " + numComputations + " avg: " + Main.truncatedOf((double) numComputations / numNodes, 2));
Timers.v().totalFlowNodes += numNodes;
Timers.v().totalFlowComputations += numComputations;
}
// STEP 4: Is the merge operator union or intersection?
// UNION
protected void merge(Object in1, Object in2, Object out) {
MonitorSet inSet1 = (MonitorSet) in1;
MonitorSet inSet2 = (MonitorSet) in2;
MonitorSet outSet = (MonitorSet) out;
inSet1.intersection(inSet2, outSet);
}
// STEP 5: Define flow equations.
// in(s) = ( out(s) minus defs(s) ) union uses(s)
//
protected void flowThrough(Object inValue, Object unit, Object outValue) {
MonitorSet in = (MonitorSet) inValue;
MonitorSet out = (MonitorSet) outValue;
JPegStmt s = (JPegStmt) unit;
Tag tag = (Tag) s.getTags().get(0);
// System.out.println("s: "+tag+" "+s);
// Copy in to out
// if (in.contains("&")) in.remove("&");
in.copy(out);
// System.out.println("-----in: ");
// in.test();
if (in.size() > 0) {
if (!s.getName().equals("waiting") && !s.getName().equals("notified-entry")) {
updateMonitor(in, unit);
}
}
String objName = s.getObject();
// if (objName == null) throw new RuntimeException("null object: "+s.getUnit());
if (s.getName().equals("entry") || s.getName().equals("exit")) {
if (out.contains("&")) {
out.remove("&");
}
Object obj = out.getMonitorDepth(objName);
if (obj == null) {
if (s.getName().equals("entry")) {
MonitorDepth md = new MonitorDepth(objName, 1);
out.add(md);
// System.out.println("add to out: "+md.getObjName()+" "+md.getDepth());
}
/*
* else{ throw new RuntimeException("The monitor depth can not be decreased at "+
* (Tag)((JPegStmt)s).getTags().get(0)+" "+unit); }
*/
} else {
// System.out.println("obj: "+obj);
if (obj instanceof MonitorDepth) {
MonitorDepth md = (MonitorDepth) obj;
if (s.getName().equals("entry")) {
md.increaseDepth();
// System.out.println("===increase depth===");
} else {
if (md.getDepth() > 1) {
// System.out.println("===decrease depth==");
md.decreaseDepth();
} else if (md.getDepth() == 1) {
// System.out.println("===remove monitordepth: "+md);
out.remove(md);
} else {
throw new RuntimeException("The monitor depth can not be decreased at " + unit);
}
}
} else {
throw new RuntimeException("MonitorSet contains non MonitorDepth element!");
}
}
}
// System.out.println("-----out: "+out);
// out.test();
// testForDebug();
}
/*
* private void testForDebug(){ System.out.println("--------test for debug-------"); int i = 0; for
* (i=0;i<nodes.size();i++){ JPegStmt stmt = (JPegStmt)nodes.elementAt(i); //System.out.println("Tag: "+
* ((Tag)stmt.getTags().get(0)).toString()); if (((Tag)stmt.getTags().get(0)).toString().equals("8")){ int pos =
* nodes.indexOf(stmt); if (((MonitorSet)valueAfter.elementAt(pos)).size() >0 &&
* !((MonitorSet)valueAfter.elementAt(pos)).contains("&")){
* System.out.println("sp"+stmt.getTags().get(0)+" "+nodes.elementAt(pos));
*
* ((MonitorSet)valueAfter.elementAt(pos)).test(); } } } System.out.println("--------test for debug end------"); }
*/
protected void copy(Object source, Object dest) {
MonitorSet sourceSet = (MonitorSet) source;
MonitorSet destSet = (MonitorSet) dest;
sourceSet.copy(destSet);
}
// STEP 6: Determine value for start/end node, and
// initial approximation.
//
// start node: empty set
// initial approximation: empty set
protected Object entryInitialFlow() {
return new MonitorSet();
}
protected Object newInitialFlow() {
MonitorSet fullSet = new MonitorSet();
fullSet.add("&");
return fullSet;
// return fullSet.clone();
}
private void updateMonitor(MonitorSet ms, Object unit) {
// System.out.println("===inside updateMonitor===");
// ml.test();
Iterator it = ms.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof MonitorDepth) {
MonitorDepth md = (MonitorDepth) obj;
String objName = md.getObjName();
if (monitor.containsKey(objName)) {
if (md.getDepth() > 0) {
monitor.get(objName).add(unit);
// System.out.println("add to monitorset "+unit);
}
} else {
FlowSet monitorObjs = new ArraySparseSet();
monitorObjs.add(unit);
monitor.put(objName, monitorObjs);
// System.out.println("put into monitor: "+objName);
}
}
}
}
private void createWorkList(LinkedList<Object> changedUnits, HashSet<Object> changedUnitsSet) {
createWorkList(changedUnits, changedUnitsSet, g.getMainPegChain());
Set maps = g.getStartToThread().entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
List runMethodChainList = (List) entry.getValue();
Iterator it = runMethodChainList.iterator();
while (it.hasNext()) {
PegChain chain = (PegChain) it.next();
createWorkList(changedUnits, changedUnitsSet, chain);
}
}
}
public void computeSynchNodes() {
int num = 0;
Set maps = monitor.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
FlowSet fs = (FlowSet) entry.getValue();
num += fs.size();
}
System.err.println("synch objects: " + num);
}
/*
* private void createWorkList(LinkedList changedUnits, HashSet changedUnitsSet, PegChain chain ){ //breadth first scan
* Iterator it = chain.getHeads().iterator();
*
* while (it.hasNext()) { Object head = it.next(); Set gray = new HashSet(); LinkedList queue = new LinkedList();
* queue.add(head); changedUnits.addLast(head); changedUnitsSet.add(head);
*
* //unitToBeforeFlow.put(head, newInitialFlow()); //unitToAfterFlow.put(head, newInitialFlow()); // add for debug April 6
* nodes.add(head); valueBefore.add(newInitialFlow()); valueAfter.add(newInitialFlow()); // end add for debug April 6
*
* while (queue.size()>0){ Object root = queue.getFirst();
*
* Iterator succsIt = graph.getSuccsOf(root).iterator(); while (succsIt.hasNext()){ Object succ = succsIt.next(); if
* (!gray.contains(succ)){ gray.add(succ); queue.addLast(succ); changedUnits.addLast(succ); changedUnitsSet.add(succ);
*
* // unitToBeforeFlow.put(succ, newInitialFlow()); //unitToAfterFlow.put(succ, newInitialFlow()); // add for debug April 6
* nodes.add(succ); valueBefore.add(newInitialFlow()); valueAfter.add(newInitialFlow()); // end add for debug April 6
*
* } } queue.remove(root); } }
*
* }
*/
private void createWorkList(LinkedList<Object> changedUnits, HashSet<Object> changedUnitsSet, PegChain chain) {
// Depth first scan
Iterator it = chain.getHeads().iterator();
Set<Object> gray = new HashSet<Object>();
while (it.hasNext()) {
Object head = it.next();
if (!gray.contains(head)) {
visitNode(gray, head, changedUnits, changedUnitsSet);
}
}
}
private void visitNode(Set<Object> gray, Object obj, LinkedList<Object> changedUnits, HashSet<Object> changedUnitsSet) {
gray.add(obj);
changedUnits.addLast(obj);
changedUnitsSet.add(obj);
nodes.add(obj);
valueBefore.add(newInitialFlow());
valueAfter.add(newInitialFlow());
Iterator succsIt = graph.getSuccsOf(obj).iterator();
if (g.getSuccsOf(obj).size() > 0) {
while (succsIt.hasNext()) {
Object succ = succsIt.next();
if (!gray.contains(succ)) {
visitNode(gray, succ, changedUnits, changedUnitsSet);
}
}
}
}
public Map<String, FlowSet> getMonitor() {
return monitor;
}
public void testMonitor() {
System.out.println("=====test monitor size: " + monitor.size());
Set maps = monitor.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
System.out.println("---key= " + key);
FlowSet list = (FlowSet) entry.getValue();
if (list.size() > 0) {
System.out.println("**set: " + list.size());
Iterator it = list.iterator();
while (it.hasNext()) {
JPegStmt stmt = (JPegStmt) it.next();
Tag tag1 = (Tag) stmt.getTags().get(0);
System.out.println(tag1 + " " + stmt);
}
}
}
System.out.println("=========monitor--ends--------");
}
}
| 15,568
| 31.776842
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/MonitorDepth.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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%
*/
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class MonitorDepth {
private String objName;
private int depth;
MonitorDepth(String s, int d) {
objName = s;
depth = d;
}
protected String getObjName() {
return objName;
}
protected void SetObjName(String s) {
objName = s;
}
protected int getDepth() {
return depth;
}
protected void setDepth(int d) {
depth = d;
}
protected void decreaseDepth() {
if (depth > 0) {
depth = depth - 1;
} else {
throw new RuntimeException("Error! You can not decrease a monitor depth of " + depth);
}
}
protected void increaseDepth() {
depth++;
}
}
| 1,941
| 25.243243
| 92
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/MonitorSet.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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 soot.toolkits.scalar.ArraySparseSet;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class MonitorSet extends ArraySparseSet {
// int size = 0;
MonitorSet() {
super();
}
public Object getMonitorDepth(String objName) {
Iterator<?> it = iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof MonitorDepth) {
MonitorDepth md = (MonitorDepth) obj;
if (md.getObjName().equals(objName)) {
return md;
}
}
}
return null;
}
public MonitorSet clone() {
MonitorSet newSet = new MonitorSet();
newSet.union(this);
return newSet;
}
/*
* public void copy(MonitorSet dest){ System.out.println("====begin copy"); dest.clear(); Iterator iterator = iterator();
* while (iterator.hasNext()){ Object obj = iterator.next(); if (obj instanceof MonitorDepth) {
* System.out.println("obj: "+((MonitorDepth)obj).getObjName());
* System.out.println("depth: "+((MonitorDepth)obj).getDepth()); } else System.out.println("obj: "+obj); if
* (!dest.contains(obj)) dest.add(obj); else System.out.println("dest contains "+obj); }
* System.out.println("===finish copy==="); }
*/
/**
* Returns the union (join) of this MonitorSet and <code>other</code>, putting result into <code>this</code>.
*/
public void union(MonitorSet other) {
}
/**
* Returns the union (join) of this MonitorSet and <code>other</code>, putting result into <code>dest</code>.
* <code>dest</code>, <code>other</code> and <code>this</code> could be the same object.
*/
/*
* ublic void union(MonitorSet other, MonitorSet dest){ other.copy(dest); Iterator iterator = iterator(); while
* (iterator.hasNext()){
*
* MonitorDepth md = (MonitorDepth)iterator.next(); Object obj = dest.getMonitorDepth(md.getObjName()); if ( obj == null){
* dest.add(md); } else{ if (obj instanceof MonitorDepth){ if (md.getDepth() != ((MonitorDepth)obj).getDepth()) throw new
* RuntimeException("Find different monitor depth at merge point!");
*
* } else throw new RuntimeException("MonitorSet contains non MonitorDepth element!"); }
*
* }
*
* }
*/
public void intersection(MonitorSet other, MonitorSet dest) {
/*
* System.out.println("this:"); this.test(); System.out.println("other:"); other.test();
*/
if (other.contains("&")) {
this.copy(dest);
// System.out.println("copy this to dest: ");
// dest.test();
} else if (this.contains("&")) {
other.copy(dest);
// System.out.println("copy other to dest: ");
// dest.test();
} else {
Iterator<?> it = iterator();
while (it.hasNext()) {
Object o = it.next();
if (o instanceof MonitorDepth) {
MonitorDepth md = (MonitorDepth) o;
Object obj = dest.getMonitorDepth(md.getObjName());
if (obj != null) {
if (md.getDepth() != ((MonitorDepth) obj).getDepth()) {
throw new RuntimeException("stmt inside different monitor depth !");
} else {
dest.add(obj);
}
}
}
}
}
}
public void test() {
System.out.println("====MonitorSet===");
Iterator<?> it = iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof MonitorDepth) {
MonitorDepth md = (MonitorDepth) obj;
;
System.out.println("obj: " + md.getObjName());
System.out.println("depth: " + md.getDepth());
} else {
System.out.println(obj);
}
}
System.out.println("====MonitorSet end====");
}
}
| 4,948
| 31.136364
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/PegCallGraphToDot.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Sable Research Group
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.toolkits.graph.DirectedGraph;
import soot.util.dot.DotGraph;
import soot.util.dot.DotGraphConstants;
import soot.util.dot.DotGraphNode;
//import soot.toolkits.mhp.*;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class PegCallGraphToDot {
/*
* make all control fields public, allow other soot class dump the graph in the middle
*/
public static boolean isBrief = false;
private static final Map<Object, String> listNodeName = new HashMap<Object, String>();
/* in one page or several pages of 8.5x11 */
public static boolean onepage = true;
public PegCallGraphToDot(DirectedGraph graph, boolean onepage, String name) {
PegCallGraphToDot.onepage = onepage;
toDotFile(name, graph, "PegCallGraph");
}
/*
* public PegToDotFile(PegGraph graph, boolean onepage, String name) { this.onepage = onepage; toDotFile(name,
* graph,"Simple graph"); }
*/
private static int nodecount = 0;
/**
* Generates a dot format file for a DirectedGraph
*
* @param methodname,
* the name of generated dot file
* @param graph,
* a directed control flow graph (UnitGraph, BlockGraph ...)
* @param graphname,
* the title of the graph
*/
public static void toDotFile(String methodname, DirectedGraph graph, String graphname) {
int sequence = 0;
// this makes the node name unique
nodecount = 0; // reset node counter first.
Hashtable nodeindex = new Hashtable(graph.size());
// file name is the method name + .dot
DotGraph canvas = new DotGraph(methodname);
// System.out.println("onepage is:"+onepage);
if (!onepage) {
canvas.setPageSize(8.5, 11.0);
}
canvas.setNodeShape(DotGraphConstants.NODE_SHAPE_BOX);
canvas.setGraphLabel(graphname);
Iterator nodesIt = graph.iterator();
{
while (nodesIt.hasNext()) {
Object node = nodesIt.next();
if (node instanceof List) {
String listName = "list" + (new Integer(sequence++)).toString();
String nodeName = makeNodeName(getNodeOrder(nodeindex, listName));
listNodeName.put(node, listName);
// System.out.println("put node: "+node +"into listNodeName");
}
}
}
nodesIt = graph.iterator();
while (nodesIt.hasNext()) {
Object node = nodesIt.next();
String nodeName = null;
if (node instanceof List) {
nodeName = makeNodeName(getNodeOrder(nodeindex, listNodeName.get(node)));
} else {
nodeName = makeNodeName(getNodeOrder(nodeindex, node));
}
Iterator succsIt = graph.getSuccsOf(node).iterator();
while (succsIt.hasNext()) {
Object s = succsIt.next();
String succName = null;
if (s instanceof List) {
succName = makeNodeName(getNodeOrder(nodeindex, listNodeName.get(s)));
} else {
Object succ = s;
// System.out.println("$$$$$$succ: "+succ);
// nodeName = makeNodeName(getNodeOrder(nodeindex, tag+" "+node));
succName = makeNodeName(getNodeOrder(nodeindex, succ));
// System.out.println("node is :" +node);
// System.out.println("find start node in pegtodotfile:"+node);
}
canvas.drawEdge(nodeName, succName);
}
}
// set node label
if (!isBrief) {
nodesIt = nodeindex.keySet().iterator();
while (nodesIt.hasNext()) {
Object node = nodesIt.next();
// System.out.println("node is:"+node);
if (node != null) {
// System.out.println("node: "+node);
String nodename = makeNodeName(getNodeOrder(nodeindex, node));
// System.out.println("nodename: "+ nodename);
DotGraphNode dotnode = canvas.getNode(nodename);
// System.out.println("dotnode: "+dotnode);
if (dotnode != null) {
dotnode.setLabel(node.toString());
}
}
}
}
canvas.plot("pecg.dot");
// clean up
listNodeName.clear();
}
private static int getNodeOrder(Hashtable<Object, Integer> nodeindex, Object node) {
Integer index = nodeindex.get(node);
if (index == null) {
index = new Integer(nodecount++);
nodeindex.put(node, index);
}
// System.out.println("order is:"+index.intValue());
return index.intValue();
}
private static String makeNodeName(int index) {
return "N" + index;
}
}
| 5,802
| 29.703704
| 112
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/PegChain.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Hierarchy;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.RefType;
import soot.SootClass;
import soot.SootMethod;
import soot.Trap;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.MonitorStmt;
import soot.jimple.NewExpr;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.internal.JIdentityStmt;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.thread.mhp.stmt.BeginStmt;
import soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.jimple.toolkits.thread.mhp.stmt.JoinStmt;
import soot.jimple.toolkits.thread.mhp.stmt.MonitorEntryStmt;
import soot.jimple.toolkits.thread.mhp.stmt.MonitorExitStmt;
import soot.jimple.toolkits.thread.mhp.stmt.NotifiedEntryStmt;
import soot.jimple.toolkits.thread.mhp.stmt.NotifyAllStmt;
import soot.jimple.toolkits.thread.mhp.stmt.NotifyStmt;
import soot.jimple.toolkits.thread.mhp.stmt.OtherStmt;
import soot.jimple.toolkits.thread.mhp.stmt.StartStmt;
import soot.jimple.toolkits.thread.mhp.stmt.WaitStmt;
import soot.jimple.toolkits.thread.mhp.stmt.WaitingStmt;
import soot.tagkit.StringTag;
import soot.toolkits.graph.CompleteUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.util.Chain;
import soot.util.HashChain;
//add for add tag
//import soot.util.cfgcmd.*;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
// NOTE that this graph builder will only run to completion if all virtual
// method calls can be resolved to a single target method. This is a severely
// limiting caveat.
public class PegChain extends HashChain {
CallGraph callGraph;
private final List heads = new ArrayList();
private final List tails = new ArrayList();
private final FlowSet pegNodes = new ArraySparseSet();
private final Map<Unit, JPegStmt> unitToPeg = new HashMap<Unit, JPegStmt>();
private final Map<String, FlowSet> waitingNodes;
private final PegGraph pg;
private final Set<List<Object>> joinNeedReconsidered = new HashSet<List<Object>>();
public Body body; // body from which this peg chain was created
// private Map startToThread;
Hierarchy hierarchy;
PAG pag;
Set threadAllocSites;
Set methodsNeedingInlining;
Set allocNodes;
List<List> inlineSites;
Map<SootMethod, String> synchObj;
Set multiRunAllocNodes;
Map<AllocNode, String> allocNodeToObj;
PegChain(CallGraph callGraph, Hierarchy hierarchy, PAG pag, Set threadAllocSites, Set methodsNeedingInlining,
Set allocNodes, List<List> inlineSites, Map<SootMethod, String> synchObj, Set multiRunAllocNodes,
Map<AllocNode, String> allocNodeToObj, Body unitBody, SootMethod sm, String threadName, boolean addBeginNode,
PegGraph pegGraph) {
this.allocNodeToObj = allocNodeToObj;
this.multiRunAllocNodes = multiRunAllocNodes;
this.synchObj = synchObj;
this.inlineSites = inlineSites;
this.allocNodes = allocNodes;
this.methodsNeedingInlining = methodsNeedingInlining;
this.threadAllocSites = threadAllocSites;
this.hierarchy = hierarchy;
this.pag = pag;
this.callGraph = callGraph;
body = unitBody;
pg = pegGraph;
waitingNodes = pegGraph.getWaitingNodes();
// Find exception handlers
Iterator trapIt = unitBody.getTraps().iterator();
Set<Unit> exceHandlers = pg.getExceHandlers();
while (trapIt.hasNext()) {
Trap trap = (Trap) trapIt.next();
Unit handlerUnit = trap.getHandlerUnit();
exceHandlers.add(handlerUnit);
}
// System.out.println("entering buildPegChain");
UnitGraph graph = new CompleteUnitGraph(unitBody);
Iterator unitIt = graph.iterator();
// HashMap unitToPeg = new HashMap((graph.size())*2+1,0.7f);
// June 19 add begin node
if (addBeginNode) {
// create PEG begin statement
JPegStmt beginStmt = new BeginStmt("*", threadName, graph, sm);
pg.getCanNotBeCompacted().add(beginStmt);
addNode(beginStmt);
heads.add(beginStmt);
}
// end June 19 add begin node
Iterator it = graph.getHeads().iterator();
while (it.hasNext()) {
Object head = it.next();
// breadth first scan
Set<Unit> gray = new HashSet<Unit>();
LinkedList<Object> queue = new LinkedList<Object>();
queue.add(head);
visit((Unit) queue.getFirst(), graph, sm, threadName, addBeginNode);
while (queue.size() > 0) {
Unit root = (Unit) queue.getFirst();
Iterator succsIt = graph.getSuccsOf(root).iterator();
while (succsIt.hasNext()) {
Unit succ = (Unit) succsIt.next();
if (!gray.contains(succ)) {
gray.add(succ);
queue.addLast(succ);
visit(succ, graph, sm, threadName, addBeginNode);
}
}
queue.remove(root);
}
}
postHandleJoinStmt();
pg.getUnitToPegMap().put(this, unitToPeg);
}
private void visit(Unit unit, UnitGraph graph, SootMethod sm, String threadName, boolean addBeginNode) {
/*
* if (unit instanceof JIdentityStmt){ System.out.println("JIdentityStmt left: "+((JIdentityStmt)unit).getLeftOp());
* System.out.println("JIdentityStmt right: "+((JIdentityStmt)unit).getRightOp()); }
*/
// System.out.println("unit: "+unit);
if (unit instanceof MonitorStmt) {
Value value = ((MonitorStmt) unit).getOp();
if (value instanceof Local) {
Type type = ((Local) value).getType();
if (type instanceof RefType) {
SootClass sc = ((RefType) type).getSootClass();
if (unit instanceof EnterMonitorStmt) {
String objName = makeObjName(value, type, unit);
JPegStmt pegStmt = new MonitorEntryStmt(objName, threadName, unit, graph, sm);
addAndPutNonCompacted(unit, pegStmt);
return;
}
if (unit instanceof ExitMonitorStmt) {
String objName = makeObjName(value, type, unit);
JPegStmt pegStmt = new MonitorExitStmt(objName, threadName, unit, graph, sm);
addAndPutNonCompacted(unit, pegStmt);
return;
}
} // end if RefType
} // end if Local
} // end if MonitorStmt
if (((Stmt) unit).containsInvokeExpr()) {
Value invokeExpr = ((Stmt) unit).getInvokeExpr();
SootMethod method = ((InvokeExpr) invokeExpr).getMethod();
String name = method.getName();
Value value = null;
Type type = null;
List paras = method.getParameterTypes();
String objName = null;
if (invokeExpr instanceof InstanceInvokeExpr) {
value = ((InstanceInvokeExpr) invokeExpr).getBase();
if (value instanceof Local) {
// Type type = ((Local)value).getType();
type = ((Local) value).getType();
if (type instanceof RefType) {
SootClass sc = ((RefType) type).getSootClass();
// sc = ((RefType)type).getSootClass();
objName = sc.getName();
}
}
} else {
if (!(invokeExpr instanceof StaticInvokeExpr)) {
throw new RuntimeException("Error: new type of invokeExpre: " + invokeExpr);
} else {
// static invoke
}
}
// Check if a method belongs to a thread.
boolean find = false;
if (method.getName().equals("start")) {
// System.out.println("Test method is: "+method);
// System.out.println("DeclaringClass: "+method.getDeclaringClass());
List<SootClass> superClasses = hierarchy.getSuperclassesOfIncluding(method.getDeclaringClass());
Iterator<SootClass> it = superClasses.iterator();
while (it.hasNext()) {
String className = it.next().getName();
if (className.equals("java.lang.Thread")) {
find = true;
break;
}
}
}
if (method.getName().equals("run")) {
// System.out.println("method name: "+method.getName());
// System.out.println("DeclaringClass name: "+method.getDeclaringClass().getName());
if ((method.getDeclaringClass().getName()).equals("java.lang.Runnable")) {
// System.out.println("find: "+find);
find = true;
}
}
if (name.equals("wait") && (paras.size() == 0 || (paras.size() == 1 && (Type) paras.get(0) instanceof LongType)
|| (paras.size() == 2 && (Type) paras.get(0) instanceof LongType && (Type) paras.get(1) instanceof IntType))) {
/*
* special modeling for wait() method call which transforms wait() node to 3 node.
*/
objName = makeObjName(value, type, unit);
transformWaitNode(objName, name, threadName, unit, graph, sm);
}
else {
if ((name.equals("start") || name.equals("run")) && find) {
// System.out.println("DeclaringClass: "+method.getDeclaringClass().getName());
// System.out.println("====start method: "+method);
// System.out.println("unit: "+unit);
List<AllocNode> mayAlias = null;
PointsToSetInternal pts = (PointsToSetInternal) pag.reachingObjects((Local) value);
mayAlias = findMayAlias(pts, unit);
JPegStmt pegStmt = new StartStmt(value.toString(), threadName, unit, graph, sm);
if (pg.getStartToThread().containsKey(pegStmt)) {
throw new RuntimeException("map startToThread contain duplicated start() method call");
}
pg.getCanNotBeCompacted().add(pegStmt);
addAndPut(unit, pegStmt);
List<PegChain> runMethodChainList = new ArrayList<PegChain>();
List<AllocNode> threadAllocNodesList = new ArrayList<AllocNode>();
// add Feb 01
if (mayAlias.size() < 1) {
throw new RuntimeException("The may alias set of " + unit + "is empty!");
}
Iterator<AllocNode> mayAliasIt = mayAlias.iterator();
// System.out.println("mayAlias: "+mayAlias);
while (mayAliasIt.hasNext()) {
AllocNode allocNode = mayAliasIt.next();
// System.out.println("allocNode toString: "+allocNode.toString());
RefType refType = ((NewExpr) allocNode.getNewExpr()).getBaseType();
SootClass maySootClass = refType.getSootClass();
// remeber to modify here!!! getMethodByName is unsafe!
// if (method.getDeclaringClass()
/*
* TargetMethodsFinder tmd = new TargetMethodsFinder(); List targetList = tmd.find(unit, callGraph, false);
* SootMethod meth=null; if (targetList.size()>1) { System.out.println("targetList: "+targetList); throw new
* RuntimeException("target of start >1!"); } else meth = (SootMethod)targetList.get(0);
*/
SootMethod meth
= hierarchy.resolveConcreteDispatch(maySootClass, method.getDeclaringClass().getMethodByName("run"));
// System.out.println("==method is: "+meth);
Body mBody = meth.getActiveBody();
// Feb 2 modify thread name
int threadNo = Counter.getThreadNo();
String callerName = "thread" + threadNo;
// System.out.println("Adding thread start point: " + "thread" + threadNo + " pegStmt: " + pegStmt);
// map caller ()-> start pegStmt
pg.getThreadNameToStart().put(callerName, pegStmt);
PegChain newChain = new PegChain(callGraph, hierarchy, pag, threadAllocSites, methodsNeedingInlining, allocNodes,
inlineSites, synchObj, multiRunAllocNodes, allocNodeToObj, mBody, sm, callerName, true, pg);
pg.getAllocNodeToThread().put(allocNode, newChain);
runMethodChainList.add(newChain);
threadAllocNodesList.add(allocNode);
}
// end add Feb 01
// System.out.println("Adding something to startToThread");
pg.getStartToThread().put(pegStmt, runMethodChainList);
pg.getStartToAllocNodes().put(pegStmt, threadAllocNodesList);
} // end if (name.equals("start") )
else {
if (name.equals("join") && method.getDeclaringClass().getName().equals("java.lang.Thread")) {
// If the may-alias of "join" has more that one elements, we can NOT kill anything.
PointsToSetInternal pts = (PointsToSetInternal) pag.reachingObjects((Local) value);
// System.out.println("pts: "+pts);
List<AllocNode> mayAlias = findMayAlias(pts, unit);
// System.out.println("=====mayAlias for thread: "+unit +" is:\n"+mayAlias);
if (mayAlias.size() != 1) {
if (mayAlias.size() < 1) {
// System.out.println("===points to set: "+pts);
// System.out.println("the size of mayAlias <0 : \n"+mayAlias);
throw new RuntimeException("==threadAllocaSits==\n" + threadAllocSites.toString());
}
JPegStmt pegStmt = new JoinStmt(value.toString(), threadName, unit, graph, sm);
addAndPutNonCompacted(unit, pegStmt);
pg.getSpecialJoin().add(pegStmt);
} else {
Iterator<AllocNode> mayAliasIt = mayAlias.iterator();
while (mayAliasIt.hasNext()) {
AllocNode allocNode = mayAliasIt.next();
// System.out.println("allocNode toString: "+allocNode.toString());
JPegStmt pegStmt = new JoinStmt(value.toString(), threadName, unit, graph, sm);
if (!pg.getAllocNodeToThread().containsKey(allocNode)) {
List<Object> list = new ArrayList<Object>();
list.add(pegStmt);
list.add(allocNode);
list.add(unit);
joinNeedReconsidered.add(list);
// throw new RuntimeException("allocNodeToThread does not contains key: "+allocNode);
} else {
// If the mayAlias contains one 1 element, then use the threadName as
// the Obj of the JPegStmt.
// String callerName = (String)allocNodeToCaller.get(allocNode);
Chain thread = pg.getAllocNodeToThread().get(allocNode);
addAndPutNonCompacted(unit, pegStmt);
pg.getJoinStmtToThread().put(pegStmt, thread);
}
}
}
} else {
// June 17 add for build obj->notifiyAll map.
if (name.equals("notifyAll") && paras.size() == 0) {
objName = makeObjName(value, type, unit);
JPegStmt pegStmt = new NotifyAllStmt(objName, threadName, unit, graph, sm);
addAndPutNonCompacted(unit, pegStmt);
// build notifyAll Map
if (pg.getNotifyAll().containsKey(objName)) {
Set<JPegStmt> notifyAllSet = pg.getNotifyAll().get(objName);
notifyAllSet.add(pegStmt);
pg.getNotifyAll().put(objName, notifyAllSet);
} else {
Set<JPegStmt> notifyAllSet = new HashSet<JPegStmt>();
notifyAllSet.add(pegStmt);
pg.getNotifyAll().put(objName, notifyAllSet);
}
// end build notifyAll Map
} else {
// add Oct 8, for building pegs with inliner.
if (name.equals("notify") && paras.size() == 0
&& method.getDeclaringClass().getName().equals("java.lang.Thread")) {
objName = makeObjName(value, type, unit);
JPegStmt pegStmt = new NotifyStmt(objName, threadName, unit, graph, sm);
addAndPutNonCompacted(unit, pegStmt);
}
else {
// //System.out.println("******method before extend: "+method);
// System.out.println("isConcretemethod: "+method.isConcrete());
// System.out.println("isLibraryClass: "+method.getDeclaringClass().isLibraryClass());
if (method.isConcrete() && !method.getDeclaringClass().isLibraryClass()) {
List<SootMethod> targetList = new LinkedList<SootMethod>();
SootMethod targetMethod = null;
if (invokeExpr instanceof StaticInvokeExpr) {
targetMethod = method;
} else {
TargetMethodsFinder tmd = new TargetMethodsFinder();
targetList = tmd.find(unit, callGraph, true, false);
if (targetList.size() > 1) {
System.out.println("target: " + targetList);
System.out.println("unit is: " + unit);
System.err.println("exit because target is bigger than 1.");
System.exit(1); // What SHOULD be done is that all possible targets are inlined
// as though each method body is in a big switch on the type of
// the receiver object. The infrastructure to do this is not
// currently available, so instead we exit. Continuing would
// yield wrong answers.
} else if (targetList.size() < 1) {
System.err.println("targetList size <1");
// System.exit(1);
// continue;
} else {
targetMethod = targetList.get(0);
}
}
if (methodsNeedingInlining == null) {
System.err.println("methodsNeedingInlining is null at " + unit);
} else if (targetMethod == null) {
System.err.println("targetMethod is null at " + unit);
} else if (methodsNeedingInlining.contains(targetMethod)) {
inlineMethod(targetMethod, objName, name, threadName, unit, graph, sm);
} else {
JPegStmt pegStmt = new OtherStmt(objName, name, threadName, unit, graph, sm);
addAndPut(unit, pegStmt);
}
}
else {
JPegStmt pegStmt = new OtherStmt(objName, name, threadName, unit, graph, sm);
addAndPut(unit, pegStmt);
}
}
// end add Oct 8, for building pegs with inliner.
}
}
}
} // end else if ("wait")
} // end if containsInvokeExpr()
else {
newAndAddElement(unit, graph, threadName, sm);
}
}
// end buildPegChain()
private void transformWaitNode(String objName, String name, String threadName, Unit unit, UnitGraph graph, SootMethod sm) {
JPegStmt pegStmt = new WaitStmt(objName, threadName, unit, graph, sm);
addAndPutNonCompacted(unit, pegStmt);
JPegStmt pegWaiting = new WaitingStmt(objName, threadName, sm);
pg.getCanNotBeCompacted().add(pegWaiting);
addNode(pegWaiting);
// build waitingNodesMap
if (waitingNodes.containsKey(objName)) {
FlowSet waitingNodesSet = waitingNodes.get(objName);
if (!waitingNodesSet.contains(pegWaiting)) {
waitingNodesSet.add(pegWaiting);
waitingNodes.put(pegWaiting.getObject(), waitingNodesSet);
// System.out.println("get a waiting nodes set");
} else {
// throw an run time exception
}
} else {
FlowSet waitingNodesSet = new ArraySparseSet();
waitingNodesSet.add(pegWaiting);
waitingNodes.put(pegWaiting.getObject(), waitingNodesSet);
// System.out.println("new a waiting nodes set");
}
// end build waitingNodes Map
{
List successors = new ArrayList();
successors.add(pegWaiting);
pg.getUnitToSuccs().put(pegStmt, successors);
}
JPegStmt pegNotify = new NotifiedEntryStmt(objName, threadName, sm);
pg.getCanNotBeCompacted().add(pegNotify);
addNode(pegNotify);
{
List successors = new ArrayList();
successors.add(pegNotify);
pg.getUnitToSuccs().put(pegWaiting, successors);
}
}
private List<AllocNode> findMayAlias(PointsToSetInternal pts, Unit unit) {
// returns a list of reaching objects' AllocNodes that are contained in the set of known AllocNodes
List<AllocNode> list = new ArrayList<AllocNode>();
Iterator<AllocNode> it = makePtsIterator(pts);
while (it.hasNext()) {
AllocNode obj = it.next();
list.add(obj);
}
return list;
}
private void inlineMethod(SootMethod targetMethod, String objName, String name, String threadName, Unit unit,
UnitGraph graph, SootMethod sm) {
// System.out.println("inside extendMethod "+ targetMethod);
Body unitBody = targetMethod.getActiveBody();
JPegStmt pegStmt = new OtherStmt(objName, name, threadName, unit, graph, sm);
if (targetMethod.isSynchronized()) {
// System.out.println(unit+" is synchronized========");
String synchObj = findSynchObj(targetMethod);
JPegStmt enter = new MonitorEntryStmt(synchObj, threadName, graph, sm);
JPegStmt exit = new MonitorExitStmt(synchObj, threadName, graph, sm);
pg.getCanNotBeCompacted().add(enter);
pg.getCanNotBeCompacted().add(exit);
List list = new ArrayList();
list.add(pegStmt);
list.add(enter);
list.add(exit);
// System.out.println("add list to synch: "+list);
pg.getSynch().add(list);
}
addAndPut(unit, pegStmt);
PegGraph pG = new PegGraph(callGraph, hierarchy, pag, methodsNeedingInlining, allocNodes, inlineSites, synchObj,
multiRunAllocNodes, allocNodeToObj, unitBody, threadName, targetMethod, true, false);
// pg.addPeg(pG, this); // RLH
// PegToDotFile printer1 = new PegToDotFile(pG, false, targetMethod.getName());
// System.out.println("NeedInlining for "+targetMethod +": "+pG.getNeedInlining());
// if (pG.getNeedInlining()){
List list = new ArrayList();
list.add(pegStmt);
list.add(this);
list.add(pg);
list.add(pG);
inlineSites.add(list);
// System.out.println("----add list to inlineSites !---------");
// }
}
private String findSynchObj(SootMethod targetMethod) {
if (synchObj.containsKey(targetMethod)) {
return synchObj.get(targetMethod);
} else {
String objName = null;
if (targetMethod.isStatic()) {
objName = targetMethod.getDeclaringClass().getName();
} else {
Iterator it = ((Chain) (targetMethod.getActiveBody()).getUnits()).iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof JIdentityStmt) {
Value thisRef = ((JIdentityStmt) obj).getLeftOp();
if (thisRef instanceof Local) {
Type type = ((Local) thisRef).getType();
if (type instanceof RefType) {
objName = makeObjName(thisRef, type, (Unit) obj);
synchObj.put(targetMethod, objName);
break;
}
}
}
}
}
return objName;
}
}
private void addNode(JPegStmt stmt) {
this.addLast(stmt);
pegNodes.add(stmt);
pg.getAllNodes().add(stmt);
}
private void addAndPut(Unit unit, JPegStmt stmt) {
unitToPeg.put(unit, stmt);
addNode(stmt);
}
private void addAndPutNonCompacted(Unit unit, JPegStmt stmt) {
pg.getCanNotBeCompacted().add(stmt);
addAndPut(unit, stmt);
}
private void newAndAddElement(Unit unit, UnitGraph graph, String threadName, SootMethod sm) {
JPegStmt pegStmt = new OtherStmt("*", unit.toString(), threadName, unit, graph, sm);
addAndPut(unit, pegStmt);
}
public List getHeads() {
return heads;
}
public List getTails() {
return tails;
}
protected void addTag() {
// add tag for each stmt
Iterator it = iterator();
while (it.hasNext()) {
JPegStmt stmt = (JPegStmt) it.next();
int count = Counter.getTagNo();
StringTag t = new StringTag(Integer.toString(count));
stmt.addTag(t);
}
}
private Iterator<AllocNode> makePtsIterator(PointsToSetInternal pts) {
final HashSet<AllocNode> ret = new HashSet<AllocNode>();
pts.forall(new P2SetVisitor() {
public void visit(Node n) {
ret.add((AllocNode) n);
}
});
// testPtsIterator(ret.iterator());
return ret.iterator();
}
/*
* public List getPredsOf(Object s) { if(!unitToPreds.containsKey(s)) throw new RuntimeException("Invalid stmt" + s);
*
* return (List) unitToPreds.get(s); }
*
* public List getSuccsOf(Object s) {
*
* if(!unitToSuccs.containsKey(s)) throw new RuntimeException("Invalid stmt:" + s);
*
* return (List) unitToSuccs.get(s); }
*/
// Sometimes, we can not find the target of join(). Now we should handle it.
private void postHandleJoinStmt() {
Iterator<List<Object>> it = joinNeedReconsidered.iterator();
while (it.hasNext()) {
List list = it.next();
JPegStmt pegStmt = (JPegStmt) list.get(0);
AllocNode allocNode = (AllocNode) list.get(1);
Unit unit = (Unit) list.get(2);
if (!pg.getAllocNodeToThread().containsKey(allocNode)) {
throw new RuntimeException("allocNodeToThread does not contains key: " + allocNode);
} else {
// If the mayAlias contains one 1 element, then use the threadName as
// the Obj of the JPegStmt.
// String callerName = (String)allocNodeToCaller.get(allocNode);
Chain thread = pg.getAllocNodeToThread().get(allocNode);
addAndPutNonCompacted(unit, pegStmt);
pg.getJoinStmtToThread().put(pegStmt, thread);
}
}
}
private String makeObjName(Value value, Type type, Unit unit) {
// System.out.println("unit: "+unit);
PointsToSetInternal pts = (PointsToSetInternal) pag.reachingObjects((Local) value);
// System.out.println("pts for makeobjname: "+pts);
List<AllocNode> mayAlias = findMayAlias(pts, unit);
String objName = null;
if (allocNodeToObj == null) {
throw new RuntimeException("allocNodeToObj is null!");
}
if (mayAlias.size() == 1) {
// System.out.println("unit: "+unit);
AllocNode an = mayAlias.get(0);
// System.out.println("alloc node: "+an);
// if (!multiRunAllocNodes.contains(an)){
if (allocNodeToObj.containsKey(an)) {
objName = allocNodeToObj.get(an);
} else {
// System.out.println("===AllocNodeToObj does not contain key allocnode: "+an);
// objName = type.toString()+Counter.getObjNo();
objName = "obj" + Counter.getObjNo();
allocNodeToObj.put(an, objName);
}
// System.out.println("objName: "+objName);
// }
// else
// throw new RuntimeException("The size of object corresponds to site "+ unit + " is not 1.");
} else {
AllocNode an = mayAlias.get(0);
// System.out.println("alloc node: "+an);
// if (!multiRunAllocNodes.contains(an)){
if (allocNodeToObj.containsKey(an)) {
objName = "MULTI" + allocNodeToObj.get(an);
} else {
// System.out.println("===AllocNodeToObj does not contain key allocnode: "+an);
// objName = type.toString()+Counter.getObjNo();
objName = "MULTIobj" + Counter.getObjNo();
allocNodeToObj.put(an, objName);
}
// System.out.println("objName: "+objName);
// }
// else
// throw new RuntimeException("The size of object corresponds to site "+ unit + " is not 1.");
// System.out.println("pts: "+pts);
// throw new RuntimeException("The program exit because the size of object corresponds to site "+ unit + "is not 1.");
}
// System.out.println("==return objName: "+objName);
if (objName == null) {
throw new RuntimeException("Can not find target object for " + unit);
}
return objName;
}
protected Map<String, FlowSet> getWaitingNodes() {
return waitingNodes;
}
protected void testChain() {
System.out.println("******** chain********");
Iterator it = iterator();
while (it.hasNext()) {
JPegStmt stmt = (JPegStmt) it.next();
System.out.println(stmt.toString());
}
}
}
| 30,103
| 35.847001
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/PegGraph.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Richard L. Halpert
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Hierarchy;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.PAG;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.jimple.toolkits.thread.mhp.stmt.StartStmt;
import soot.tagkit.StringTag;
import soot.tagkit.Tag;
import soot.toolkits.graph.CompleteUnitGraph;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.util.Chain;
//add for add tag
/**
* Oct. 7, 2003 modify buildPegChain() for building chain without inliner. June 19, 2003 add begin node to peg June 18, 2003
* modify the iterator() to be iterator for all nodes of PEG and mainIterator() to be the iterator for main chain. June 12,
* 2003 add monitor Map, notifyAll Map, waitingNodes Map.
*/
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
// NOTE that this graph builder will only run to completion if all virtual
// method calls can be resolved to a single target method. This is a severely
// limiting caveat.
public class PegGraph implements DirectedGraph
// public class PegGraph extends SimplePegGraph
{
private List heads;
private List tails;
// private long numberOfEdge = 0;
protected HashMap<Object, List> unitToSuccs;
protected HashMap<Object, List> unitToPreds;
private HashMap unitToPegMap;
public HashMap<JPegStmt, List> startToThread;
public HashMap startToAllocNodes;
private HashMap<String, FlowSet> waitingNodes;
private Map startToBeginNodes;
private HashMap<String, Set<JPegStmt>> notifyAll;
private Set methodsNeedingInlining;
private boolean needInlining;
private Set<List> synch;
private Set<JPegStmt> specialJoin;
private Body body;
private Chain unitChain;
private Chain mainPegChain;
private FlowSet allNodes;
private Map<String, FlowSet> monitor;
private Set canNotBeCompacted;
private Set threadAllocSites;
private File logFile;
private FileWriter fileWriter;
private Set<Object> monitorObjs;
private Set<Unit> exceHandlers;
protected Map threadNo;// add for print to graph
protected Map threadNameToStart;
protected Map<AllocNode, String> allocNodeToObj;
protected Map<AllocNode, PegChain> allocNodeToThread;
protected Map<JPegStmt, Chain> joinStmtToThread;
// protected int count=0;
Set allocNodes;
List<List> inlineSites;
Map<SootMethod, String> synchObj;
Set multiRunAllocNodes;
/**
* Constructs a graph for the units found in the provided Body instance. Each node in the graph corresponds to a unit. The
* edges are derived from the control flow.
*
* @param Body
* The underlying body of main thread
* @param addExceptionEdges
* If true then the control flow edges associated with exceptions are added.
* @param Hierarchy
* Using class hierarchy analysis to find the run method of started thread
* @param PointsToAnalysis
* Using point to analysis (SPARK package) to improve the precision of results
*/
public PegGraph(CallGraph callGraph, Hierarchy hierarchy, PAG pag, Set<Object> methodsNeedingInlining,
Set<AllocNode> allocNodes, List inlineSites, Map synchObj, Set<AllocNode> multiRunAllocNodes, Map allocNodeToObj,
Body unitBody, SootMethod sm, boolean addExceptionEdges,
boolean dontAddEdgeFromStmtBeforeAreaOfProtectionToCatchBlock) {
/*
* public PegGraph( Body unitBody, Hierarchy hierarchy, boolean addExceptionEdges, boolean
* dontAddEdgeFromStmtBeforeAreaOfProtectionToCatchBlock) {
*/
this(callGraph, hierarchy, pag, methodsNeedingInlining, allocNodes, inlineSites, synchObj, multiRunAllocNodes,
allocNodeToObj, unitBody, "main", sm, addExceptionEdges, dontAddEdgeFromStmtBeforeAreaOfProtectionToCatchBlock);
}
/**
* Constructs a graph for the units found in the provided Body instance. Each node in the graph corresponds to a unit. The
* edges are derived from the control flow.
*
* @param body
* The underlying body we want to make a graph for.
* @param addExceptionEdges
* If true then the control flow edges associated with exceptions are added.
* @param dontAddEdgeFromStmtBeforeAreaOfProtectionToCatchBlock
* This was added for Dava. If true, edges are not added from statement before area of protection to catch. If
* false, edges ARE added. For Dava, it should be true. For flow analyses, it should be false.
* @param Hierarchy
* Using class hierarchy analysis to find the run method of started thread
* @param PointsToAnalysis
* Using point to analysis (SPARK package) to improve the precision of results
*/
public PegGraph(CallGraph callGraph, Hierarchy hierarchy, PAG pag, Set methodsNeedingInlining, Set allocNodes,
List<List> inlineSites, Map<SootMethod, String> synchObj, Set multiRunAllocNodes,
Map<AllocNode, String> allocNodeToObj, Body unitBody, String threadName, SootMethod sm, boolean addExceEdge,
boolean dontAddEdgeFromStmtBeforeAreaOfProtectionToCatchBlock) {
this.allocNodeToObj = allocNodeToObj;
this.multiRunAllocNodes = multiRunAllocNodes;
this.synchObj = synchObj;
this.inlineSites = inlineSites;
this.allocNodes = allocNodes;
this.methodsNeedingInlining = methodsNeedingInlining;
logFile = new File("log.txt");
try {
fileWriter = new FileWriter(logFile);
} catch (IOException io) {
System.err.println("Errors occur during create FileWriter !");
// throw io;
}
body = unitBody;
synch = new HashSet<List>();
exceHandlers = new HashSet<Unit>();
needInlining = true;
monitorObjs = new HashSet<Object>();
startToBeginNodes = new HashMap();
unitChain = body.getUnits();
int size = unitChain.size();
// initial unitToSuccs, unitToPreds, unitToPegMap, and startToThread
unitToSuccs = new HashMap(size * 2 + 1, 0.7f);
unitToPreds = new HashMap(size * 2 + 1, 0.7f);
// unitToPegMap is the map of a chain to its corresponding (cfg node --> peg node ) map.
unitToPegMap = new HashMap(size * 2 + 1, 0.7f);
startToThread = new HashMap(size * 2 + 1, 0.7f);
startToAllocNodes = new HashMap(size * 2 + 1, 0.7f);
waitingNodes = new HashMap<String, FlowSet>(size * 2 + 1, 0.7f);
joinStmtToThread = new HashMap<JPegStmt, Chain>();
threadNo = new HashMap();
threadNameToStart = new HashMap();
this.allocNodeToObj = new HashMap<AllocNode, String>(size * 2 + 1, 0.7f);
allocNodeToThread = new HashMap<AllocNode, PegChain>(size * 2 + 1, 0.7f);
notifyAll = new HashMap<String, Set<JPegStmt>>(size * 2 + 1, 0.7f);
methodsNeedingInlining = new HashSet();
allNodes = new ArraySparseSet();
canNotBeCompacted = new HashSet();
threadAllocSites = new HashSet();
specialJoin = new HashSet<JPegStmt>();
// if(Main.isVerbose)
// System.out.println(" Constructing PegGraph...");
// if(Main.isProfilingOptimization)
// Main.graphTimer.start();
// make a peg for debug
/*
* mainPegChain = new HashChain(); specialTreatment1();
*/
// end make a peg
UnitGraph mainUnitGraph = new CompleteUnitGraph(body);
// mainPegChain = new HashChain();
mainPegChain = new PegChain(callGraph, hierarchy, pag, threadAllocSites, methodsNeedingInlining, allocNodes, inlineSites,
synchObj, multiRunAllocNodes, allocNodeToObj, body, sm, threadName, true, this);
// testPegChain();
// System.out.println("finish building chain");
// testStartToThread();
// buildSuccessor(mainUnitGraph, mainPegChain,addExceptionEdges);
// buildSuccessorForExtendingMethod(mainPegChain);
// testSet(exceHandlers, "exceHandlers");
buildSuccessor(mainPegChain);
// System.out.println("finish building successors");
// unmodifiableSuccs(mainPegChain);
// testUnitToSucc );
buildPredecessor(mainPegChain);
// System.out.println("finish building predcessors");
// unmodifiablePreds(mainPegChain);
// testSynch();
addMonitorStmt();
addTag();
// System.out.println(this.toString());
buildHeadsAndTails();
// testIterator();
// testWaitingNodes();
// System.out.println("finish building heads and tails");
// testSet(canNotBeCompacted, "canNotBeCompacted");
// computeEdgeAndThreadNo();
// testExtendingPoints();
// testUnitToSucc();
// testPegChain();
/*
* if (print) { PegToDotFile printer1 = new PegToDotFile(this, false, sm.getName()); }
*/
try {
fileWriter.flush();
fileWriter.close();
} catch (IOException io) {
System.err.println("Errors occur during close file " + logFile.getName());
// throw io;
}
// System.out.println("==threadAllocaSits==\n"+threadAllocSites.toString());
}
protected Map getStartToBeginNodes() {
return startToBeginNodes;
}
protected Map<JPegStmt, Chain> getJoinStmtToThread() {
return joinStmtToThread;
}
protected Map getUnitToPegMap() {
return unitToPegMap;
}
// This method adds the monitorenter/exit statements into whichever pegChain contains the corresponding node statement
protected void addMonitorStmt() {
// System.out.println("====entering addMonitorStmt");
if (synch.size() > 0) {
// System.out.println("synch: "+synch);
Iterator<List> it = synch.iterator();
while (it.hasNext()) {
List list = it.next();
JPegStmt node = (JPegStmt) list.get(0);
JPegStmt enter = (JPegStmt) list.get(1);
JPegStmt exit = (JPegStmt) list.get(2);
// System.out.println("monitor node: "+node);
// System.out.println("monitor enter: "+enter);
// System.out.println("monitor exit: "+exit);
// add for test
// System.out.println("allNodes contains node: "+allNodes.contains(node));
// end add for test
{
if (!mainPegChain.contains(node)) {
boolean find = false;
// System.out.println("main chain does not contain node");
Set maps = startToThread.entrySet();
// System.out.println("size of startToThread: "+startToThread.size());
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object startNode = entry.getKey();
Iterator runIt = ((List) entry.getValue()).iterator();
while (runIt.hasNext()) {
Chain chain = (Chain) runIt.next();
// testPegChain(chain);
if (chain.contains(node)) {
find = true;
// System.out.println("---find it---");
chain.add(enter);
chain.add(exit);
break;
}
}
}
if (!find) {
throw new RuntimeException("fail to find stmt: " + node + " in chains!");
}
// this.toString();
} else {
mainPegChain.add(enter);
mainPegChain.add(exit);
}
}
allNodes.add(enter);
allNodes.add(exit);
insertBefore(node, enter);
insertAfter(node, exit);
}
}
// add for test
/*
* { // System.out.println("===main peg chain==="); //testPegChain(mainPegChain);
* //System.out.println("===end main peg chain==="); Set maps = startToThread.entrySet(); for(Iterator
* iter=maps.iterator(); iter.hasNext();){ Map.Entry entry = (Map.Entry)iter.next(); Object startNode = entry.getKey();
* Iterator runIt = ((List)entry.getValue()).iterator(); while (runIt.hasNext()){ Chain chain=(Chain)runIt.next();
* testPegChain(chain); } } }
*/
// System.out.println(this.toString());
// end add for test
}
private void insertBefore(JPegStmt node, JPegStmt enter) {
// build preds of before
List predOfBefore = new ArrayList();
predOfBefore.addAll(getPredsOf(node));
unitToPreds.put(enter, predOfBefore);
// System.out.println("put into unitToPreds enter: "+enter);
// System.out.println("put into unitToPreds value: "+predOfBefore);
Iterator predsIt = getPredsOf(node).iterator();
// build succs of former preds of node
while (predsIt.hasNext()) {
Object pred = predsIt.next();
List succ = getSuccsOf(pred);
succ.remove(node);
succ.add(enter);
// System.out.println("in unitToPred pred: "+pred);
// System.out.println("in unitToPred value is: "+succ);
}
List succOfBefore = new ArrayList();
succOfBefore.add(node);
unitToSuccs.put(enter, succOfBefore);
// System.out.println("put into unitToSuccs enter: "+enter);
// System.out.println("put into unitToSuccs value: "+succOfBefore);
List predOfNode = new ArrayList();
predOfNode.add(enter);
unitToPreds.put(node, predOfNode);
// System.out.println("put into unitToPreds enter: "+node);
// System.out.println("put into unitToPreds value: "+predOfNode);
// buildPreds();
}
private void insertAfter(JPegStmt node, JPegStmt after) {
// System.out.println("node: "+node);
// System.out.println("after: "+after);
// System.out.println("succs of node: "+getSuccsOf(node));
// this must be done first because the succs of node will be chanaged lately
List succOfAfter = new ArrayList();
succOfAfter.addAll(getSuccsOf(node));
unitToSuccs.put(after, succOfAfter);
Iterator succsIt = getSuccsOf(node).iterator();
while (succsIt.hasNext()) {
Object succ = succsIt.next();
List pred = getPredsOf(succ);
pred.remove(node);
pred.add(after);
}
List succOfNode = new ArrayList();
succOfNode.add(after);
unitToSuccs.put(node, succOfNode);
List predOfAfter = new ArrayList();
predOfAfter.add(node);
unitToPreds.put(after, predOfAfter);
// buildPredecessor(Chain pegChain);
}
private void buildSuccessor(Chain pegChain) {
// Add regular successors
{
HashMap unitToPeg = (HashMap) unitToPegMap.get(pegChain);
Iterator pegIt = pegChain.iterator();
JPegStmt currentNode, nextNode;
currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
// June 19 add for begin node
if (currentNode != null) {
// System.out.println("currentNode: "+currentNode);
// if the unit is "begin" node
nextNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
if (currentNode.getName().equals("begin")) {
List<JPegStmt> successors = new ArrayList<JPegStmt>();
successors.add(nextNode);
unitToSuccs.put(currentNode, successors);
currentNode = nextNode;
}
// end June 19 add for begin node
while (currentNode != null) {
// System.out.println("currentNode: "+currentNode);
/*
* If unitToSuccs contains currentNode, it is the point to inline methods, we need not compute its successors again
*/
if (unitToSuccs.containsKey(currentNode) && !currentNode.getName().equals("wait")) {
currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
continue;
}
List<JPegStmt> successors = new ArrayList<JPegStmt>();
Unit unit = currentNode.getUnit();
UnitGraph unitGraph = currentNode.getUnitGraph();
List unitSucc = unitGraph.getSuccsOf(unit);
Iterator succIt = unitSucc.iterator();
while (succIt.hasNext()) {
Unit un = (Unit) succIt.next();
// Don't build the edge from "monitor exit" to exception handler
if (unit instanceof ExitMonitorStmt && exceHandlers.contains(un)) {
// System.out.println("====find it! unit: "+unit+"\n un: "+un);
continue;
}
else if (unitToPeg.containsKey(un)) {
JPegStmt pp = (JPegStmt) (unitToPeg.get(un));
if (pp != null && !successors.contains(pp)) {
successors.add(pp);
}
}
} // end while
if (currentNode.getName().equals("wait")) {
while (!(currentNode.getName().equals("notified-entry"))) {
currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
}
unitToSuccs.put(currentNode, successors);
// System.out.println("put key: "+currentNode+" into unitToSucc");
} else {
unitToSuccs.put(currentNode, successors);
}
if (currentNode.getName().equals("start")) {
// System.out.println("-----build succ for start----");
if (startToThread.containsKey(currentNode)) {
List runMethodChainList = startToThread.get(currentNode);
Iterator possibleMethodIt = runMethodChainList.iterator();
while (possibleMethodIt.hasNext()) {
Chain subChain = (Chain) possibleMethodIt.next();
if (subChain != null) {
// System.out.println("build succ for subChain");
// buildSuccessor(subGraph, subChain, addExceptionEdges);
buildSuccessor(subChain);
} else {
System.out.println("*********subgraph is null!!!");
}
}
}
}
currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
} // while
// June 19 add for begin node
}
// end June 19 add for begin node
}
}
/*
* private void deleteExitToException(){ Iterator it = iterator(); while (it.hasNext()){ JPegStmt stmt =
* (JPegStmt)it.next(); Unit unit = stmt.getUnit(); UnitGraph unitGraph = stmt.getUnitGraph(); if (unit instanceof
* ExitMonitorStmt){ Iterator succIt = unitGraph.getSuccsOf(unit).iterator(); while(succIt.next &&
* exceHandlers.contains(un) ){ System.out.println("====find it! unit: "+unit+"\n un: "+un); continue; } } }
*/
private void buildPredecessor(Chain pegChain) {
// System.out.println("==building predcessor===");
// initialize the pred sets to empty
{
JPegStmt s = null;
Iterator unitIt = pegChain.iterator();
while (unitIt.hasNext()) {
s = (JPegStmt) unitIt.next();
unitToPreds.put(s, new ArrayList());
}
}
// System.out.println("==finish init of unitToPred===");
{
Iterator unitIt = pegChain.iterator();
while (unitIt.hasNext()) {
Object s = unitIt.next();
// System.out.println("s is: "+s);
// Modify preds set for each successor for this statement
if (unitToSuccs.containsKey(s)) {
List succList = unitToSuccs.get(s);
Iterator succIt = succList.iterator();
// System.out.println("unitToSuccs contains "+s);
// System.out.println("succList is: "+succList);
while (succIt.hasNext()) {
// Object successor = succIt.next();
JPegStmt successor = (JPegStmt) succIt.next();
// System.out.println("successor is: "+successor);
List<Object> predList = unitToPreds.get(successor);
// System.out.println("predList is: "+predList);
if (predList != null && !predList.contains(s)) {
try {
predList.add(s);
/*
* Tag tag1 = (Tag)((JPegStmt)s).getTags().get(0); System.out.println("add "+tag1+" "+s+" to predListof");
* Tag tag2 = (Tag)((JPegStmt)successor).getTags().get(0); System.out.println(tag2+" "+successor);
*/
} catch (NullPointerException e) {
System.out.println(s + "successor: " + successor);
throw e;
}
// if (((JPegStmt)successor).getName().equals("start")){
if (successor instanceof StartStmt) {
List runMethodChainList = startToThread.get(successor);
if (runMethodChainList == null) {
throw new RuntimeException("null runmehtodchain: \n" + successor.getUnit());
}
Iterator possibleMethodIt = runMethodChainList.iterator();
while (possibleMethodIt.hasNext()) {
Chain subChain = (Chain) possibleMethodIt.next();
buildPredecessor(subChain);
}
}
} else {
System.err.println("predlist of " + s + " is null");
// System.exit(1);
}
// unitToPreds.put(successor, predList);
}
} else {
throw new RuntimeException("unitToSuccs does not contains key" + s);
}
}
}
}
// Make pred lists unmodifiable.
private void buildHeadsAndTails() {
List tailList = new ArrayList();
List headList = new ArrayList();
// Build the sets
{
Iterator unitIt = mainPegChain.iterator();
while (unitIt.hasNext()) {
JPegStmt s = (JPegStmt) unitIt.next();
List succs = unitToSuccs.get(s);
if (succs.size() == 0) {
tailList.add(s);
}
if (!unitToPreds.containsKey(s)) {
throw new RuntimeException("unitToPreds does not contain key: " + s);
}
List preds = unitToPreds.get(s);
if (preds.size() == 0) {
headList.add(s);
// System.out.println("head is:");
}
}
}
tails = (List) tailList;
heads = (List) headList;
// tails = Collections.unmodifiableList(tailList);
// heads = Collections.unmodifiableList(headList);
Iterator tmpIt = heads.iterator();
while (tmpIt.hasNext()) {
Object temp = tmpIt.next();
// System.out.println(temp);
}
buildPredecessor(mainPegChain);
}
public boolean addPeg(PegGraph pg, Chain chain) {
if (!pg.removeBeginNode()) {
return false;
// System.out.println("adding one peg into another");
}
// System.out.println("after removeBeginNode===");
// pg.testPegChain();
// System.out.println(pg);
// put every node of peg into this
Iterator mainIt = pg.mainIterator();
while (mainIt.hasNext()) {
JPegStmt s = (JPegStmt) mainIt.next();
// System.out.println("add to mainPegChain: "+s);
mainPegChain.addLast(s);
// if (chain.contains(s)){
// System.err.println("error! chain contains: "+s);
// System.exit(1);
// }
// else
// chain.addLast(s);
}
Iterator it = pg.iterator();
while (it.hasNext()) {
JPegStmt s = (JPegStmt) it.next();
// System.out.println("add to allNodes: "+s);
if (allNodes.contains(s)) {
throw new RuntimeException("error! allNodes contains: " + s);
} else {
allNodes.add(s);
}
}
// testPegChain();
// testIterator();
unitToSuccs.putAll(pg.getUnitToSuccs());
unitToPreds.putAll(pg.getUnitToPreds());
// testUnitToSucc();
// testUnitToPred();
// buildMaps(pg); // RLH
return true;
}
private boolean removeBeginNode() {
List heads = getHeads();
if (heads.size() != 1) {
// System.out.println("heads: "+heads);
// System.out.println("Error: the size of heads is not equal to 1!");
return false;
// System.exit(1);
}
else {
JPegStmt head = (JPegStmt) heads.get(0);
// System.out.println("test head: "+head);
if (!head.getName().equals("begin")) {
throw new RuntimeException("Error: the head is not begin node!");
}
// remove begin node from heads list
heads.remove(0);
// set the preds list of the succs of head to a new list and put succs of head into heads
Iterator succOfHeadIt = getSuccsOf(head).iterator();
while (succOfHeadIt.hasNext()) {
JPegStmt succOfHead = (JPegStmt) succOfHeadIt.next();
unitToPreds.put(succOfHead, new ArrayList());
// put succs of head into heads
heads.add(succOfHead);
}
// remove begin node from inlinee Peg
if (!mainPegChain.remove(head)) {
throw new RuntimeException("fail to remove begin node in from mainPegChain!");
}
if (!allNodes.contains(head)) {
throw new RuntimeException("fail to find begin node in FlowSet allNodes!");
} else {
allNodes.remove(head);
}
// remove begin node from unitToSuccs
if (unitToSuccs.containsKey(head)) {
unitToSuccs.remove(head);
}
}
return true;
}
protected void buildSuccsForInlining(JPegStmt stmt, Chain chain, PegGraph inlinee) {
// System.out.println("entering buildSuccsForInlining...");
Tag tag = (Tag) stmt.getTags().get(0);
// System.out.println("stmt is: "+tag+" "+stmt);
/*
* connect heads of inlinee with the preds of invokeStmt and delete stmt from the succs list from the preds
*/
Iterator predIt = getPredsOf(stmt).iterator();
// System.out.println("preds list: "+getPredsOf(stmt));
// System.out.println("preds size: "+getPredsOf(stmt).size());
Iterator headsIt = inlinee.getHeads().iterator();
{
// System.out.println("heads: "+inlinee.getHeads());
while (predIt.hasNext()) {
JPegStmt pred = (JPegStmt) predIt.next();
// System.out.println("pred: "+pred);
List succList = (List) getSuccsOf(pred);
// System.out.println("succList of pred: "+succList);
int pos = succList.indexOf(stmt);
// System.out.println("remove : "+stmt + " from succList: \n"+succList+ "\n of pred" );
// remove invokeStmt
succList.remove(pos);
while (headsIt.hasNext()) {
succList.add(headsIt.next());
}
unitToSuccs.put(pred, succList);
}
{
while (headsIt.hasNext()) {
Object head = headsIt.next();
List predsOfHeads = new ArrayList();
predsOfHeads.addAll(getPredsOf(head));
unitToPreds.put(head, predsOfHeads);
}
}
/*
* { predIt = getPredsOf(stmt).iterator(); while (predIt.hasNext()){ JPegStmt s = (JPegStmt)predIt.next(); if
* (unitToSuccs.containsKey(s)){ Iterator succIt = ((List) unitToSuccs.get(s)).iterator(); while(succIt.hasNext()){
*
* //Object successor = succIt.next(); JPegStmt successor = (JPegStmt)succIt.next(); List predList = (List)
* unitToPreds.get(successor); if (predList != null) { try { predList.add(s);
*
* } catch(NullPointerException e) { System.out.println(s + "successor: " + successor); throw e; } } } } }
*
*
*
*
* }
*/
}
/*
* connect tails of inlinee with the succ of invokeStmt and delete stmt from the
*/
Iterator tailsIt = inlinee.getTails().iterator();
{
// System.out.println("tails: "+inlinee.getTails());
while (tailsIt.hasNext()) {
Iterator succIt = getSuccsOf(stmt).iterator();
JPegStmt tail = (JPegStmt) tailsIt.next();
List succList = null;
if (unitToSuccs.containsKey(tail)) {
// System.out.println("error: unitToSucc containsKey: "+tail);
succList = (List) getSuccsOf(tail);
// System.out.println("succList: "+succList);
} else {
succList = new ArrayList();
}
while (succIt.hasNext()) {
JPegStmt succ = (JPegStmt) succIt.next();
succList.add(succ);
// System.out.println("succ: "+succ);
// remove stmt from the preds list of the succs of itself.
List predListOfSucc = getPredsOf(succ);
if (predListOfSucc == null) {
throw new RuntimeException("Error: predListOfSucc is null!");
} else {
if (predListOfSucc.size() != 0) {
int pos = predListOfSucc.indexOf(stmt);
if (pos > 0 || pos == 0) {
// System.out.println("remove stmt: "+stmt+" from the preds list"+predListOfSucc+" of the succ");
predListOfSucc.remove(pos);
}
// System.out.println("remove(from PRED): ");
}
}
unitToPreds.put(succ, predListOfSucc);
}
unitToSuccs.put(tail, succList);
// System.out.println("put: "+tail);
// System.out.println("succList: "+succList+ "into unitToSucc");
}
}
// add Nov 1
{
tailsIt = inlinee.getTails().iterator();
while (tailsIt.hasNext()) {
JPegStmt s = (JPegStmt) tailsIt.next();
if (unitToSuccs.containsKey(s)) {
Iterator succIt = unitToSuccs.get(s).iterator();
while (succIt.hasNext()) {
// Object successor = succIt.next();
JPegStmt successor = (JPegStmt) succIt.next();
List<JPegStmt> predList = unitToPreds.get(successor);
if (predList != null && !predList.contains(s)) {
try {
predList.add(s);
/*
* Tag tag = (Tag)successor.getTags().get(0);
* System.out.println("add "+s+" to predlist of "+tag+" "+successor);
*/
} catch (NullPointerException e) {
System.out.println(s + "successor: " + successor);
throw e;
}
}
}
}
}
}
// end add Nov 1
// System.out.println("stmt: "+stmt);
// remove stmt from allNodes and mainPegChain
// System.out.println("mainPegChain contains stmt: "+mainPegChain.contains(stmt));
// testPegChain();
if (!allNodes.contains(stmt)) {
throw new RuntimeException("fail to find begin node in allNodes!");
} else {
allNodes.remove(stmt);
// System.out.println("remove from allNode: "+stmt);
}
if (!chain.contains(stmt)) {
throw new RuntimeException("Error! Chain does not contains stmt (extending point)!");
} else {
if (!chain.remove(stmt)) {
throw new RuntimeException("fail to remove invoke stmt in from Chain!");
}
}
/*
* if (!mainPegChain.contains(stmt)){ boolean find = false; //System.out.println("main chain does not contain AFTER");
* Set maps = startToThread.entrySet(); for(Iterator iter=maps.iterator(); iter.hasNext();){ Map.Entry entry =
* (Map.Entry)iter.next(); Object startNode = entry.getKey(); Iterator runIt = ((List)entry.getValue()).iterator(); while
* (runIt.hasNext()){ Chain chain=(Chain)runIt.next(); if (chain.contains(stmt)) { find = true; if (!chain.remove(stmt)){
* System.err.println("fail to remove begin node in from mainPegChain!"); System.exit(1); } break; } } if (find ==
* false){ System.err.println("fail to find stmt: "+stmt+" in chains!"); System.exit(1); } } //this.toString(); } else{
* if (!mainPegChain.remove(stmt)) { System.err.println("fail to remove begin node in from mainPegChain!");
* System.exit(1); } else{ // System.out.println("remove(from mainchain): "+stmt); } }
*/
// remove stmt from unitToSuccs and unitToPreds
if (unitToSuccs.containsKey(stmt)) {
unitToSuccs.remove(stmt);
}
if (unitToPreds.containsKey(stmt)) {
unitToPreds.remove(stmt);
}
}
protected void buildMaps(PegGraph pg) {
exceHandlers.addAll(pg.getExceHandlers());
startToThread.putAll(pg.getStartToThread());
startToAllocNodes.putAll(pg.getStartToAllocNodes());
startToBeginNodes.putAll(pg.getStartToBeginNodes());
waitingNodes.putAll(pg.getWaitingNodes());
notifyAll.putAll(pg.getNotifyAll());
canNotBeCompacted.addAll(pg.getCanNotBeCompacted());
synch.addAll(pg.getSynch());
threadNameToStart.putAll(pg.getThreadNameToStart());
specialJoin.addAll(pg.getSpecialJoin());
joinStmtToThread.putAll(pg.getJoinStmtToThread());
threadAllocSites.addAll(pg.getThreadAllocSites());
allocNodeToThread.putAll(pg.getAllocNodeToThread());
}
protected void buildPreds() {
buildPredecessor(mainPegChain);
Set maps = getStartToThread().entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
List runMethodChainList = (List) entry.getValue();
Iterator it = runMethodChainList.iterator();
while (it.hasNext()) {
Chain chain = (Chain) it.next();
// System.out.println("chain is null: "+(chain == null));
buildPredecessor(chain);
}
}
}
public void computeMonitorObjs() {
Set maps = monitor.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
FlowSet fs = (FlowSet) entry.getValue();
Iterator it = fs.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (!monitorObjs.contains(obj)) {
monitorObjs.add(obj);
}
}
}
}
protected boolean getNeedInlining() {
// System.out.println("return needInlining: "+ needInlining);
return needInlining;
}
protected FlowSet getAllNodes() {
return (FlowSet) allNodes;
}
protected HashMap getUnitToSuccs() {
return (HashMap) unitToSuccs;
}
protected HashMap getUnitToPreds() {
return (HashMap) unitToPreds;
}
public Body getBody() {
return body;
}
/* DirectedGraph implementation */
public List getHeads() {
return heads;
}
public List getTails() {
return tails;
}
public List getPredsOf(Object s) {
if (!unitToPreds.containsKey(s)) {
throw new RuntimeException("Invalid stmt" + s);
}
return unitToPreds.get(s);
}
public List getSuccsOf(Object s) {
if (!unitToSuccs.containsKey(s)) {
return new ArrayList();
// throw new RuntimeException("Invalid stmt:" + s);
}
return unitToSuccs.get(s);
}
public Set getCanNotBeCompacted() {
return (Set) canNotBeCompacted;
}
public int size() {
return allNodes.size();
// return pegSize;
}
public Iterator mainIterator() {
return mainPegChain.iterator();
}
public Iterator iterator() {
return allNodes.iterator();
}
public String toString() {
Iterator it = iterator();
StringBuffer buf = new StringBuffer();
while (it.hasNext()) {
JPegStmt u = (JPegStmt) it.next();
buf.append("u is: " + u + "\n");
List l = new ArrayList();
l.addAll(getPredsOf(u));
buf.append("preds: " + l + "\n");
// buf.append(u.toString() + '\n');
l = new ArrayList();
l.addAll(getSuccsOf(u));
buf.append("succs: " + l + "\n");
}
return buf.toString();
}
protected Set<Unit> getExceHandlers() {
return (Set<Unit>) exceHandlers;
}
protected void setMonitor(Map<String, FlowSet> m) {
monitor = m;
}
public Map<String, FlowSet> getMonitor() {
return (Map<String, FlowSet>) monitor;
}
public Set<Object> getMonitorObjs() {
return (Set<Object>) monitorObjs;
}
protected Set getThreadAllocSites() {
return (Set) threadAllocSites;
}
protected Set<JPegStmt> getSpecialJoin() {
return (Set<JPegStmt>) specialJoin;
}
public HashSet<List> getSynch() {
return (HashSet<List>) synch;
}
public Map<JPegStmt, List> getStartToThread() {
return startToThread;
}
public Map getStartToAllocNodes() {
return (Map) startToAllocNodes;
}
protected Map<String, FlowSet> getWaitingNodes() {
return (Map<String, FlowSet>) waitingNodes;
}
public Map<String, Set<JPegStmt>> getNotifyAll() {
return (Map<String, Set<JPegStmt>>) notifyAll;
}
protected Map<AllocNode, String> getAllocNodeToObj() {
return (Map<AllocNode, String>) allocNodeToObj;
}
public Map<AllocNode, PegChain> getAllocNodeToThread() {
return (Map<AllocNode, PegChain>) allocNodeToThread;
}
protected Map getThreadNameToStart() {
return (Map) threadNameToStart;
}
public PegChain getMainPegChain() {
return (PegChain) mainPegChain;
}
public Set getMethodsNeedingInlining() {
return (Set) methodsNeedingInlining;
}
// helper function
protected void testIterator() {
System.out.println("********begin test iterator*******");
Iterator testIt = iterator();
while (testIt.hasNext()) {
System.out.println(testIt.next());
}
System.out.println("********end test iterator*******");
System.out.println("=======size is: " + size());
}
public void testWaitingNodes() {
System.out.println("------waiting---begin");
Set maps = waitingNodes.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println("---key= " + entry.getKey());
FlowSet fs = (FlowSet) entry.getValue();
if (fs.size() > 0) {
System.out.println("**waiting nodes set:");
Iterator it = fs.iterator();
while (it.hasNext()) {
JPegStmt unit = (JPegStmt) it.next();
System.out.println(unit.toString());
}
}
}
System.out.println("------------waitingnodes---ends--------");
}
protected void testStartToThread() {
System.out.println("=====test startToThread ");
Set maps = startToThread.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
JPegStmt key = (JPegStmt) entry.getKey();
Tag tag = (Tag) key.getTags().get(0);
System.out.println("---key= " + tag + " " + key);
/*
* List list = (List)entry.getValue(); if (list.size()>0){
*
* System.out.println("**thread set:"); Iterator it = list.iterator(); while (it.hasNext()){ Chain chain
* =(Chain)it.next(); Iterator chainIt = chain.iterator();
*
* System.out.println("the size of chain is: "+chain.size()); while (chainIt.hasNext()){ JPegStmt stmt =
* (JPegStmt)chainIt.next(); System.out.println(stmt); } } }
*/
}
System.out.println("=========startToThread--ends--------");
}
protected void testUnitToPeg(HashMap unitToPeg) {
System.out.println("=====test unitToPeg ");
Set maps = unitToPeg.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println("---key= " + entry.getKey());
JPegStmt s = (JPegStmt) entry.getValue();
System.out.println("--value= " + s);
}
System.out.println("=========unitToPeg--ends--------");
}
protected void testUnitToSucc() {
System.out.println("=====test unitToSucc ");
Set maps = unitToSuccs.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
JPegStmt key = (JPegStmt) entry.getKey();
Tag tag = (Tag) key.getTags().get(0);
System.out.println("---key= " + tag + " " + key);
List list = (List) entry.getValue();
if (list.size() > 0) {
System.out.println("**succ set: size: " + list.size());
Iterator it = list.iterator();
while (it.hasNext()) {
JPegStmt stmt = (JPegStmt) it.next();
Tag tag1 = (Tag) stmt.getTags().get(0);
System.out.println(tag1 + " " + stmt);
}
}
}
System.out.println("=========unitToSucc--ends--------");
}
protected void testUnitToPred() {
System.out.println("=====test unitToPred ");
Set maps = unitToPreds.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
JPegStmt key = (JPegStmt) entry.getKey();
Tag tag = (Tag) key.getTags().get(0);
System.out.println("---key= " + tag + " " + key);
List list = (List) entry.getValue();
// if (list.size()>0){
System.out.println("**pred set: size: " + list.size());
Iterator it = list.iterator();
while (it.hasNext()) {
JPegStmt stmt = (JPegStmt) it.next();
Tag tag1 = (Tag) stmt.getTags().get(0);
System.out.println(tag1 + " " + stmt);
}
// }
}
System.out.println("=========unitToPred--ends--------");
}
protected void addTag() {
// add tag for each stmt
Iterator it = iterator();
// int count = 0;
while (it.hasNext()) {
JPegStmt stmt = (JPegStmt) it.next();
int count = Counter.getTagNo();
// count++;
StringTag t = new StringTag(Integer.toString(count));
stmt.addTag(t);
}
}
protected void testSynch() {
Iterator<List> it = synch.iterator();
System.out.println("========test synch======");
while (it.hasNext()) {
// JPegStmt s = (JPegStmt)it.next();
// Tag tag = (Tag)s.getTags().get(0);
// System.out.println(tag+" "+s);
System.out.println(it.next());
}
System.out.println("========end test synch======");
}
protected void testThreadNameToStart() {
System.out.println("=====test ThreadNameToStart");
Set maps = threadNameToStart.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
System.out.println("---key= " + key);
JPegStmt stmt = (JPegStmt) entry.getValue();
Tag tag1 = (Tag) stmt.getTags().get(0);
System.out.println("value: " + tag1 + " " + stmt);
}
System.out.println("=========ThreadNameToStart--ends--------");
}
protected void testJoinStmtToThread() {
System.out.println("=====test JoinStmtToThread");
Set maps = threadNameToStart.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
System.out.println("---key= " + key);
System.out.println("value: " + entry.getValue());
}
System.out.println("=========JoinStmtToThread--ends--------");
}
protected void testPegChain(Chain chain) {
System.out.println("******** chain********");
Iterator it = chain.iterator();
while (it.hasNext()) {
/*
* Object o = it.next(); System.out.println(o); if (!(o instanceof JPegStmt))
* System.out.println("not instanceof JPegStmt: "+o); JPegStmt s = (JPegStmt)o;
*/
JPegStmt stmt = (JPegStmt) it.next();
System.out.println(stmt.toString());
/*
* if (stmt.getName().equals("start")){
*
* System.out.println("find start method in : " + stmt.toString() ); List list =(List)startToThread.get(stmt); Iterator
* chainIt = list.iterator(); while (chainIt.hasNext()){ Chain chain = (Chain)chainIt.next(); Iterator subit =
* chain.iterator(); while (subit.hasNext()){ System.out.println("**" + ((JPegStmt)subit.next()).toString()); } }
* System.out.println("$$$$$$returing to main chain"); }
*/
}
}
protected void computeEdgeAndThreadNo() {
Iterator it = iterator();
int numberOfEdge = 0;
while (it.hasNext()) {
List succList = (List) getSuccsOf(it.next());
numberOfEdge = numberOfEdge + succList.size();
}
numberOfEdge = numberOfEdge + startToThread.size();
System.err.println("**number of edges: " + numberOfEdge);
System.err.println("**number of threads: " + (startToThread.size() + 1));
/*
* Set keySet = startToThread.keySet(); Iterator keyIt = keySet.iterator(); while (keyIt.hasNext()){ List list =
* (List)startToThread.get(keyIt.next()); System.out.println("********start thread:"); Iterator itit = list.iterator();
* while (itit.hasNext()){ System.out.println(it.next()); } }
*/
}
protected void testList(List list) {
// System.out.println("test list");
Iterator listIt = list.iterator();
while (listIt.hasNext()) {
System.out.println(listIt.next());
}
}
protected void testSet(Set set, String name) {
System.out.println("$test set " + name);
Iterator setIt = set.iterator();
while (setIt.hasNext()) {
Object s = setIt.next();
// JPegStmt s = (JPegStmt)setIt.next();
// Tag tag = (Tag)s.getTags().get(0);
System.out.println(s);
}
}
public void testMonitor() {
System.out.println("=====test monitor size: " + monitor.size());
Set maps = monitor.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
System.out.println("---key= " + key);
FlowSet list = (FlowSet) entry.getValue();
if (list.size() > 0) {
System.out.println("**set: " + list.size());
Iterator it = list.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof JPegStmt) {
JPegStmt stmt = (JPegStmt) obj;
Tag tag1 = (Tag) stmt.getTags().get(0);
System.out.println(tag1 + " " + stmt);
} else {
System.out.println("---list---");
Iterator listIt = ((List) obj).iterator();
while (listIt.hasNext()) {
Object oo = listIt.next();
if (oo instanceof JPegStmt) {
JPegStmt unit = (JPegStmt) oo;
Tag tag = (Tag) unit.getTags().get(0);
System.out.println(tag + " " + unit);
} else {
System.out.println(oo);
}
}
System.out.println("---list--end-");
}
}
}
}
System.out.println("=========monitor--ends--------");
}
}
| 47,263
| 32.856734
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/PegToDotFile.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Sable Research Group
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.jimple.toolkits.thread.mhp.stmt.JPegStmt;
import soot.tagkit.Tag;
import soot.util.Chain;
import soot.util.dot.DotGraph;
import soot.util.dot.DotGraphConstants;
import soot.util.dot.DotGraphEdge;
import soot.util.dot.DotGraphNode;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class PegToDotFile {
/*
* make all control fields public, allow other soot class dump the graph in the middle
*/
public final static int UNITGRAPH = 0;
public final static int BLOCKGRAPH = 1;
public final static int ARRAYBLOCK = 2;
public static int graphtype = UNITGRAPH;
public static boolean isBrief = false;
private static final Map<Object, String> listNodeName = new HashMap<Object, String>();
private static final Map<Object, String> startNodeToName = new HashMap<Object, String>();
/* in one page or several pages of 8.5x11 */
public static boolean onepage = true;
public PegToDotFile(PegGraph graph, boolean onepage, String name) {
PegToDotFile.onepage = onepage;
toDotFile(name, graph, "PEG graph");
}
private static int nodecount = 0;
/**
* Generates a dot format file for a DirectedGraph
*
* @param methodname,
* the name of generated dot file
* @param graph,
* a directed control flow graph (UnitGraph, BlockGraph ...)
* @param graphname,
* the title of the graph
*/
public static void toDotFile(String methodname, PegGraph graph, String graphname) {
int sequence = 0;
// this makes the node name unique
nodecount = 0; // reset node counter first.
Hashtable nodeindex = new Hashtable(graph.size());
// file name is the method name + .dot
DotGraph canvas = new DotGraph(methodname);
// System.out.println("onepage is:"+onepage);
if (!onepage) {
canvas.setPageSize(8.5, 11.0);
}
canvas.setNodeShape(DotGraphConstants.NODE_SHAPE_BOX);
canvas.setGraphLabel(graphname);
Iterator nodesIt = graph.iterator();
{
while (nodesIt.hasNext()) {
Object node = nodesIt.next();
if (node instanceof List) {
String listName = "list" + (new Integer(sequence++)).toString();
String nodeName = makeNodeName(getNodeOrder(nodeindex, listName));
listNodeName.put(node, listName);
}
}
}
nodesIt = graph.mainIterator();
while (nodesIt.hasNext()) {
Object node = nodesIt.next();
String nodeName = null;
if (node instanceof List) {
nodeName = makeNodeName(getNodeOrder(nodeindex, listNodeName.get(node)));
} else {
Tag tag = (Tag) ((JPegStmt) node).getTags().get(0);
nodeName = makeNodeName(getNodeOrder(nodeindex, tag + " " + node));
if (((JPegStmt) node).getName().equals("start")) {
startNodeToName.put(node, nodeName);
}
}
Iterator succsIt = graph.getSuccsOf(node).iterator();
// Iterator succsIt = graph.getPredsOf(node).iterator();
while (succsIt.hasNext()) {
Object s = succsIt.next();
String succName = null;
if (s instanceof List) {
succName = makeNodeName(getNodeOrder(nodeindex, listNodeName.get(s)));
} else {
JPegStmt succ = (JPegStmt) s;
Tag succTag = (Tag) succ.getTags().get(0);
succName = makeNodeName(getNodeOrder(nodeindex, succTag + " " + succ));
}
canvas.drawEdge(nodeName, succName);
// System.out.println("main: nodeName: "+nodeName);
// System.out.println("main: succName: "+succName);
}
}
System.out.println("Drew main chain");
// graph for thread
System.out.println("while printing, startToThread has size " + graph.getStartToThread().size());
Set maps = graph.getStartToThread().entrySet();
System.out.println("maps has size " + maps.size());
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object startNode = entry.getKey();
System.out.println("startNode is: " + startNode);
String startNodeName = startNodeToName.get(startNode);
System.out.println("startNodeName is: " + startNodeName);
List runMethodChainList = (List) entry.getValue();
Iterator it = runMethodChainList.iterator();
while (it.hasNext()) {
Chain chain = (Chain) it.next();
Iterator subNodesIt = chain.iterator();
boolean firstNode = false;
while (subNodesIt.hasNext()) {
Object node = subNodesIt.next();
// JPegStmt node = (JPegStmt)subNodesIt.next();
// System.out.println(node);
String nodeName = null;
if (node instanceof List) {
nodeName = makeNodeName(getNodeOrder(nodeindex, listNodeName.get(node)));
System.out.println("Didn't draw list node");
// need to draw these nodes!!!
} else {
if (((JPegStmt) node).getName().equals("begin")) {
firstNode = true;
}
Tag tag = (Tag) ((JPegStmt) node).getTags().get(0);
nodeName = makeNodeName(getNodeOrder(nodeindex, tag + " " + node));
if (((JPegStmt) node).getName().equals("start")) {
startNodeToName.put(node, nodeName);
}
// draw start edge
if (firstNode) {
if (startNodeName == null) {
System.out.println("00000000startNodeName is null ");
}
if (nodeName == null) {
System.out.println("00000000nodeName is null ");
}
// DotGraphEdge startThreadEdge = canvas.drawEdge(startNodeName, threadNodeName);
DotGraphEdge startThreadEdge = canvas.drawEdge(startNodeName, nodeName);
startThreadEdge.setStyle("dotted");
firstNode = false;
}
}
Iterator succsIt = graph.getSuccsOf(node).iterator();
// Iterator succsIt = graph.getPredsOf(node).iterator();
while (succsIt.hasNext()) {
Object succ = succsIt.next();
String threadNodeName = null;
if (succ instanceof List) {
threadNodeName = makeNodeName(getNodeOrder(nodeindex, listNodeName.get(succ)));
} else {
JPegStmt succStmt = (JPegStmt) succ;
Tag succTag = (Tag) succStmt.getTags().get(0);
threadNodeName = makeNodeName(getNodeOrder(nodeindex, succTag + " " + succStmt));
}
// canvas.drawEdge(threadNodeName,
// makeNodeName(getNodeOrder(nodeindex, succTag+" "+succ)));
canvas.drawEdge(nodeName, threadNodeName);
// System.out.println(" nodeName: "+nodeName);
// System.out.println(" threadNdoeName: "+threadNodeName);
// canvas.drawEdge(threadNodeName,
// makeNodeName(getNodeOrder(nodeindex,succ)));
}
}
}
}
// set node label
if (!isBrief) {
nodesIt = nodeindex.keySet().iterator();
while (nodesIt.hasNext()) {
Object node = nodesIt.next();
String nodename = makeNodeName(getNodeOrder(nodeindex, node));
DotGraphNode dotnode = canvas.getNode(nodename);
dotnode.setLabel(node.toString());
}
}
canvas.plot("peg.dot");
// clean up
listNodeName.clear();
startNodeToName.clear();
}
private static int getNodeOrder(Hashtable<Object, Integer> nodeindex, Object node) {
if (node == null) {
System.out.println("----node is null-----");
return 0;
// System.exit(1); // RLH
}
// System.out.println("node is: "+node);
Integer index = nodeindex.get(node);
if (index == null) {
index = new Integer(nodecount++);
nodeindex.put(node, index);
}
// System.out.println("order is:"+index.intValue());
return index.intValue();
}
private static String makeNodeName(int index) {
return "N" + index;
}
}
| 9,394
| 32.794964
| 100
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/RunMethodsPred.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.jimple.toolkits.callgraph.Edge;
import soot.jimple.toolkits.callgraph.EdgePredicate;
/**
* A predicate that accepts edges whose targets are runnable.run methods.
*
* @author Richard L. Halpert
*/
public class RunMethodsPred implements EdgePredicate {
/** Returns true iff the edge e is wanted. */
public boolean want(Edge e) {
String tgtSubSignature = e.tgt().getSubSignature();
if (tgtSubSignature.equals("void run()")) {
return true;
}
return false;
}
}
| 1,343
| 29.545455
| 73
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/SCC.java
|
package soot.jimple.toolkits.thread.mhp;
import heros.solver.Pair;
/*-
* #%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.LinkedList;
import java.util.List;
import java.util.Set;
import soot.toolkits.graph.DirectedGraph;
import soot.util.FastStack;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class SCC<T> {
private Set<T> gray;
private final LinkedList<T> finishedOrder;
private final List<List<T>> sccList;
public SCC(Iterator<T> it, DirectedGraph<T> g) {
gray = new HashSet<T>();
finishedOrder = new LinkedList<T>();
sccList = new ArrayList<List<T>>();
// Visit each node
{
while (it.hasNext()) {
T s = it.next();
if (!gray.contains(s)) {
visitNode(g, s);
}
}
}
// Re-color all nodes white
gray = new HashSet<T>();
// visit nodes via tranpose edges according decreasing order of finish time of nodes
{
Iterator<T> revNodeIt = finishedOrder.iterator();
while (revNodeIt.hasNext()) {
T s = revNodeIt.next();
if (!gray.contains(s)) {
List<T> scc = new ArrayList<T>();
visitRevNode(g, s, scc);
sccList.add(scc);
}
}
}
}
private void visitNode(DirectedGraph<T> g, T s) {
gray.add(s);
FastStack<Pair<T, Iterator<T>>> stack = new FastStack<>();
stack.push(new Pair<>(s, g.getSuccsOf(s).iterator()));
next: while (!stack.isEmpty()) {
Pair<T, Iterator<T>> p = stack.peek();
Iterator<T> it = p.getO2();
while (it.hasNext()) {
T succ = it.next();
if (!gray.contains(succ)) {
gray.add(succ);
stack.push(new Pair<T, Iterator<T>>(succ, g.getSuccsOf(succ).iterator()));
continue next;
}
}
stack.pop();
finishedOrder.addFirst(p.getO1());
}
}
private void visitRevNode(DirectedGraph<T> g, T s, List<T> scc) {
scc.add(s);
gray.add(s);
FastStack<Iterator<T>> stack = new FastStack<>();
stack.push(g.getPredsOf(s).iterator());
next: while (!stack.isEmpty()) {
Iterator<T> predsIt = stack.peek();
while (predsIt.hasNext()) {
T pred = predsIt.next();
if (!gray.contains(pred)) {
scc.add(pred);
gray.add(pred);
stack.push(g.getPredsOf(pred).iterator());
continue next;
}
}
stack.pop();
}
}
public List<List<T>> getSccList() {
return sccList;
}
public LinkedList<T> getFinishedOrder() {
return finishedOrder;
}
}
| 3,814
| 24.777027
| 88
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/StartJoinAnalysis.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.Hierarchy;
import soot.Local;
import soot.MethodOrMethodContext;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Value;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Filter;
import soot.jimple.toolkits.callgraph.TransitiveTargets;
import soot.jimple.toolkits.pointer.LocalMustAliasAnalysis;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.MHGPostDominatorsFinder;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
// StartJoinFinder written by Richard L. Halpert, 2006-12-04
// This can be used as an alternative to PegGraph and PegChain
// if only thread start, join, and type information is needed
// This is implemented as a real flow analysis so that, in the future,
// flow information can be used to match starts with joins
public class StartJoinAnalysis extends ForwardFlowAnalysis {
private static final Logger logger = LoggerFactory.getLogger(StartJoinAnalysis.class);
Set<Stmt> startStatements;
Set<Stmt> joinStatements;
Hierarchy hierarchy;
Map<Stmt, List<SootMethod>> startToRunMethods;
Map<Stmt, List<AllocNode>> startToAllocNodes;
Map<Stmt, Stmt> startToJoin;
public StartJoinAnalysis(UnitGraph g, SootMethod sm, CallGraph callGraph, PAG pag) {
super(g);
startStatements = new HashSet<Stmt>();
joinStatements = new HashSet<Stmt>();
hierarchy = Scene.v().getActiveHierarchy();
startToRunMethods = new HashMap<Stmt, List<SootMethod>>();
startToAllocNodes = new HashMap<Stmt, List<AllocNode>>();
startToJoin = new HashMap<Stmt, Stmt>();
// Get lists of start and join statements
doFlowInsensitiveSingleIterationAnalysis();
if (!startStatements.isEmpty()) {
// Get supporting info and analyses
MHGPostDominatorsFinder pd = new MHGPostDominatorsFinder(new BriefUnitGraph(sm.getActiveBody()));
// EqualUsesAnalysis lif = new EqualUsesAnalysis(g);
LocalMustAliasAnalysis lma = new LocalMustAliasAnalysis(g);
TransitiveTargets runMethodTargets = new TransitiveTargets(callGraph, new Filter(new RunMethodsPred()));
// Build a map from start stmt to possible run methods,
// and a map from start stmt to possible allocation nodes,
// and a map from start stmt to guaranteed join stmt
Iterator<Stmt> startIt = startStatements.iterator();
while (startIt.hasNext()) {
Stmt start = startIt.next();
List<SootMethod> runMethodsList = new ArrayList<SootMethod>(); // will be a list of possible run methods called by
// this start stmt
List<AllocNode> allocNodesList = new ArrayList<AllocNode>(); // will be a list of possible allocation nodes for the
// thread object that's
// getting started
// Get possible thread objects (may alias)
Value startObject = ((InstanceInvokeExpr) (start).getInvokeExpr()).getBase();
PointsToSetInternal pts = (PointsToSetInternal) pag.reachingObjects((Local) startObject);
List<AllocNode> mayAlias = getMayAliasList(pts);
if (mayAlias.size() < 1) {
continue; // If the may alias is empty, this must be dead code
}
// For each possible thread object, get run method
Iterator<MethodOrMethodContext> mayRunIt = runMethodTargets.iterator(start); // fails for some call graphs
while (mayRunIt.hasNext()) {
SootMethod runMethod = (SootMethod) mayRunIt.next();
if (runMethod.getSubSignature().equals("void run()")) {
runMethodsList.add(runMethod);
}
}
// If haven't found any run methods, then use the type of the startObject,
// and add run from it and all subclasses
if (runMethodsList.isEmpty() && ((RefType) startObject.getType()).getSootClass().isApplicationClass()) {
List<SootClass> threadClasses
= hierarchy.getSubclassesOfIncluding(((RefType) startObject.getType()).getSootClass());
Iterator<SootClass> threadClassesIt = threadClasses.iterator();
while (threadClassesIt.hasNext()) {
SootClass currentClass = threadClassesIt.next();
SootMethod currentMethod = currentClass.getMethodUnsafe("void run()");
if (currentMethod != null) {
runMethodsList.add(currentMethod);
}
}
}
// For each possible thread object, get alloc node
Iterator<AllocNode> mayAliasIt = mayAlias.iterator();
while (mayAliasIt.hasNext()) {
AllocNode allocNode = mayAliasIt.next();
allocNodesList.add(allocNode);
if (runMethodsList.isEmpty()) {
throw new RuntimeException("Can't find run method for: " + startObject);
/*
* if( allocNode.getType() instanceof RefType ) { List threadClasses = hierarchy.getSubclassesOf(((RefType)
* allocNode.getType()).getSootClass()); Iterator threadClassesIt = threadClasses.iterator();
* while(threadClassesIt.hasNext()) { SootClass currentClass = (SootClass) threadClassesIt.next(); if(
* currentClass.declaresMethod("void run()") ) { runMethodsList.add(currentClass.getMethod("void run()")); } } }
*/
}
}
// Add this start stmt to both maps
startToRunMethods.put(start, runMethodsList);
startToAllocNodes.put(start, allocNodesList);
// does this start stmt match any join stmt???
Iterator<Stmt> joinIt = joinStatements.iterator();
while (joinIt.hasNext()) {
Stmt join = joinIt.next();
Value joinObject = ((InstanceInvokeExpr) (join).getInvokeExpr()).getBase();
// If startObject and joinObject MUST be the same, and if join post-dominates start
List barriers = new ArrayList();
barriers.addAll(g.getSuccsOf(join)); // definitions of the start variable are tracked until they pass a join
// if( lif.areEqualUses( start, (Local) startObject, join, (Local) joinObject, barriers) )
if (lma.mustAlias((Local) startObject, start, (Local) joinObject, join)) {
if ((pd.getDominators(start)).contains(join)) // does join post-dominate start?
{
// logger.debug("START-JOIN PAIR: " + start + ", " + join);
startToJoin.put(start, join); // then this join always joins this start's thread
}
}
}
}
}
}
private List<AllocNode> getMayAliasList(PointsToSetInternal pts) {
List<AllocNode> list = new ArrayList<AllocNode>();
final HashSet<AllocNode> ret = new HashSet<AllocNode>();
pts.forall(new P2SetVisitor() {
public void visit(Node n) {
ret.add((AllocNode) n);
}
});
Iterator<AllocNode> it = ret.iterator();
while (it.hasNext()) {
list.add(it.next());
}
return list;
}
public Set<Stmt> getStartStatements() {
return startStatements;
}
public Set<Stmt> getJoinStatements() {
return joinStatements;
}
public Map<Stmt, List<SootMethod>> getStartToRunMethods() {
return startToRunMethods;
}
public Map<Stmt, List<AllocNode>> getStartToAllocNodes() {
return startToAllocNodes;
}
public Map<Stmt, Stmt> getStartToJoin() {
return startToJoin;
}
public void doFlowInsensitiveSingleIterationAnalysis() {
FlowSet fs = (FlowSet) newInitialFlow();
Iterator stmtIt = graph.iterator();
while (stmtIt.hasNext()) {
Stmt s = (Stmt) stmtIt.next();
flowThrough(fs, s, fs);
}
}
protected void merge(Object in1, Object in2, Object out) {
FlowSet inSet1 = (FlowSet) in1;
FlowSet inSet2 = (FlowSet) in2;
FlowSet outSet = (FlowSet) out;
inSet1.intersection(inSet2, outSet);
}
protected void flowThrough(Object inValue, Object unit, Object outValue) {
Stmt stmt = (Stmt) unit;
/*
* in.copy(out);
*
* // get list of definitions at this unit List newDefs = new ArrayList(); if(stmt instanceof DefinitionStmt) { Value
* leftOp = ((DefinitionStmt)stmt).getLeftOp(); if(leftOp instanceof Local) newDefs.add((Local) leftOp); }
*
* // kill any start stmt whose base has been redefined Iterator outIt = out.iterator(); while(outIt.hasNext()) { Stmt
* outStmt = (Stmt) outIt.next(); if(newDefs.contains((Local) ((InstanceInvokeExpr)
* (outStmt).getInvokeExpr()).getBase())) out.remove(outStmt); }
*/
// Search for start/join invoke expressions
if (stmt.containsInvokeExpr()) {
// If this is a start stmt, add it to startStatements
InvokeExpr ie = stmt.getInvokeExpr();
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
SootMethod invokeMethod = ie.getMethod();
if (invokeMethod.getName().equals("start")) {
RefType baseType = (RefType) iie.getBase().getType();
if (!baseType.getSootClass().isInterface()) // the start method we're looking for is NOT an interface method
{
List<SootClass> superClasses = hierarchy.getSuperclassesOfIncluding(baseType.getSootClass());
Iterator<SootClass> it = superClasses.iterator();
while (it.hasNext()) {
if (it.next().getName().equals("java.lang.Thread")) {
// This is a Thread.start()
if (!startStatements.contains(stmt)) {
startStatements.add(stmt);
}
// Flow this Thread.start() down
// out.add(stmt);
}
}
}
}
// If this is a join stmt, add it to joinStatements
if (invokeMethod.getName().equals("join")) // the join method we're looking for is NOT an interface method
{
RefType baseType = (RefType) iie.getBase().getType();
if (!baseType.getSootClass().isInterface()) {
List<SootClass> superClasses = hierarchy.getSuperclassesOfIncluding(baseType.getSootClass());
Iterator<SootClass> it = superClasses.iterator();
while (it.hasNext()) {
if (it.next().getName().equals("java.lang.Thread")) {
// This is a Thread.join()
if (!joinStatements.contains(stmt)) {
joinStatements.add(stmt);
}
}
}
}
}
}
}
}
protected void copy(Object source, Object dest) {
FlowSet sourceSet = (FlowSet) source;
FlowSet destSet = (FlowSet) dest;
sourceSet.copy(destSet);
}
protected Object entryInitialFlow() {
return new ArraySparseSet();
}
protected Object newInitialFlow() {
return new ArraySparseSet();
}
}
| 12,459
| 37.816199
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/StartJoinFinder.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.jimple.Stmt;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.PAG;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
// StartJoinFinder written by Richard L. Halpert, 2006-12-04
// This can be used as an alternative to PegGraph and PegChain
// if only thread start, join, and type information is needed
public class StartJoinFinder {
Set<Stmt> startStatements;
Set<Stmt> joinStatements;
Map<Stmt, List<SootMethod>> startToRunMethods;
Map<Stmt, List<AllocNode>> startToAllocNodes;
Map<Stmt, Stmt> startToJoin;
Map<Stmt, SootMethod> startToContainingMethod;
public StartJoinFinder(CallGraph callGraph, PAG pag) {
startStatements = new HashSet<Stmt>();
joinStatements = new HashSet<Stmt>();
startToRunMethods = new HashMap<Stmt, List<SootMethod>>();
startToAllocNodes = new HashMap<Stmt, List<AllocNode>>();
startToJoin = new HashMap<Stmt, Stmt>();
startToContainingMethod = new HashMap<Stmt, SootMethod>();
Iterator runAnalysisClassesIt = Scene.v().getApplicationClasses().iterator();
while (runAnalysisClassesIt.hasNext()) {
SootClass appClass = (SootClass) runAnalysisClassesIt.next();
Iterator methodsIt = appClass.getMethods().iterator();
while (methodsIt.hasNext()) {
SootMethod method = (SootMethod) methodsIt.next();
// If this method may have a start or run method as a target, then do a start/join analysis
boolean mayHaveStartStmt = false;
Iterator edgesIt = callGraph.edgesOutOf(method);
while (edgesIt.hasNext()) {
SootMethod target = ((Edge) edgesIt.next()).tgt();
if (target.getName().equals("start") || target.getName().equals("run")) {
mayHaveStartStmt = true;
}
}
if (mayHaveStartStmt && method.isConcrete()) {
Body b = method.retrieveActiveBody();
// run the intraprocedural analysis
StartJoinAnalysis sja
= new StartJoinAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b), method, callGraph, pag);
// Add to interprocedural results
startStatements.addAll(sja.getStartStatements());
joinStatements.addAll(sja.getJoinStatements());
startToRunMethods.putAll(sja.getStartToRunMethods());
startToAllocNodes.putAll(sja.getStartToAllocNodes());
startToJoin.putAll(sja.getStartToJoin());
Iterator<Stmt> startIt = sja.getStartStatements().iterator();
while (startIt.hasNext()) {
Stmt start = startIt.next();
startToContainingMethod.put(start, method);
}
}
}
}
}
public Set<Stmt> getStartStatements() {
return startStatements;
}
public Set<Stmt> getJoinStatements() {
return joinStatements;
}
public Map<Stmt, List<SootMethod>> getStartToRunMethods() {
return startToRunMethods;
}
public Map<Stmt, List<AllocNode>> getStartToAllocNodes() {
return startToAllocNodes;
}
public Map<Stmt, Stmt> getStartToJoin() {
return startToJoin;
}
public Map<Stmt, SootMethod> getStartToContainingMethod() {
return startToContainingMethod;
}
}
| 4,376
| 32.930233
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/SynchObliviousMhpAnalysis.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.util.SootThreadGroup;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Kind;
import soot.PointsToAnalysis;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.Stmt;
import soot.jimple.spark.ondemand.DemandCSPointsTo;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.PAG;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.jimple.toolkits.thread.AbstractRuntimeThread;
import soot.jimple.toolkits.thread.mhp.findobject.AllocNodesFinder;
import soot.jimple.toolkits.thread.mhp.findobject.MultiRunStatementsFinder;
import soot.jimple.toolkits.thread.mhp.pegcallgraph.PegCallGraph;
import soot.options.SparkOptions;
import soot.toolkits.graph.CompleteUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.FlowSet;
/**
* UnsynchronizedMhpAnalysis written by Richard L. Halpert 2006-12-09 Calculates May-Happen-in-Parallel (MHP) information as
* if in the absence of synchronization. Any synchronization statements (synchronized, wait, notify, etc.) are ignored. If
* the program has no synchronization, then this actually generates correct MHP. This is useful if you are trying to generate
* (replacement) synchronization. It is also useful if an approximation is acceptable, because it runs much faster than a
* synch-aware MHP analysis.
*
* This analysis uses may-alias information to determine the types of threads launched and the call graph to determine which
* methods they may call. This analysis uses a run-once/run-one-at-a-time/run-many classification to determine if a thread
* may be run in parallel with itself.
*/
public class SynchObliviousMhpAnalysis implements MhpTester, Runnable {
private static final Logger logger = LoggerFactory.getLogger(SynchObliviousMhpAnalysis.class);
List<AbstractRuntimeThread> threadList;
boolean optionPrintDebug;
boolean optionThreaded = false; // DOESN'T WORK if set to true... ForwardFlowAnalysis uses a static field in a
// thread-unsafe way
Thread self;
public SynchObliviousMhpAnalysis() {
threadList = new ArrayList<AbstractRuntimeThread>();
optionPrintDebug = false;
self = null;
buildThreadList();
}
protected void buildThreadList() // can only be run once if optionThreaded is true
{
if (optionThreaded) {
if (self != null) {
return; // already running... do nothing
}
self = new Thread(new SootThreadGroup(), this);
self.start();
} else {
run();
}
}
public void run() {
SootMethod mainMethod = Scene.v().getMainClass().getMethodByName("main");
PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
if (pta instanceof DemandCSPointsTo) {
DemandCSPointsTo demandCSPointsTo = (DemandCSPointsTo) pta;
pta = demandCSPointsTo.getPAG();
}
if (!(pta instanceof PAG)) {
throw new RuntimeException("You must use Spark for points-to analysis when computing MHP information!");
}
PAG pag = (PAG) pta;
SparkOptions so = pag.getOpts();
if (so.rta()) {
throw new RuntimeException("MHP cannot be calculated using RTA due to incomplete call graph");
}
CallGraph callGraph = Scene.v().getCallGraph();
// Get a call graph trimmed to contain only the relevant methods (non-lib, non-native)
// logger.debug(" MHP: PegCallGraph");
PegCallGraph pecg = new PegCallGraph(callGraph);
// Find allocation nodes that are run more than once
// Also find methods that are run more than once
// logger.debug(" MHP: AllocNodesFinder");
AllocNodesFinder anf = new AllocNodesFinder(pecg, callGraph, (PAG) pta);
Set<AllocNode> multiRunAllocNodes = anf.getMultiRunAllocNodes();
Set<SootMethod> multiCalledMethods = anf.getMultiCalledMethods();
// Find Thread.start() and Thread.join() statements (in live code)
// logger.debug(" MHP: StartJoinFinder");
StartJoinFinder sjf = new StartJoinFinder(callGraph, (PAG) pta); // does analysis
Map<Stmt, List<AllocNode>> startToAllocNodes = sjf.getStartToAllocNodes();
Map<Stmt, List<SootMethod>> startToRunMethods = sjf.getStartToRunMethods();
Map<Stmt, SootMethod> startToContainingMethod = sjf.getStartToContainingMethod();
Map<Stmt, Stmt> startToJoin = sjf.getStartToJoin();
// Build MHP Lists
// logger.debug(" MHP: Building MHP Lists");
List<AbstractRuntimeThread> runAtOnceCandidates = new ArrayList<AbstractRuntimeThread>();
Iterator threadIt = startToRunMethods.entrySet().iterator();
int threadNum = 0;
while (threadIt.hasNext()) {
// Get list of possible Runnable.run methods (actually, a list of peg chains)
// and a list of allocation sites for this thread start statement
// and the thread start statement itself
Map.Entry e = (Map.Entry) threadIt.next();
Stmt startStmt = (Stmt) e.getKey();
List runMethods = (List) e.getValue();
List threadAllocNodes = startToAllocNodes.get(e.getKey());
// Get a list of all possible unique Runnable.run methods for this thread start statement
AbstractRuntimeThread thread = new AbstractRuntimeThread(); // provides a list interface to the methods in a thread's
// sub-call-graph
thread.setStartStmt(startStmt);
// List threadMethods = new ArrayList();
Iterator runMethodsIt = runMethods.iterator();
while (runMethodsIt.hasNext()) {
SootMethod method = (SootMethod) runMethodsIt.next();
if (!thread.containsMethod(method)) {
thread.addMethod(method);
thread.addRunMethod(method);
}
}
// Get a list containing all methods in the call graph(s) rooted at the possible run methods for this thread start
// statement
// AKA a list of all methods that might be called by the thread started here
int methodNum = 0;
while (methodNum < thread.methodCount()) // iterate over all methods in threadMethods, even as new methods are being
// added to it
{
Iterator succMethodsIt = pecg.getSuccsOf(thread.getMethod(methodNum)).iterator();
while (succMethodsIt.hasNext()) {
SootMethod method = (SootMethod) succMethodsIt.next();
// if all edges into this method are of Kind THREAD, ignore it
// (because it's a run method that won't be called as part of THIS thread) THIS IS NOT OPTIMAL
boolean ignoremethod = true;
Iterator edgeInIt = callGraph.edgesInto(method);
while (edgeInIt.hasNext()) {
Edge edge = (Edge) edgeInIt.next();
if (edge.kind() != Kind.THREAD && edge.kind() != Kind.EXECUTOR && edge.kind() != Kind.ASYNCTASK
&& thread.containsMethod(edge.src())) {
ignoremethod = false;
}
}
if (!ignoremethod && !thread.containsMethod(method)) {
thread.addMethod(method);
}
}
methodNum++;
}
// Add this list of methods to MHPLists
threadList.add(thread);
if (optionPrintDebug) {
System.out.println(thread.toString());
}
// Find out if the "thread" in "thread.start()" could be more than one object
boolean mayStartMultipleThreadObjects = (threadAllocNodes.size() > 1) || so.types_for_sites();
if (!mayStartMultipleThreadObjects) // if there's only one alloc node
{
if (multiRunAllocNodes.contains(threadAllocNodes.iterator().next())) // but it gets run more than once
{
mayStartMultipleThreadObjects = true; // then "thread" in "thread.start()" could be more than one object
}
}
if (mayStartMultipleThreadObjects) {
thread.setStartStmtHasMultipleReachingObjects();
}
// Find out if the "thread.start()" statement may be run more than once
SootMethod startStmtMethod = startToContainingMethod.get(startStmt);
thread.setStartStmtMethod(startStmtMethod);
boolean mayBeRunMultipleTimes = multiCalledMethods.contains(startStmtMethod); // if method is called more than once...
if (!mayBeRunMultipleTimes) {
UnitGraph graph = new CompleteUnitGraph(startStmtMethod.getActiveBody());
MultiRunStatementsFinder finder
= new MultiRunStatementsFinder(graph, startStmtMethod, multiCalledMethods, callGraph);
FlowSet multiRunStatements = finder.getMultiRunStatements(); // list of all units that may be run more than once in
// this method
if (multiRunStatements.contains(startStmt)) {
mayBeRunMultipleTimes = true;
}
}
if (mayBeRunMultipleTimes) {
thread.setStartStmtMayBeRunMultipleTimes();
}
// If a run-many thread.start() statement is (always) associated with a join statement in the same method,
// then it may be possible to treat it as run-once, if this method is non-reentrant and called only
// by one thread (sounds strict, but actually this is the most common case)
if (mayBeRunMultipleTimes && startToJoin.containsKey(startStmt)) {
thread.setJoinStmt(startToJoin.get(startStmt));
mayBeRunMultipleTimes = false; // well, actually, we don't know yet
methodNum = 0;
List<SootMethod> containingMethodCalls = new ArrayList<SootMethod>();
containingMethodCalls.add(startStmtMethod);
while (methodNum < containingMethodCalls.size()) // iterate over all methods in threadMethods, even as new methods
// are being added to it
{
Iterator succMethodsIt = pecg.getSuccsOf(containingMethodCalls.get(methodNum)).iterator();
while (succMethodsIt.hasNext()) {
SootMethod method = (SootMethod) succMethodsIt.next();
if (method == startStmtMethod) { // this method is reentrant
mayBeRunMultipleTimes = true; // this time it's for sure
thread.setStartMethodIsReentrant();
thread.setRunsMany();
break;
}
if (!containingMethodCalls.contains(method)) {
containingMethodCalls.add(method);
}
}
methodNum++;
}
if (!mayBeRunMultipleTimes) { // There's still one thing that might cause this to be run multiple times: if it can be
// run in parallel with
// itself
// but we can't find that out 'till we're done
runAtOnceCandidates.add(thread);
}
}
// If more than one thread might be started at this start statement,
// and this start statement may be run more than once,
// then add this list of methods to MHPLists *AGAIN*
if (optionPrintDebug) {
System.out.println("Start Stmt " + startStmt.toString() + " mayStartMultipleThreadObjects="
+ mayStartMultipleThreadObjects + " mayBeRunMultipleTimes=" + mayBeRunMultipleTimes);
}
if (mayStartMultipleThreadObjects && mayBeRunMultipleTimes) {
threadList.add(thread); // add another copy
thread.setRunsMany();
if (optionPrintDebug) {
System.out.println(thread.toString());
}
} else {
thread.setRunsOnce();
}
threadNum++;
}
// do same for main method
AbstractRuntimeThread mainThread = new AbstractRuntimeThread();
// List mainMethods = new ArrayList();
threadList.add(mainThread);
mainThread.setRunsOnce();
mainThread.addMethod(mainMethod);
mainThread.addRunMethod(mainMethod);
mainThread.setIsMainThread();
// get all the successors, add to threadMethods
int methodNum = 0;
while (methodNum < mainThread.methodCount()) {
Iterator succMethodsIt = pecg.getSuccsOf(mainThread.getMethod(methodNum)).iterator();
while (succMethodsIt.hasNext()) {
SootMethod method = (SootMethod) succMethodsIt.next();
// if all edges into this are of Kind THREAD, ignore it
boolean ignoremethod = true;
Iterator edgeInIt = callGraph.edgesInto(method);
while (edgeInIt.hasNext()) {
if (((Edge) edgeInIt.next()).kind() != Kind.THREAD) {
ignoremethod = false;
}
}
if (!ignoremethod && !mainThread.containsMethod(method)) {
mainThread.addMethod(method);
}
}
methodNum++;
}
if (optionPrintDebug) {
logger.debug("" + mainThread.toString());
}
// Revisit the containing methods of start-join pairs that are non-reentrant but might be called in parallel
boolean addedNew = true;
while (addedNew) {
addedNew = false;
ListIterator<AbstractRuntimeThread> it = runAtOnceCandidates.listIterator();
while (it.hasNext()) {
AbstractRuntimeThread someThread = it.next();
SootMethod someStartMethod = someThread.getStartStmtMethod();
if (mayHappenInParallelInternal(someStartMethod, someStartMethod)) {
threadList.add(someThread); // add a second copy of it
someThread.setStartMethodMayHappenInParallel();
someThread.setRunsMany();
it.remove();
if (optionPrintDebug) {
logger.debug("" + someThread.toString());
}
addedNew = true;
}
}
}
// mark the remaining threads here as run-one-at-a-time
Iterator<AbstractRuntimeThread> it = runAtOnceCandidates.iterator();
while (it.hasNext()) {
AbstractRuntimeThread someThread = it.next();
someThread.setRunsOneAtATime();
}
}
public boolean mayHappenInParallel(SootMethod m1, Unit u1, SootMethod m2, Unit u2) {
if (optionThreaded) {
if (self == null) {
return true; // not started...
}
// Wait until finished
logger.debug("[mhp] waiting for analysis thread to finish");
try {
self.join();
} catch (InterruptedException ie) {
return true;
}
}
return mayHappenInParallelInternal(m1, m2);
}
public boolean mayHappenInParallel(SootMethod m1, SootMethod m2) {
if (optionThreaded) {
if (self == null) {
return true; // not started...
}
// Wait until finished
logger.debug("[mhp] waiting for thread to finish");
try {
self.join();
} catch (InterruptedException ie) {
return true;
}
}
return mayHappenInParallelInternal(m1, m2);
}
private boolean mayHappenInParallelInternal(SootMethod m1, SootMethod m2) {
if (threadList == null) // not run
{
return true;
}
int size = threadList.size();
for (int i = 0; i < size; i++) {
if (threadList.get(i).containsMethod(m1)) {
for (int j = 0; j < size; j++) {
if (threadList.get(j).containsMethod(m2) && i != j) {
return true;
}
}
}
}
return false;
}
public void printMhpSummary() {
if (optionThreaded) {
if (self == null) {
return; // not run... do nothing
}
// Wait until finished
logger.debug("[mhp] waiting for thread to finish");
try {
self.join();
} catch (InterruptedException ie) {
return;
}
}
List<AbstractRuntimeThread> threads = new ArrayList<AbstractRuntimeThread>();
int size = threadList.size();
logger.debug("[mhp]");
for (int i = 0; i < size; i++) {
if (!threads.contains(threadList.get(i))) {
logger.debug("[mhp] " + threadList.get(i).toString().replaceAll("\n", "\n[mhp] ").replaceAll(">,", ">\n[mhp] "));
logger.debug("[mhp]");
}
threads.add(threadList.get(i));
}
}
public List<SootClass> getThreadClassList() {
if (optionThreaded) {
if (self == null) {
return null; // not run... do nothing
}
// Wait until finished
logger.debug("[mhp] waiting for thread to finish");
try {
self.join();
} catch (InterruptedException ie) {
return null;
}
}
if (threadList == null) {
return null;
}
List<SootClass> threadClasses = new ArrayList<SootClass>();
int size = threadList.size();
for (int i = 0; i < size; i++) {
AbstractRuntimeThread thread = threadList.get(i);
Iterator<Object> threadRunMethodIt = thread.getRunMethods().iterator();
while (threadRunMethodIt.hasNext()) {
SootClass threadClass = ((SootMethod) threadRunMethodIt.next()).getDeclaringClass(); // what about subclasses???
if (!threadClasses.contains(threadClass) && threadClass.isApplicationClass()) {
threadClasses.add(threadClass);
}
}
}
return threadClasses;
}
public List<AbstractRuntimeThread> getThreads() {
if (optionThreaded) {
if (self == null) {
return null; // not run... do nothing
}
// Wait until finished
logger.debug("[mhp] waiting for thread to finish");
try {
self.join();
} catch (InterruptedException ie) {
return null;
}
}
if (threadList == null) {
return null;
}
List<AbstractRuntimeThread> threads = new ArrayList<AbstractRuntimeThread>();
int size = threadList.size();
for (int i = 0; i < size; i++) {
if (!threads.contains(threadList.get(i))) {
threads.add(threadList.get(i));
}
}
return threads;
}
}
| 18,724
| 36.752016
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/TargetMethodsFinder.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.Kind;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
/**
* Assembles a list of target methods for a given unit and call graph, filtering out static initializers and optionally
* native methods. Can optionally throw a runtime exception if the list is null.
*/
public class TargetMethodsFinder {
public List<SootMethod> find(Unit unit, CallGraph cg, boolean canBeNullList, boolean canBeNative) {
List<SootMethod> target = new ArrayList<SootMethod>();
Iterator<Edge> it = cg.edgesOutOf(unit);
while (it.hasNext()) {
Edge edge = it.next();
SootMethod targetMethod = edge.tgt();
if (targetMethod.isNative() && !canBeNative) {
continue;
}
if (edge.kind() == Kind.CLINIT) {
continue;
}
target.add(targetMethod);
}
if (target.size() < 1 && !canBeNullList) {
throw new RuntimeException("No target method for: " + unit);
}
return target;
}
}
| 1,972
| 31.344262
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/TopologicalSorter.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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.LinkedList;
import java.util.List;
import soot.util.Chain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class TopologicalSorter {
Chain chain;
PegGraph pg;
LinkedList<Object> sorter = new LinkedList<Object>();
List<Object> visited = new ArrayList<Object>();
public TopologicalSorter(Chain chain, PegGraph pg) {
this.chain = chain;
this.pg = pg;
go();
// printSeq(sorter);
}
private void go() {
Iterator it = chain.iterator();
while (it.hasNext()) {
Object node = it.next();
dfsVisit(node);
}
}
private void dfsVisit(Object m) {
if (visited.contains(m)) {
return;
}
visited.add(m);
Iterator targetsIt = pg.getSuccsOf(m).iterator();
while (targetsIt.hasNext()) {
Object target = targetsIt.next();
dfsVisit(target);
}
sorter.addFirst(m);
}
public List<Object> sorter() {
return sorter;
}
}
| 2,254
| 26.839506
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/UnsynchronizedMhpAnalysis.java
|
package soot.jimple.toolkits.thread.mhp;
/*-
* #%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%
*/
/**
* @deprecated This class has been added to maintain compatibility while it is being renamed to
* {@link SynchObliviousMhpAnalysis}. Use that instead!
*/
@Deprecated
public class UnsynchronizedMhpAnalysis extends SynchObliviousMhpAnalysis {
}
| 1,122
| 33.030303
| 95
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/findobject/AllocNodesFinder.java
|
package soot.jimple.toolkits.thread.mhp.findobject;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import soot.PointsToAnalysis;
import soot.RefType;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.NewExpr;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.PAG;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.thread.mhp.pegcallgraph.PegCallGraph;
import soot.toolkits.graph.CompleteUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.FlowSet;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class AllocNodesFinder {
private final Set<AllocNode> allocNodes;
private final Set<AllocNode> multiRunAllocNodes;
private final Set<SootMethod> multiCalledMethods;
PAG pag;
public AllocNodesFinder(PegCallGraph pcg, CallGraph cg, PAG pag) {
// System.out.println("===inside AllocNodesFinder===");
this.pag = pag;
allocNodes = new HashSet<AllocNode>();
multiRunAllocNodes = new HashSet<AllocNode>();
multiCalledMethods = new HashSet<SootMethod>();
MultiCalledMethods mcm = new MultiCalledMethods(pcg, multiCalledMethods);
find(mcm.getMultiCalledMethods(), pcg, cg);
}
private void find(Set<SootMethod> multiCalledMethods, PegCallGraph pcg, CallGraph callGraph) {
Set clinitMethods = pcg.getClinitMethods();
Iterator it = pcg.iterator();
while (it.hasNext()) {
SootMethod sm = (SootMethod) it.next();
UnitGraph graph = new CompleteUnitGraph(sm.getActiveBody());
Iterator iterator = graph.iterator();
if (multiCalledMethods.contains(sm)) {
while (iterator.hasNext()) {
Unit unit = (Unit) iterator.next();
// System.out.println("unit: "+unit);
if (clinitMethods.contains(sm) && unit instanceof AssignStmt) {
// Value rightOp = ((AssignStmt)unit).getRightOp();
// Type type = ((NewExpr)rightOp).getType();
AllocNode allocNode = pag.makeAllocNode(PointsToAnalysis.STRING_NODE, RefType.v("java.lang.String"), null);
// AllocNode allocNode = pag.makeAllocNode((NewExpr)rightOp, type, sm);
// System.out.println("make alloc node: "+allocNode);
allocNodes.add(allocNode);
multiRunAllocNodes.add(allocNode);
}
else if (unit instanceof DefinitionStmt) {
Value rightOp = ((DefinitionStmt) unit).getRightOp();
if (rightOp instanceof NewExpr) {
Type type = ((NewExpr) rightOp).getType();
AllocNode allocNode = pag.makeAllocNode(rightOp, type, sm);
// System.out.println("make alloc node: "+allocNode);
allocNodes.add(allocNode);
multiRunAllocNodes.add(allocNode);
}
}
}
}
else {
// MultiRunStatementsFinder finder = new MultiRunStatementsFinder(graph, sm);
MultiRunStatementsFinder finder = new MultiRunStatementsFinder(graph, sm, multiCalledMethods, callGraph);
FlowSet fs = finder.getMultiRunStatements();
// methodsToMultiObjsSites.put(sm, fs);
// PatchingChain pc = sm.getActiveBody().getUnits();
while (iterator.hasNext()) {
Unit unit = (Unit) iterator.next();
// System.out.println("unit: "+unit);
if (clinitMethods.contains(sm) && unit instanceof AssignStmt) {
AllocNode allocNode = pag.makeAllocNode(PointsToAnalysis.STRING_NODE, RefType.v("java.lang.String"), null);
// AllocNode allocNode = pag.makeAllocNode((NewExpr)rightOp, type, sm);
// System.out.println("make alloc node: "+allocNode);
allocNodes.add(allocNode);
/*
* if (fs.contains(unit)){ multiRunAllocNodes.add(unit); }
*/
} else if (unit instanceof DefinitionStmt) {
Value rightOp = ((DefinitionStmt) unit).getRightOp();
if (rightOp instanceof NewExpr) {
Type type = ((NewExpr) rightOp).getType();
AllocNode allocNode = pag.makeAllocNode(rightOp, type, sm);
// System.out.println("make alloc node: "+allocNode);
allocNodes.add(allocNode);
if (fs.contains(unit)) {
// System.out.println("fs contains: "+unit);
multiRunAllocNodes.add(allocNode);
}
}
}
}
}
}
}
public Set<AllocNode> getAllocNodes() {
return allocNodes;
}
public Set<AllocNode> getMultiRunAllocNodes() {
return multiRunAllocNodes;
}
public Set<SootMethod> getMultiCalledMethods() {
return multiCalledMethods;
}
}
| 6,024
| 36.42236
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/findobject/MultiCalledMethods.java
|
package soot.jimple.toolkits.thread.mhp.findobject;
/*-
* #%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.LinkedList;
import java.util.List;
import java.util.Set;
import soot.Scene;
import soot.SootMethod;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.thread.mhp.pegcallgraph.PegCallGraph;
import soot.toolkits.graph.CompleteUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.FlowSet;
/*
import soot.tagkit.*;
import soot.toolkits.scalar.*;
*/
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class MultiCalledMethods {
Set<SootMethod> multiCalledMethods = new HashSet<SootMethod>();
MultiCalledMethods(PegCallGraph pcg, Set<SootMethod> mcm) {
multiCalledMethods = mcm;
byMCalledS0(pcg);
finder1(pcg);
finder2(pcg);
propagate(pcg);
}
private void byMCalledS0(PegCallGraph pcg) {
Iterator it = pcg.iterator();
while (it.hasNext()) {
SootMethod sm = (SootMethod) it.next();
UnitGraph graph = new CompleteUnitGraph(sm.getActiveBody());
CallGraph callGraph = Scene.v().getCallGraph();
MultiRunStatementsFinder finder = new MultiRunStatementsFinder(graph, sm, multiCalledMethods, callGraph);
FlowSet fs = finder.getMultiRunStatements();
}
}
private void propagate(PegCallGraph pcg) {
Set<SootMethod> visited = new HashSet();
List<SootMethod> reachable = new ArrayList<SootMethod>();
reachable.addAll(multiCalledMethods);
while (reachable.size() >= 1) {
SootMethod popped = reachable.remove(0);
if (visited.contains(popped)) {
continue;
}
if (!multiCalledMethods.contains(popped)) {
multiCalledMethods.add(popped);
}
visited.add(popped);
Iterator succIt = pcg.getSuccsOf(popped).iterator();
while (succIt.hasNext()) {
Object succ = succIt.next();
reachable.add((SootMethod) succ);
}
}
}
// Use breadth first search to find methods are called more than once in call graph
private void finder1(PegCallGraph pcg) {
Set clinitMethods = pcg.getClinitMethods();
Iterator it = pcg.iterator();
while (it.hasNext()) {
Object head = it.next();
// breadth first scan
Set<Object> gray = new HashSet<Object>();
LinkedList<Object> queue = new LinkedList<Object>();
queue.add(head);
while (queue.size() > 0) {
Object root = queue.getFirst();
Iterator succsIt = pcg.getSuccsOf(root).iterator();
while (succsIt.hasNext()) {
Object succ = succsIt.next();
if (!gray.contains(succ)) {
gray.add(succ);
queue.addLast(succ);
} else if (clinitMethods.contains(succ)) {
continue;
} else {
multiCalledMethods.add((SootMethod) succ);
}
}
queue.remove(root);
}
}
}
// Find multi called methods relavant to recusive method invocation
private void finder2(PegCallGraph pcg) {
pcg.trim();
Set<SootMethod> first = new HashSet<SootMethod>();
Set<SootMethod> second = new HashSet<SootMethod>();
// Visit each node
Iterator it = pcg.iterator();
while (it.hasNext()) {
SootMethod s = (SootMethod) it.next();
if (!second.contains(s)) {
visitNode(s, pcg, first, second);
}
}
}
private void visitNode(SootMethod node, PegCallGraph pcg, Set<SootMethod> first, Set<SootMethod> second) {
if (first.contains(node)) {
second.add(node);
if (!multiCalledMethods.contains(node)) {
multiCalledMethods.add(node);
}
} else {
first.add(node);
}
Iterator it = pcg.getTrimSuccsOf(node).iterator();
while (it.hasNext()) {
SootMethod succ = (SootMethod) it.next();
if (!second.contains(succ)) {
visitNode(succ, pcg, first, second);
}
}
}
public Set<SootMethod> getMultiCalledMethods() {
return multiCalledMethods;
}
}
| 5,252
| 28.511236
| 111
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/findobject/MultiRunStatementsFinder.java
|
package soot.jimple.toolkits.thread.mhp.findobject;
/*-
* #%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.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.thread.mhp.TargetMethodsFinder;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class MultiRunStatementsFinder extends ForwardFlowAnalysis<Unit, BitSet> {
Set<Unit> multiRunStatements = new HashSet<Unit>();
protected Map<Object, Integer> nodeToIndex;
protected int lastIndex = 0;
// add soot method here just for debug
public MultiRunStatementsFinder(UnitGraph g, SootMethod sm, Set<SootMethod> multiCalledMethods, CallGraph cg) {
super(g);
nodeToIndex = new HashMap<Object, Integer>();
// System.out.println("===entering MultiObjectAllocSites==");
doAnalysis();
// testMultiObjSites(sm);
findMultiCalledMethodsIntra(multiCalledMethods, cg);
// testMultiObjSites(sm);
}
private void findMultiCalledMethodsIntra(Set<SootMethod> multiCalledMethods, CallGraph callGraph) {
Iterator<Unit> it = multiRunStatements.iterator();
while (it.hasNext()) {
Stmt stmt = (Stmt) it.next();
if (stmt.containsInvokeExpr()) {
InvokeExpr invokeExpr = stmt.getInvokeExpr();
List<SootMethod> targetList = new ArrayList<SootMethod>();
SootMethod method = invokeExpr.getMethod();
if (invokeExpr instanceof StaticInvokeExpr) {
targetList.add(method);
} else if (invokeExpr instanceof InstanceInvokeExpr) {
if (method.isConcrete() && !method.getDeclaringClass().isLibraryClass()) {
TargetMethodsFinder tmd = new TargetMethodsFinder();
targetList = tmd.find(stmt, callGraph, true, true);
}
}
if (targetList != null) {
Iterator<SootMethod> iterator = targetList.iterator();
while (iterator.hasNext()) {
SootMethod obj = iterator.next();
if (!obj.isNative()) {
multiCalledMethods.add(obj);
}
}
}
}
}
}
// STEP 4: Is the merge operator union or intersection?
// UNION
protected void merge(BitSet in1, BitSet in2, BitSet out) {
out.clear();
out.or(in1);
out.or(in2);
}
// STEP 5: Define flow equations.
// in(s) = ( out(s) minus defs(s) ) union uses(s)
//
protected void flowThrough(BitSet in, Unit unit, BitSet out) {
out.clear();
out.or(in);
if (!out.get(indexOf(unit))) {
out.set(indexOf(unit));
// System.out.println("add to out: "+unit);
} else {
multiRunStatements.add(unit);
}
// System.out.println("in: "+in);
// System.out.println("out: "+out);
}
protected void copy(BitSet source, BitSet dest) {
dest.clear();
dest.or(source);
}
// STEP 6: Determine value for start/end node, and
// initial approximation.
//
// start node: empty set
// initial approximation: empty set
protected BitSet entryInitialFlow() {
return new BitSet();
}
protected BitSet newInitialFlow() {
return new BitSet();
}
public FlowSet getMultiRunStatements() {
FlowSet res = new ArraySparseSet();
for (Unit u : multiRunStatements) {
res.add(u);
}
return res;
}
protected int indexOf(Object o) {
Integer index = nodeToIndex.get(o);
if (index == null) {
index = lastIndex;
nodeToIndex.put(o, index);
lastIndex++;
}
return index;
}
}
| 5,156
| 28.135593
| 113
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/pegcallgraph/CheckRecursiveCalls.java
|
package soot.jimple.toolkits.thread.mhp.pegcallgraph;
/*-
* #%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 java.util.Set;
import soot.jimple.toolkits.thread.mhp.SCC;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class CheckRecursiveCalls {
List<List> newSccList = null;
public CheckRecursiveCalls(PegCallGraph pcg, Set<Object> methodNeedExtent) {
Iterator it = pcg.iterator();
// PegCallGraphToDot pcgtd = new PegCallGraphToDot(pcg, false, "pegcallgraph");
SCC scc = new SCC(it, pcg);
List<List<Object>> sccList = scc.getSccList();
// printSCC(sccList);
newSccList = updateScc(sccList, pcg);
// System.out.println("after update scc");
// printSCC(newSccList);
check(newSccList, methodNeedExtent);
}
private List<List> updateScc(List<List<Object>> sccList, PegCallGraph pcg) {
List<List> newList = new ArrayList<List>();
Iterator<List<Object>> listIt = sccList.iterator();
while (listIt.hasNext()) {
List s = listIt.next();
if (s.size() == 1) {
Object o = s.get(0);
if ((pcg.getSuccsOf(o)).contains(o) || (pcg.getPredsOf(o)).contains(o)) {
// sccList.remove(s);
newList.add(s);
}
} else {
newList.add(s);
}
}
return newList;
}
private void check(List<List> sccList, Set<Object> methodNeedExtent) {
Iterator<List> listIt = sccList.iterator();
while (listIt.hasNext()) {
List s = listIt.next();
// printSCC(s);
if (s.size() > 0) {
Iterator it = s.iterator();
while (it.hasNext()) {
Object o = it.next();
if (methodNeedExtent.contains(o)) {
// if (((Boolean)methodsNeedingInlining.get(o)).booleanValue() == true){
System.err.println("Fail to compute MHP because interested method call relate to recursive calls!");
System.err.println("interested method: " + o);
throw new RuntimeException("Fail to compute MHP because interested method call relate to recursive calls!");
// }
}
}
}
}
}
}
| 3,352
| 32.868687
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/pegcallgraph/PegCallGraph.java
|
package soot.jimple.toolkits.thread.mhp.pegcallgraph;
/*-
* #%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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.SootMethod;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.toolkits.graph.DirectedGraph;
import soot.util.Chain;
import soot.util.HashChain;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class PegCallGraph implements DirectedGraph {
List heads;
List tails;
Chain chain;
// protected Map methodToSuccs;
// protected Map methodToPreds;
private final Map<Object, List> methodToSuccs;
private final Map<Object, List> methodToPreds;
private final Map<Object, List> methodToSuccsTrim;
private final Set clinitMethods;
public PegCallGraph(CallGraph cg) {
clinitMethods = new HashSet();
chain = new HashChain();
heads = new ArrayList();
tails = new ArrayList();
methodToSuccs = new HashMap();
methodToPreds = new HashMap();
methodToSuccsTrim = new HashMap();
// buildfortest();
buildChainAndSuccs(cg);
// testChain();
// testMethodToSucc();
buildPreds();
// trim(); BROKEN
// testMethodToPred();
// testClinitMethods();
}
protected void testChain() {
System.out.println("******** chain of pegcallgraph********");
Iterator it = chain.iterator();
while (it.hasNext()) {
SootMethod sm = (SootMethod) it.next();
System.out.println(sm);
// System.out.println("name: "+sm.getName());
}
}
public Set getClinitMethods() {
return clinitMethods;
}
private void buildChainAndSuccs(CallGraph cg) {
Iterator it = cg.sourceMethods();
while (it.hasNext()) {
SootMethod sm = (SootMethod) it.next();
if (sm.getName().equals("main")) {
heads.add(sm);
}
// if (sm.isConcrete() && !sm.getDeclaringClass().isLibraryClass()){
// if (sm.hasActiveBody() && sm.getDeclaringClass().isApplicationClass() ){
if (sm.isConcrete() && sm.getDeclaringClass().isApplicationClass()) {
if (!chain.contains(sm)) {
chain.add(sm);
}
List succsList = new ArrayList();
Iterator edgeIt = cg.edgesOutOf(sm);
while (edgeIt.hasNext()) {
Edge edge = (Edge) edgeIt.next();
SootMethod target = edge.tgt();
// if (target.isConcrete() && !target.getDeclaringClass().isLibraryClass()){
// if (target.hasActiveBody() && target.getDeclaringClass().isApplicationClass()){
if (target.isConcrete() && target.getDeclaringClass().isApplicationClass()) {
succsList.add(target);
if (!chain.contains(target)) {
chain.add(target);
// System.out.println("add: "+target);
}
if (edge.isClinit()) {
clinitMethods.add(target);
}
}
}
// if (succsList == null) System.out.println("null succsList");
if (succsList.size() > 0) {
methodToSuccs.put(sm, succsList);
}
}
}
// testChain();
/*
* Because CallGraph.sourceMethods only "Returns an iterator over all methods that are the sources of at least one edge",
* some application methods may not in methodToSuccs. So add them.
*/
{
Iterator chainIt = chain.iterator();
while (chainIt.hasNext()) {
SootMethod sm = (SootMethod) chainIt.next();
if (!methodToSuccs.containsKey(sm)) {
methodToSuccs.put(sm, new ArrayList());
// System.out.println("put: "+sm+"into methodToSuccs");
}
}
}
// remove the entry for those who's preds are null.
{
Iterator chainIt = chain.iterator();
while (it.hasNext()) {
SootMethod s = (SootMethod) chainIt.next();
if (methodToSuccs.containsKey(s)) {
List succList = methodToSuccs.get(s);
if (succList.size() <= 0) {
// methodToSuccs.remove(s);
}
}
}
}
// testMethodToSucc();
// unmodidiable
{
Iterator chainIt = chain.iterator();
while (chainIt.hasNext()) {
SootMethod s = (SootMethod) chainIt.next();
// System.out.println(s);
if (methodToSuccs.containsKey(s)) {
methodToSuccs.put(s, Collections.unmodifiableList(methodToSuccs.get(s)));
}
}
}
}
private void buildPreds() {
// initialize the pred sets to empty
{
Iterator unitIt = chain.iterator();
while (unitIt.hasNext()) {
methodToPreds.put(unitIt.next(), new ArrayList());
}
}
{
Iterator unitIt = chain.iterator();
while (unitIt.hasNext()) {
Object s = unitIt.next();
// Modify preds set for each successor for this statement
List succList = methodToSuccs.get(s);
if (succList.size() > 0) {
Iterator succIt = succList.iterator();
while (succIt.hasNext()) {
Object successor = succIt.next();
List<Object> predList = methodToPreds.get(successor);
// if (predList == null) System.out.println("null predList");
// if (s == null) System.out.println("null s");
try {
predList.add(s);
} catch (NullPointerException e) {
System.out.println(s + "successor: " + successor);
throw e;
}
}
}
}
}
// Make pred lists unmodifiable.
{
Iterator unitIt = chain.iterator();
while (unitIt.hasNext()) {
SootMethod s = (SootMethod) unitIt.next();
if (methodToPreds.containsKey(s)) {
List predList = methodToPreds.get(s);
methodToPreds.put(s, Collections.unmodifiableList(predList));
}
}
}
}
public void trim() {
// If there are multiple edges from one method to another, we only keeps one edge. BROKEN
Set maps = methodToSuccs.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
List list = (List) entry.getValue();
List<Object> newList = new ArrayList<Object>();
Iterator it = list.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (!list.contains(obj)) {
newList.add(obj);
}
}
methodToSuccsTrim.put(entry.getKey(), newList);
}
}
public List getHeads() {
return heads;
}
public List getTails() {
return tails;
}
public List getTrimSuccsOf(Object s) {
if (!methodToSuccsTrim.containsKey(s)) {
return java.util.Collections.EMPTY_LIST;
}
// throw new RuntimeException("Invalid method"+s);
return methodToSuccsTrim.get(s);
}
public List getSuccsOf(Object s) {
if (!methodToSuccs.containsKey(s)) {
return java.util.Collections.EMPTY_LIST;
}
// throw new RuntimeException("Invalid method"+s);
return methodToSuccs.get(s);
}
public List getPredsOf(Object s) {
if (!methodToPreds.containsKey(s)) {
return java.util.Collections.EMPTY_LIST;
}
// throw new RuntimeException("Invalid method"+s);
return methodToPreds.get(s);
}
public Iterator iterator() {
return chain.iterator();
}
public int size() {
return chain.size();
}
protected void testMethodToSucc() {
System.out.println("=====test methodToSucc ");
Set maps = methodToSuccs.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println("---key= " + entry.getKey());
List list = (List) entry.getValue();
if (list.size() > 0) {
System.out.println("**succ set:");
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
System.out.println("=========methodToSucc--ends--------");
}
protected void testMethodToPred() {
System.out.println("=====test methodToPred ");
Set maps = methodToPreds.entrySet();
for (Iterator iter = maps.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println("---key= " + entry.getKey());
List list = (List) entry.getValue();
if (list.size() > 0) {
System.out.println("**pred set:");
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
System.out.println("=========methodToPred--ends--------");
}
}
| 9,900
| 28.467262
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/BeginStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class BeginStmt extends JPegStmt {
public BeginStmt(String obj, String ca, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "begin";
this.caller = ca;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,626
| 30.901961
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/JPegStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.Unit;
import soot.tagkit.AbstractHost;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public abstract class JPegStmt extends AbstractHost
// public class JPegStmt implements CommunicationStmt
// public class JPegStmt extends AbstractStmt implements CommunicationStm
// public class JPegStmt extends AbstractStm
{
protected String object;
protected String name;
protected String caller;
protected Unit unit = null;
protected UnitGraph unitGraph = null;
// add for build dot file
protected SootMethod sootMethod = null;
// end add for build dot file
protected JPegStmt() {
}
protected JPegStmt(String obj, String na, String ca) {
this.object = obj;
this.name = na;
this.caller = ca;
}
protected JPegStmt(String obj, String na, String ca, SootMethod sm) {
this.object = obj;
this.name = na;
this.caller = ca;
this.sootMethod = sm;
}
protected JPegStmt(String obj, String na, String ca, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = na;
this.caller = ca;
this.unitGraph = ug;
this.sootMethod = sm;
}
protected JPegStmt(String obj, String na, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = na;
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
this.sootMethod = sm;
}
protected void setUnit(Unit un) {
unit = un;
}
protected void setUnitGraph(UnitGraph ug) {
unitGraph = ug;
}
public UnitGraph getUnitGraph() {
if (!containUnitGraph()) {
throw new RuntimeException("This statement does not contain UnitGraph!");
}
return unitGraph;
}
public boolean containUnitGraph() {
if (unitGraph == null) {
return false;
} else {
return true;
}
}
public Unit getUnit() {
if (!containUnit()) {
throw new RuntimeException("This statement does not contain Unit!");
}
return unit;
}
public boolean containUnit() {
if (unit == null) {
return false;
} else {
return true;
}
}
public String getObject() {
return object;
}
protected void setObject(String ob) {
object = ob;
}
public String getName() {
return name;
}
protected void setName(String na) {
name = na;
}
public String getCaller() {
return caller;
}
protected void setCaller(String ca) {
caller = ca;
}
public SootMethod getMethod() {
return sootMethod;
}
/*
* public void apply(Switch sw) { ((StmtSwitch) sw).caseCommunicationStmt(this); }
*/
/*
* public Object clone() { if (containUnit()){ } return new JPegStmt(object,name,caller, ); }
*/
public String toString() {
if (sootMethod != null) {
return "(" + getObject() + ", " + getName() + ", " + getCaller() + "," + sootMethod + ")";
} else {
return "(" + getObject() + ", " + getName() + ", " + getCaller() + ")";
}
}
public String testToString() {
if (containUnit()) {
if (sootMethod != null) {
return "(" + getObject() + ", " + getName() + ", " + getCaller() + ", " + getUnit() + "," + sootMethod + ")";
} else {
return "(" + getObject() + ", " + getName() + ", " + getCaller() + ", " + getUnit() + ")";
}
} else {
return "(" + getObject() + ", " + getName() + ", " + getCaller() + ")";
}
}
}
| 4,677
| 23.364583
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/JoinStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class JoinStmt extends JPegStmt
{
public JoinStmt(String obj, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "join";
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,671
| 29.4
| 80
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/MonitorEntryStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class MonitorEntryStmt extends JPegStmt
{
public MonitorEntryStmt(String obj, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "entry";
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
}
public MonitorEntryStmt(String obj, String ca, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "entry";
this.caller = ca;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,868
| 29.145161
| 88
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/MonitorExitStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class MonitorExitStmt extends JPegStmt {
public MonitorExitStmt(String obj, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "exit";
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
}
public MonitorExitStmt(String obj, String ca, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "exit";
this.caller = ca;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,862
| 30.05
| 87
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/NotifiedEntryStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class NotifiedEntryStmt extends JPegStmt {
public NotifiedEntryStmt(String obj, String ca, SootMethod sm) {
this.object = obj;
this.name = "notified-entry";
this.caller = ca;
this.sootMethod = sm;
}
}
| 1,574
| 31.142857
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/NotifyAllStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class NotifyAllStmt extends JPegStmt
{
public NotifyAllStmt(String obj, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "notifyAll";
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,686
| 29.672727
| 85
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/NotifyStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class NotifyStmt extends JPegStmt
{
public NotifyStmt(String obj, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "notify";
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,677
| 29.509091
| 82
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/OtherStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class OtherStmt extends JPegStmt
{
public OtherStmt(String obj, String na, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = na;
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,680
| 29.563636
| 92
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/StartStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1999 Patrick Lam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class StartStmt extends JPegStmt
// public class JPegStmt implements CommunicationStmt
// public class JPegStmt extends AbstractStmt implements CommunicationStm
// public class JPegStmt extends AbstractStm
{
public StartStmt(String obj, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "start";
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,825
| 30.482759
| 81
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/WaitStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class WaitStmt extends JPegStmt {
public WaitStmt(String obj, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "wait";
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| 1,670
| 30.528302
| 80
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/mhp/stmt/WaitingStmt.java
|
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%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.SootMethod;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class WaitingStmt extends JPegStmt {
public WaitingStmt(String obj, String ca, SootMethod sm) {
this.object = obj;
this.name = "waiting";
this.caller = ca;
this.sootMethod = sm;
}
}
| 1,555
| 30.755102
| 72
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/CriticalSection.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.HashMap;
import java.util.HashSet;
import java.util.List;
import soot.EquivalentValue;
import soot.MethodOrMethodContext;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.toolkits.pointer.CodeBlockRWSet;
class CriticalSection extends SynchronizedRegion {
public static int nextIDNum = 1;
// Information about the transactional region
public int IDNum;
public int nestLevel;
public String name;
public Value origLock;
public CodeBlockRWSet read, write;
public HashSet<Unit> invokes;
public HashSet<Unit> units;
public HashMap<Unit, CodeBlockRWSet> unitToRWSet;
public HashMap<Unit, List> unitToUses; // For lockset analysis
public boolean wholeMethod;
// Information for analyzing conflicts with other transactions
public SootMethod method;
public int setNumber; // used for breaking the list of transactions into sets
public CriticalSectionGroup group;
public HashSet<CriticalSectionDataDependency> edges;
public HashSet<Unit> waits;
public HashSet<Unit> notifys;
public HashSet<MethodOrMethodContext> transitiveTargets;
// Locking Information
public Value lockObject;
public Value lockObjectArrayIndex;
public List<EquivalentValue> lockset;
CriticalSection(boolean wholeMethod, SootMethod method, int nestLevel) {
super();
this.IDNum = nextIDNum;
nextIDNum++;
this.nestLevel = nestLevel;
this.read = new CodeBlockRWSet();
this.write = new CodeBlockRWSet();
this.invokes = new HashSet<Unit>();
this.units = new HashSet<Unit>();
this.unitToRWSet = new HashMap<Unit, CodeBlockRWSet>();
this.unitToUses = new HashMap<Unit, List>();
this.wholeMethod = wholeMethod;
this.method = method;
this.setNumber = 0; // 0 = no group, -1 = DELETE
this.group = null;
this.edges = new HashSet<CriticalSectionDataDependency>();
this.waits = new HashSet<Unit>();
this.notifys = new HashSet<Unit>();
this.transitiveTargets = null;
this.lockObject = null;
this.lockObjectArrayIndex = null;
this.lockset = null;
}
CriticalSection(CriticalSection tn) {
super(tn);
this.IDNum = tn.IDNum;
this.nestLevel = tn.nestLevel;
this.origLock = tn.origLock;
this.read = new CodeBlockRWSet();
this.read.union(tn.read);
this.write = new CodeBlockRWSet();
this.write.union(tn.write);
this.invokes = (HashSet<Unit>) tn.invokes.clone();
this.units = (HashSet<Unit>) tn.units.clone();
this.unitToRWSet = (HashMap<Unit, CodeBlockRWSet>) tn.unitToRWSet.clone();
this.unitToUses = (HashMap<Unit, List>) tn.unitToUses.clone();
this.wholeMethod = tn.wholeMethod;
this.method = tn.method;
this.setNumber = tn.setNumber;
this.group = tn.group;
this.edges = (HashSet<CriticalSectionDataDependency>) tn.edges.clone();
this.waits = (HashSet<Unit>) tn.waits.clone();
this.notifys = (HashSet<Unit>) tn.notifys.clone();
this.transitiveTargets
= (HashSet<MethodOrMethodContext>) (tn.transitiveTargets == null ? null : tn.transitiveTargets.clone());
this.lockObject = tn.lockObject;
this.lockObjectArrayIndex = tn.lockObjectArrayIndex;
this.lockset = tn.lockset;
}
protected Object clone() {
return new CriticalSection(this);
}
public String toString() {
return name;
}
}
| 4,203
| 32.632
| 112
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/CriticalSectionAwareSideEffectAnalysis.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.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import soot.Local;
import soot.MethodOrMethodContext;
import soot.PointsToAnalysis;
import soot.PointsToSet;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.SootFieldRef;
import soot.SootMethod;
import soot.Type;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.NewExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Filter;
import soot.jimple.toolkits.callgraph.TransitiveTargets;
import soot.jimple.toolkits.pointer.CodeBlockRWSet;
import soot.jimple.toolkits.pointer.FullObjectSet;
import soot.jimple.toolkits.pointer.RWSet;
import soot.jimple.toolkits.pointer.SideEffectAnalysis;
import soot.jimple.toolkits.pointer.StmtRWSet;
import soot.jimple.toolkits.thread.EncapsulatedObjectAnalysis;
import soot.jimple.toolkits.thread.ThreadLocalObjectsAnalysis;
/**
* Generates side-effect information from a PointsToAnalysis. Uses various heuristic rules to filter out side-effects that
* are not visible to other threads in a Transactional program.
*/
class WholeObject {
Type type;
public WholeObject(Type type) {
this.type = type;
}
public WholeObject() {
this.type = null;
}
public String toString() {
return "All Fields" + (type == null ? "" : " (" + type + ")");
}
public int hashCode() {
if (type == null) {
return 1;
}
return type.hashCode();
}
public boolean equals(Object o) {
if (type == null) {
return true;
}
if (o instanceof WholeObject) {
WholeObject other = (WholeObject) o;
if (other.type == null) {
return true;
} else {
return (type == other.type);
}
} else if (o instanceof FieldRef) {
return type == ((FieldRef) o).getType();
} else if (o instanceof SootFieldRef) {
return type == ((SootFieldRef) o).type();
} else if (o instanceof SootField) {
return type == ((SootField) o).getType();
} else {
return true;
}
}
}
public class CriticalSectionAwareSideEffectAnalysis {
PointsToAnalysis pa;
CallGraph cg;
Map<SootMethod, CodeBlockRWSet> methodToNTReadSet = new HashMap<SootMethod, CodeBlockRWSet>();
Map<SootMethod, CodeBlockRWSet> methodToNTWriteSet = new HashMap<SootMethod, CodeBlockRWSet>();
int rwsetcount = 0;
CriticalSectionVisibleEdgesPred tve;
TransitiveTargets tt;
TransitiveTargets normaltt;
SideEffectAnalysis normalsea;
Collection<CriticalSection> criticalSections;
EncapsulatedObjectAnalysis eoa;
ThreadLocalObjectsAnalysis tlo;
public Vector sigBlacklist;
public Vector sigReadGraylist;
public Vector sigWriteGraylist;
public Vector subSigBlacklist;
public void findNTRWSets(SootMethod method) {
if (methodToNTReadSet.containsKey(method) && methodToNTWriteSet.containsKey(method)) {
return;
}
CodeBlockRWSet read = null;
CodeBlockRWSet write = null;
for (Iterator sIt = method.retrieveActiveBody().getUnits().iterator(); sIt.hasNext();) {
final Stmt s = (Stmt) sIt.next();
boolean ignore = false;
// Ignore Reads/Writes inside another transaction
if (criticalSections != null) {
Iterator<CriticalSection> tnIt = criticalSections.iterator();
while (tnIt.hasNext()) {
CriticalSection tn = tnIt.next();
if (tn.units.contains(s) || tn.prepStmt == s) {
ignore = true;
break;
}
}
}
if (!ignore) {
RWSet ntr = ntReadSet(method, s);
if (ntr != null) {
if (read == null) {
read = new CodeBlockRWSet();
}
read.union(ntr);
}
RWSet ntw = ntWriteSet(method, s);
if (ntw != null) {
if (write == null) {
write = new CodeBlockRWSet();
}
write.union(ntw);
}
if (s.containsInvokeExpr()) {
InvokeExpr ie = s.getInvokeExpr();
SootMethod calledMethod = ie.getMethod();
// if it's an invoke on certain lib methods
if (calledMethod.getDeclaringClass().toString().startsWith("java.util")
|| calledMethod.getDeclaringClass().toString().startsWith("java.lang")) {
// then it gets approximated
Local base = null;
if (ie instanceof InstanceInvokeExpr) {
base = (Local) ((InstanceInvokeExpr) ie).getBase();
}
if (tlo == null || base == null || !tlo.isObjectThreadLocal(base, method)) {
// add its approximated read set to read
RWSet r;
// String InvokeSig = calledMethod.getSubSignature();
// if( InvokeSig.equals("void notify()") || InvokeSig.equals("void notifyAll()") ||
// InvokeSig.equals("void wait()") || InvokeSig.equals("void wait(long)") || InvokeSig.equals("void
// wait(long,int)"))
// r = approximatedReadSet(method, s, base, true);
// else
r = approximatedReadSet(method, s, base, true);
if (read == null) {
read = new CodeBlockRWSet();
}
if (r != null) {
read.union(r);
}
// add its approximated write set to write
RWSet w;
// if( InvokeSig.equals("void notify()") || InvokeSig.equals("void notifyAll()") ||
// InvokeSig.equals("void wait()") || InvokeSig.equals("void wait(long)") || InvokeSig.equals("void
// wait(long,int)"))
// w = approximatedWriteSet(method, s, base, true);
// else
w = approximatedWriteSet(method, s, base, true);
if (write == null) {
write = new CodeBlockRWSet();
}
if (w != null) {
write.union(w);
}
}
}
}
}
}
methodToNTReadSet.put(method, read);
methodToNTWriteSet.put(method, write);
}
public void setExemptTransaction(CriticalSection tn) {
tve.setExemptTransaction(tn);
}
public RWSet nonTransitiveReadSet(SootMethod method) {
findNTRWSets(method);
return methodToNTReadSet.get(method);
}
public RWSet nonTransitiveWriteSet(SootMethod method) {
findNTRWSets(method);
return methodToNTWriteSet.get(method);
}
public CriticalSectionAwareSideEffectAnalysis(PointsToAnalysis pa, CallGraph cg,
Collection<CriticalSection> criticalSections, ThreadLocalObjectsAnalysis tlo) {
this.pa = pa;
this.cg = cg;
this.tve = new CriticalSectionVisibleEdgesPred(criticalSections);
this.tt = new TransitiveTargets(cg, new Filter(tve));
this.normaltt = new TransitiveTargets(cg, null);
this.normalsea = new SideEffectAnalysis(pa, cg);
this.criticalSections = criticalSections;
this.eoa = new EncapsulatedObjectAnalysis();
this.tlo = tlo; // can be null
sigBlacklist = new Vector(); // Signatures of methods known to have effective read/write sets of size 0
// Math does not have any synchronization risks, we think :-)
/*
* sigBlacklist.add("<java.lang.Math: double abs(double)>");
* sigBlacklist.add("<java.lang.Math: double min(double,double)>");
* sigBlacklist.add("<java.lang.Math: double sqrt(double)>");
* sigBlacklist.add("<java.lang.Math: double pow(double,double)>"); //
*/
// sigBlacklist.add("");
sigReadGraylist = new Vector(); // Signatures of methods whose effects must be approximated
sigWriteGraylist = new Vector();
/*
* sigReadGraylist.add("<java.util.Vector: boolean remove(java.lang.Object)>");
* sigWriteGraylist.add("<java.util.Vector: boolean remove(java.lang.Object)>");
*
* sigReadGraylist.add("<java.util.Vector: boolean add(java.lang.Object)>");
* sigWriteGraylist.add("<java.util.Vector: boolean add(java.lang.Object)>");
*
* sigReadGraylist.add("<java.util.Vector: java.lang.Object clone()>"); //
* sigWriteGraylist.add("<java.util.Vector: java.lang.Object clone()>");
*
* sigReadGraylist.add("<java.util.Vector: java.lang.Object get(int)>"); //
* sigWriteGraylist.add("<java.util.Vector: java.lang.Object get(int)>");
*
* sigReadGraylist.add("<java.util.Vector: java.util.List subList(int,int)>"); //
* sigWriteGraylist.add("<java.util.Vector: java.util.List subList(int,int)>");
*
* sigReadGraylist.add("<java.util.List: void clear()>"); sigWriteGraylist.add("<java.util.List: void clear()>"); //
*/
subSigBlacklist = new Vector(); // Subsignatures of methods on all objects known to have read/write sets of size 0
/*
* subSigBlacklist.add("java.lang.Class class$(java.lang.String)"); subSigBlacklist.add("void notify()");
* subSigBlacklist.add("void notifyAll()"); subSigBlacklist.add("void wait()"); subSigBlacklist.add("void <clinit>()");
* //
*/
}
private RWSet ntReadSet(SootMethod method, Stmt stmt) {
if (stmt instanceof AssignStmt) {
AssignStmt a = (AssignStmt) stmt;
Value r = a.getRightOp();
if (r instanceof NewExpr) {
return null;
}
return addValue(r, method, stmt);
}
return null;
}
private HashMap<Stmt, RWSet> RCache = new HashMap<Stmt, RWSet>();
public RWSet approximatedReadSet(SootMethod method, Stmt stmt, Value specialRead, boolean allFields) { // used for stmts
// with method calls
// where the
// effect of the
// method call
// should be
// approximated by 0
// or 1 reads (plus
// reads
// of
// all args)
CodeBlockRWSet ret = new CodeBlockRWSet();
if (specialRead != null) {
if (specialRead instanceof Local) {
Local vLocal = (Local) specialRead;
PointsToSet base = pa.reachingObjects(vLocal);
// Get an RWSet containing all fields
// Set possibleTypes = base.possibleTypes();
// for(Iterator pTypeIt = possibleTypes.iterator(); pTypeIt.hasNext(); )
// {
Type pType = vLocal.getType(); // (Type) pTypeIt.next();
if (pType instanceof RefType) {
SootClass baseTypeClass = ((RefType) pType).getSootClass();
if (!baseTypeClass.isInterface()) {
List<SootClass> baseClasses = Scene.v().getActiveHierarchy().getSuperclassesOfIncluding(baseTypeClass);
if (!baseClasses.contains(RefType.v("java.lang.Exception").getSootClass())) {
for (SootClass baseClass : baseClasses) {
for (Iterator baseFieldIt = baseClass.getFields().iterator(); baseFieldIt.hasNext();) {
SootField baseField = (SootField) baseFieldIt.next();
if (!baseField.isStatic()) {
ret.addFieldRef(base, baseField);
}
}
}
}
}
}
// }
// If desired, prune to just actually-read fields
if (!allFields) {
// Should actually get a list of fields of this object that are read/written
// make fake RW set of <base, all fields> (use a special class)
// intersect with the REAL RW set of this stmt
CodeBlockRWSet allRW = ret;
ret = new CodeBlockRWSet();
RWSet normalRW;
if (RCache.containsKey(stmt)) {
normalRW = RCache.get(stmt);
} else {
normalRW = normalsea.readSet(method, stmt);
RCache.put(stmt, normalRW);
}
if (normalRW != null) {
for (Iterator fieldsIt = normalRW.getFields().iterator(); fieldsIt.hasNext();) {
Object field = fieldsIt.next();
if (allRW.containsField(field)) {
PointsToSet otherBase = normalRW.getBaseForField(field);
if (otherBase instanceof FullObjectSet) {
ret.addFieldRef(otherBase, field);
} else {
if (base.hasNonEmptyIntersection(otherBase)) {
ret.addFieldRef(base, field); // should use intersection of bases!!!
}
}
}
}
}
}
} else if (specialRead instanceof FieldRef) {
ret.union(addValue(specialRead, method, stmt));
}
}
if (stmt.containsInvokeExpr()) {
int argCount = stmt.getInvokeExpr().getArgCount();
for (int i = 0; i < argCount; i++) {
ret.union(addValue(stmt.getInvokeExpr().getArg(i), method, stmt));
}
}
if (stmt instanceof AssignStmt) {
AssignStmt a = (AssignStmt) stmt;
Value r = a.getRightOp();
ret.union(addValue(r, method, stmt));
}
return ret;
}
public RWSet readSet(SootMethod method, Stmt stmt, CriticalSection tn, Set uses) {
boolean ignore = false;
if (stmt.containsInvokeExpr()) {
InvokeExpr ie = stmt.getInvokeExpr();
SootMethod calledMethod = ie.getMethod();
if (ie instanceof StaticInvokeExpr) {
// ignore = false;
} else if (ie instanceof InstanceInvokeExpr) {
if (calledMethod.getSubSignature().startsWith("void <init>") && eoa.isInitMethodPureOnObject(calledMethod)) {
ignore = true;
} else if (tlo != null && !tlo.hasNonThreadLocalEffects(method, ie)) {
ignore = true;
}
}
}
boolean inaccessibleUses = false;
RWSet ret = new CodeBlockRWSet();
tve.setExemptTransaction(tn);
Iterator<MethodOrMethodContext> targets = tt.iterator(stmt);
while (!ignore && targets.hasNext()) {
SootMethod target = (SootMethod) targets.next();
// if( target.isNative() ) {
// if( ret == null ) ret = new SiteRWSet();
// ret.setCallsNative();
// } else
if (target.isConcrete()) {
// Special treatment for java.util and java.lang... their children are filtered out by the ThreadVisibleEdges filter
// An approximation of their behavior must be performed here
if (target.getDeclaringClass().toString().startsWith("java.util")
|| target.getDeclaringClass().toString().startsWith("java.lang")) {
/*
* RWSet ntr; if(stmt.getInvokeExpr() instanceof InstanceInvokeExpr) { Local base =
* (Local)((InstanceInvokeExpr)stmt.getInvokeExpr()).getBase();
*
* // Add base object and args to set of possibly contributing uses at this stmt if(!inaccessibleUses) {
* uses.add(base); int argCount = stmt.getInvokeExpr().getArgCount(); for(int i = 0; i < argCount; i++) {
* if(addValue( stmt.getInvokeExpr().getArg(i), method, stmt ) != null) uses.add(stmt.getInvokeExpr().getArg(i)); }
* }
*
* // Add base object to read set String InvokeSig = target.getSubSignature(); if(
* InvokeSig.equals("void notify()") || InvokeSig.equals("void notifyAll()") || InvokeSig.equals("void wait()") ||
* InvokeSig.equals("void wait(long)") || InvokeSig.equals("void wait(long,int)")) { ntr =
* approximatedReadSet(method, stmt, base, target, true); } else { ntr = approximatedReadSet(method, stmt, base,
* target, false); } } else { ntr = approximatedReadSet(method, stmt, null, target, false); } ret.union(ntr);
*/ } else { // note that all library functions have already been filtered out (by name) via the filter
// passed to the TransitiveTargets constructor.
RWSet ntr = nonTransitiveReadSet(target);
if (ntr != null) {
// uses.clear();
// inaccessibleUses = true;
ret.union(ntr);
}
}
}
}
RWSet ntr = ntReadSet(method, stmt);
if (inaccessibleUses == false && ntr != null && stmt instanceof AssignStmt) {
AssignStmt a = (AssignStmt) stmt;
Value r = a.getRightOp();
if (r instanceof InstanceFieldRef) {
uses.add(((InstanceFieldRef) r).getBase());
} else if (r instanceof StaticFieldRef) {
uses.add(r);
} else if (r instanceof ArrayRef) {
uses.add(((ArrayRef) r).getBase());
}
}
ret.union(ntr);
if (stmt.containsInvokeExpr()) {
InvokeExpr ie = stmt.getInvokeExpr();
SootMethod calledMethod = ie.getMethod();
// if it's an invoke on certain lib methods
if (calledMethod.getDeclaringClass().toString().startsWith("java.util")
|| calledMethod.getDeclaringClass().toString().startsWith("java.lang")) {
// then it gets approximated as a NTReadSet
Local base = null;
if (ie instanceof InstanceInvokeExpr) {
base = (Local) ((InstanceInvokeExpr) ie).getBase();
}
if (tlo == null || base == null || !tlo.isObjectThreadLocal(base, method)) {
// add its approximated read set to read
RWSet r;
// String InvokeSig = calledMethod.getSubSignature();
// if( InvokeSig.equals("void notify()") || InvokeSig.equals("void notifyAll()") ||
// InvokeSig.equals("void wait()") || InvokeSig.equals("void wait(long)") || InvokeSig.equals("void
// wait(long,int)"))
// r = approximatedReadSet(method, stmt, base, true);
// else
r = approximatedReadSet(method, stmt, base, true);
if (r != null) {
ret.union(r);
}
int argCount = stmt.getInvokeExpr().getArgCount();
for (int i = 0; i < argCount; i++) {
uses.add(ie.getArg(i));
}
if (base != null) {
uses.add(base);
}
}
}
}
return ret;
}
private RWSet ntWriteSet(SootMethod method, Stmt stmt) {
if (stmt instanceof AssignStmt) {
AssignStmt a = (AssignStmt) stmt;
Value l = a.getLeftOp();
return addValue(l, method, stmt);
}
return null;
}
private HashMap<Stmt, RWSet> WCache = new HashMap<Stmt, RWSet>();
public RWSet approximatedWriteSet(SootMethod method, Stmt stmt, Value v, boolean allFields) { // used for stmts with method
// calls where the effect
// of
// the method call should be
// approximated by 0 or 1
// writes
CodeBlockRWSet ret = new CodeBlockRWSet();
if (v != null) {
if (v instanceof Local) {
Local vLocal = (Local) v;
PointsToSet base = pa.reachingObjects(vLocal);
// Get an RWSet containing all fields
// Set possibleTypes = base.possibleTypes();
// for(Iterator pTypeIt = possibleTypes.iterator(); pTypeIt.hasNext(); )
// {
Type pType = vLocal.getType(); // (Type) pTypeIt.next();
if (pType instanceof RefType) {
SootClass baseTypeClass = ((RefType) pType).getSootClass();
if (!baseTypeClass.isInterface()) {
List<SootClass> baseClasses = Scene.v().getActiveHierarchy().getSuperclassesOfIncluding(baseTypeClass);
if (!baseClasses.contains(RefType.v("java.lang.Exception").getSootClass())) {
for (SootClass baseClass : baseClasses) {
for (Iterator baseFieldIt = baseClass.getFields().iterator(); baseFieldIt.hasNext();) {
SootField baseField = (SootField) baseFieldIt.next();
if (!baseField.isStatic()) {
ret.addFieldRef(base, baseField);
}
}
}
}
}
}
// }
// If desired, prune to just actually-written fields
if (!allFields) {
// Should actually get a list of fields of this object that are read/written
// make fake RW set of <base, all fields> (use a special class)
// intersect with the REAL RW set of this stmt
CodeBlockRWSet allRW = ret;
ret = new CodeBlockRWSet();
RWSet normalRW;
if (WCache.containsKey(stmt)) {
normalRW = WCache.get(stmt);
} else {
normalRW = normalsea.writeSet(method, stmt);
WCache.put(stmt, normalRW);
}
if (normalRW != null) {
for (Iterator fieldsIt = normalRW.getFields().iterator(); fieldsIt.hasNext();) {
Object field = fieldsIt.next();
if (allRW.containsField(field)) {
PointsToSet otherBase = normalRW.getBaseForField(field);
if (otherBase instanceof FullObjectSet) {
ret.addFieldRef(otherBase, field);
} else {
if (base.hasNonEmptyIntersection(otherBase)) {
ret.addFieldRef(base, field); // should use intersection of bases!!!
}
}
}
}
}
}
} else if (v instanceof FieldRef) {
ret.union(addValue(v, method, stmt));
}
}
if (stmt instanceof AssignStmt) {
AssignStmt a = (AssignStmt) stmt;
Value l = a.getLeftOp();
ret.union(addValue(l, method, stmt));
}
return ret;
}
public RWSet writeSet(SootMethod method, Stmt stmt, CriticalSection tn, Set uses) {
boolean ignore = false;
if (stmt.containsInvokeExpr()) {
InvokeExpr ie = stmt.getInvokeExpr();
SootMethod calledMethod = ie.getMethod();
if (ie instanceof StaticInvokeExpr) {
// ignore = false;
} else if (ie instanceof InstanceInvokeExpr) {
if (calledMethod.getSubSignature().startsWith("void <init>") && eoa.isInitMethodPureOnObject(calledMethod)) {
ignore = true;
} else if (tlo != null && !tlo.hasNonThreadLocalEffects(method, ie)) {
ignore = true;
}
}
}
boolean inaccessibleUses = false;
RWSet ret = new CodeBlockRWSet();
tve.setExemptTransaction(tn);
Iterator<MethodOrMethodContext> targets = tt.iterator(stmt);
while (!ignore && targets.hasNext()) {
SootMethod target = (SootMethod) targets.next();
// if( target.isNative() ) {
// if( ret == null ) ret = new SiteRWSet();
// ret.setCallsNative();
// } else
if (target.isConcrete()) {
if (target.getDeclaringClass().toString().startsWith("java.util")
|| target.getDeclaringClass().toString().startsWith("java.lang")) {
/*
* RWSet ntw; if(stmt.getInvokeExpr() instanceof InstanceInvokeExpr) { Local base =
* (Local)((InstanceInvokeExpr)stmt.getInvokeExpr()).getBase();
*
* // Add base object to set of possibly contributing uses at this stmt if(!inaccessibleUses) uses.add(base);
*
* // Add base object to write set String InvokeSig = target.getSubSignature(); if(
* InvokeSig.equals("void notify()") || InvokeSig.equals("void notifyAll()") || InvokeSig.equals("void wait()") ||
* InvokeSig.equals("void wait(long)") || InvokeSig.equals("void wait(long,int)")) { ntw =
* approximatedWriteSet(method, stmt, base, true); } else { ntw = approximatedWriteSet(method, stmt, base, false);
* } } else { ntw = approximatedWriteSet(method, stmt, null, false); } ret.union(ntw);
*/
} else {
RWSet ntw = nonTransitiveWriteSet(target);
if (ntw != null) {
// inaccessibleUses = true;
// uses.clear();
ret.union(ntw);
}
}
}
}
RWSet ntw = ntWriteSet(method, stmt);
if (!inaccessibleUses && ntw != null && stmt instanceof AssignStmt) {
AssignStmt a = (AssignStmt) stmt;
Value l = a.getLeftOp();
if (l instanceof InstanceFieldRef) {
uses.add(((InstanceFieldRef) l).getBase());
} else if (l instanceof StaticFieldRef) {
uses.add(l);
} else if (l instanceof ArrayRef) {
uses.add(((ArrayRef) l).getBase());
}
}
ret.union(ntw);
if (stmt.containsInvokeExpr()) {
InvokeExpr ie = stmt.getInvokeExpr();
SootMethod calledMethod = ie.getMethod();
// if it's an invoke on certain lib methods
if (calledMethod.getDeclaringClass().toString().startsWith("java.util")
|| calledMethod.getDeclaringClass().toString().startsWith("java.lang")) {
// then it gets approximated as a NTReadSet
Local base = null;
if (ie instanceof InstanceInvokeExpr) {
base = (Local) ((InstanceInvokeExpr) ie).getBase();
}
if (tlo == null || base == null || !tlo.isObjectThreadLocal(base, method)) {
// add its approximated read set to read
RWSet w;
// String InvokeSig = calledMethod.getSubSignature();
// if( InvokeSig.equals("void notify()") || InvokeSig.equals("void notifyAll()") ||
// InvokeSig.equals("void wait()") || InvokeSig.equals("void wait(long)") || InvokeSig.equals("void
// wait(long,int)"))
// w = approximatedWriteSet(method, stmt, base, true);
// else
w = approximatedWriteSet(method, stmt, base, true);
if (w != null) {
ret.union(w);
}
if (base != null) {
uses.add(base);
}
}
}
}
return ret;
}
public RWSet valueRWSet(Value v, SootMethod m, Stmt s, CriticalSection tn) {
RWSet ret = null;
if (tlo != null) {
// fields/elements of local objects may be read/written w/o visible
// side effects if the base object is local, or if the base is "this"
// and the field itself is local (since "this" is always assumed shared)
if (v instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) v;
if (m.isConcrete() && !m.isStatic() && m.retrieveActiveBody().getThisLocal().equivTo(ifr.getBase())
&& tlo.isObjectThreadLocal(ifr, m)) {
return null;
} else if (tlo.isObjectThreadLocal(ifr.getBase(), m)) {
return null;
}
} else if (v instanceof ArrayRef && tlo.isObjectThreadLocal(((ArrayRef) v).getBase(), m)) {
return null;
}
}
if (v instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) v;
PointsToSet base = pa.reachingObjects((Local) ifr.getBase());
ret = new StmtRWSet();
ret.addFieldRef(base, ifr.getField());
} else if (v instanceof StaticFieldRef) {
StaticFieldRef sfr = (StaticFieldRef) v;
ret = new StmtRWSet();
ret.addGlobal(sfr.getField());
} else if (v instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) v;
PointsToSet base = pa.reachingObjects((Local) ar.getBase());
ret = new StmtRWSet();
ret.addFieldRef(base, PointsToAnalysis.ARRAY_ELEMENTS_NODE);
} else if (v instanceof Local) {
Local vLocal = (Local) v;
PointsToSet base = pa.reachingObjects(vLocal);
ret = new CodeBlockRWSet();
CodeBlockRWSet stmtRW = new CodeBlockRWSet();
RWSet rSet = readSet(m, s, tn, new HashSet());
if (rSet != null) {
stmtRW.union(rSet);
}
RWSet wSet = writeSet(m, s, tn, new HashSet());
if (wSet != null) {
stmtRW.union(wSet);
}
// Should actually get a list of fields of this object that are read/written
// make fake RW set of <base, all fields> (use a special class)
// intersect with the REAL RW set of this stmt
for (Iterator fieldsIt = stmtRW.getFields().iterator(); fieldsIt.hasNext();) {
Object field = fieldsIt.next();
PointsToSet fieldBase = stmtRW.getBaseForField(field);
if (base.hasNonEmptyIntersection(fieldBase)) {
ret.addFieldRef(base, field); // should use intersection of bases!!!
}
}
} else {
return null;
}
return ret;
}
protected RWSet addValue(Value v, SootMethod m, Stmt s) {
RWSet ret = null;
if (tlo != null) {
// fields/elements of local objects may be read/written w/o visible
// side effects if the base object is local, or if the base is "this"
// and the field itself is local (since "this" is always assumed shared)
if (v instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) v;
if (m.isConcrete() && !m.isStatic() && m.retrieveActiveBody().getThisLocal().equivTo(ifr.getBase())
&& tlo.isObjectThreadLocal(ifr, m)) {
return null;
} else if (tlo.isObjectThreadLocal(ifr.getBase(), m)) {
return null;
}
} else if (v instanceof ArrayRef && tlo.isObjectThreadLocal(((ArrayRef) v).getBase(), m)) {
return null;
}
}
// if(tlo != null &&
// (( v instanceof InstanceFieldRef && tlo.isObjectThreadLocal(((InstanceFieldRef)v).getBase(), m) ) ||
// ( v instanceof ArrayRef && tlo.isObjectThreadLocal(((ArrayRef)v).getBase(), m) )))
// return null;
if (v instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) v;
Local baseLocal = (Local) ifr.getBase();
PointsToSet base = pa.reachingObjects(baseLocal);
if (baseLocal.getType() instanceof RefType) {
SootClass baseClass = ((RefType) baseLocal.getType()).getSootClass();
if (Scene.v().getActiveHierarchy().isClassSubclassOfIncluding(baseClass,
RefType.v("java.lang.Exception").getSootClass())) {
return null;
}
}
ret = new StmtRWSet();
ret.addFieldRef(base, ifr.getField());
} else if (v instanceof StaticFieldRef) {
StaticFieldRef sfr = (StaticFieldRef) v;
ret = new StmtRWSet();
ret.addGlobal(sfr.getField());
} else if (v instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) v;
PointsToSet base = pa.reachingObjects((Local) ar.getBase());
ret = new StmtRWSet();
ret.addFieldRef(base, PointsToAnalysis.ARRAY_ELEMENTS_NODE);
}
return ret;
}
public String toString() {
return "TransactionAwareSideEffectAnalysis: PA=" + pa + " CG=" + cg;
}
}
| 32,681
| 39.100613
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/thread/synchronization/CriticalSectionDataDependency.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.jimple.toolkits.pointer.RWSet;
class CriticalSectionDataDependency {
public CriticalSection other;
public int size;
public RWSet rw;
CriticalSectionDataDependency(CriticalSection other, int size, RWSet rw) {
this.other = other;
this.size = size;
this.rw = rw;
}
}
| 1,172
| 29.868421
| 76
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.