Java源码示例:soot.jimple.JimpleBody
示例1
private TypeResolver(JimpleBody stmtBody, Scene scene)
{
this.stmtBody = stmtBody;
hierarchy = ClassHierarchy.classHierarchy(scene);
OBJECT = hierarchy.OBJECT;
NULL = hierarchy.NULL;
typeVariable(OBJECT);
typeVariable(NULL);
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
typeVariable(hierarchy.CLONEABLE);
typeVariable(hierarchy.SERIALIZABLE);
}
}
示例2
private boolean typingFailed(JimpleBody b) {
// Check to see if any locals are untyped
{
Iterator<Local> localIt = b.getLocals().iterator();
while (localIt.hasNext()) {
Local l = localIt.next();
if (l.getType().equals(UnknownType.v())
|| l.getType().equals(ErroneousType.v())) {
return true;
}
}
}
return false;
}
示例3
private TypeResolverBV(JimpleBody stmtBody, Scene scene)
{
this.stmtBody = stmtBody;
hierarchy = ClassHierarchy.classHierarchy(scene);
OBJECT = hierarchy.OBJECT;
NULL = hierarchy.NULL;
typeVariable(OBJECT);
typeVariable(NULL);
// hack for J2ME library, reported by Stephen Cheng
if (!Options.v().j2me()) {
typeVariable(hierarchy.CLONEABLE);
typeVariable(hierarchy.SERIALIZABLE);
}
}
示例4
/**
* Gets the baf body for the given SootMethod. This method will first check
* whether the method already has a baf body. If not, it will query the local
* cache. If this fails as well, it will construct a new baf body.
* @param method The method for which to obtain a baf body
* @return The baf body for the given method
*/
protected BafBody getBafBody(SootMethod method) {
final Body activeBody = method.getActiveBody();
if (activeBody instanceof BafBody)
return (BafBody) activeBody;
BafBody body = bafBodyCache.get(method);
if (body != null)
return body;
if (activeBody instanceof JimpleBody) {
body = PackManager.v().convertJimpleBodyToBaf(method);
} else {
throw new RuntimeException(
"ASM-backend can only translate Baf- and JimpleBodies!");
}
bafBodyCache.put(method, body);
return body;
}
示例5
private String getTargetClass() {
SootClass sootClass = new SootClass("dummyClass");
Type paramType = ArrayType.v(RefType.v("java.lang.String"), 1);
SootMethod mainMethod = new SootMethod("main", Collections.singletonList(paramType), VoidType.v(),
Modifier.PUBLIC | Modifier.STATIC);
sootClass.addMethod(mainMethod);
JimpleBody body = Jimple.v().newBody(mainMethod);
mainMethod.setActiveBody(body);
RefType testCaseType = RefType.v(getTestCaseClassName());
Local loc = Jimple.v().newLocal("l0", paramType);
body.getLocals().add(loc);
body.getUnits().add(Jimple.v().newIdentityStmt(loc, Jimple.v().newParameterRef(paramType, 0)));
Local allocatedTestObj = Jimple.v().newLocal("dummyObj", testCaseType);
body.getLocals().add(allocatedTestObj);
body.getUnits().add(Jimple.v().newAssignStmt(allocatedTestObj, Jimple.v().newNewExpr(testCaseType)));
body.getUnits().add(
Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(allocatedTestObj, sootTestMethod.makeRef())));
body.getUnits().add(Jimple.v().newReturnVoidStmt());
Scene.v().addClass(sootClass);
body.validate();
return sootClass.toString();
}
示例6
private static Map/*<Integer,Local>*/ getLocals(SootClass sc, String methodname, String typename) {
Map res = new HashMap();
Iterator mi = sc.getMethods().iterator();
while (mi.hasNext()) {
SootMethod sm = (SootMethod)mi.next();
System.err.println(sm.getName());
if (true && sm.getName().equals(methodname) && sm.isConcrete()) {
JimpleBody jb = (JimpleBody)sm.retrieveActiveBody();
Iterator ui = jb.getUnits().iterator();
while (ui.hasNext()) {
Stmt s = (Stmt)ui.next();
int line = getLineNumber(s);
// find definitions
Iterator bi = s.getDefBoxes().iterator();
while (bi.hasNext()) {
Object o = bi.next();
if (o instanceof ValueBox) {
Value v = ((ValueBox)o).getValue();
if (v.getType().toString().equals(typename) && v instanceof Local)
res.put(new Integer(line),v);
}
}
}
}
}
return res;
}
示例7
private void stashBodiesForClass(SootClass sc)
{
methodToParsedBodyMap = new HashMap<SootMethod, JimpleBody>();
Walker w = new BodyExtractorWalker(sc, SootResolver.v(), methodToParsedBodyMap);
boolean oldPhantomValue = Scene.v().getPhantomRefs();
Scene.v().setPhantomRefs(true);
mTree.apply(w);
Scene.v().setPhantomRefs(oldPhantomValue);
}
示例8
public TypeResolver(JimpleBody jb)
{
this.jb = jb;
this.assignments = new ArrayList<DefinitionStmt>();
this.depends = new HashMap<Local, BitSet>();
for ( Local v : this.jb.getLocals() )
this.addLocal(v);
this.initAssignments();
}
示例9
public CastInsertionUseVisitor(boolean countOnly, JimpleBody jb,
Typing tg, IHierarchy h)
{
this.jb = jb;
this.tg = tg;
this.h = h;
this.countOnly = countOnly;
this.count = 0;
}
示例10
public TypePromotionUseVisitor(JimpleBody jb, Typing tg)
{
this.jb = jb;
this.tg = tg;
this.fail = false;
this.typingChanged = false;
}
示例11
public void check(Stmt stmt, JimpleBody stmtBody) throws TypeException {
try {
this.stmtBody = stmtBody;
stmt.apply(this);
} catch (RuntimeTypeException e) {
StringWriter st = new StringWriter();
PrintWriter pw = new PrintWriter(st);
e.printStackTrace(pw);
pw.close();
throw new TypeException(st.toString());
}
}
示例12
private static int compareTypings(JimpleBody a, JimpleBody b) {
int r = 0;
Iterator<Local> ib = b.getLocals().iterator();
for (Local v : a.getLocals()) {
Type ta = v.getType(), tb = ib.next().getType();
if (soot.jimple.toolkits.typing.fast.TypeResolver
.typesEqual(ta, tb))
continue;
/*
* Sometimes there is no reason to choose between the char and byte /
* short types. Enabling this check allows one algorithm to select
* char and the other to select byte / short without returning
* incomparable.
*/
else if (true && ((ta instanceof CharType && (tb instanceof ByteType || tb instanceof ShortType))
|| (tb instanceof CharType && (ta instanceof ByteType || ta instanceof ShortType))))
continue;
else if (soot.jimple.toolkits.typing.fast.AugHierarchy.ancestor_(
ta, tb)) {
if (r == -1)
return 3;
else
r = 1;
} else if (soot.jimple.toolkits.typing.fast.AugHierarchy.ancestor_(
tb, ta)) {
if (r == 1)
return 3;
else
r = -1;
} else
return 3;
}
return r;
}
示例13
/** Removes {@link NopStmt}s from the passed body (which must be
a {@link JimpleBody}). Complexity is linear
with respect to the statements.
*/
protected void internalTransform(Body b, String phaseName, Map<String, String> options)
{
JimpleBody body = (JimpleBody)b;
if(Options.v().verbose())
G.v().out.println("[" + body.getMethod().getName() +
"] Removing nops...");
Chain<Unit> units = body.getUnits();
// Just do one trivial pass.
{
Iterator<Unit> stmtIt = units.snapshotIterator();
while(stmtIt.hasNext())
{
Unit u = stmtIt.next();
if (u instanceof NopStmt) {
// 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 (b.getUnits().getLast() == u) {
for (Trap t : b.getTraps()) {
if (t.getEndUnit() == u) {
keepNop = true;
}
}
}
if (!keepNop) {
units.remove(u);
}
}
}
}
}
示例14
public BafBody convertJimpleBodyToBaf(SootMethod m) {
JimpleBody body = (JimpleBody) m.getActiveBody().clone();
//Change
// ConditionalBranchFolder.v().transform(body);
// UnreachableCodeEliminator.v().transform(body);
// DeadAssignmentEliminator.v().transform(body);
// UnusedLocalEliminator.v().transform(body);
BafBody bafBody = Baf.v().newBody(body);
PackManager.v().getPack("bop").apply(bafBody);
PackManager.v().getPack("tag").apply(bafBody);
if( Options.v().validate() ) {
bafBody.validate();
}
return bafBody;
}
示例15
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
initialize(options);
SootMethod meth = b.getMethod();
if ((methodsToPrint == null) || (meth.getDeclaringClass().getName() == methodsToPrint.get(meth.getName()))) {
Body body = ir.getBody((JimpleBody) b);
print_cfg(body);
}
}
示例16
public SootMethod generateDummyMainMethod(List<String> entryPoints, String sootClassName)
{
List<String> androidClasses = new ArrayList<String>();
androidClasses.add(sootClassName);
SootMethod mainMethod = new SootMethod(DUMMY_MAIN_METHOD,
new ArrayList<Type>(),
VoidType.v(),
Modifier.PUBLIC);// | Modifier.STATIC); //no need be static
JimpleBody body = Jimple.v().newBody(mainMethod);
mainMethod.setActiveBody(body);
SootClass compSootClass = Scene.v().getSootClass(sootClassName);
compSootClass.addMethod(mainMethod);
//this is mandatory, the default dummyMainMethod is static, so they
//do not deal thisIdentity. since we don't need static dummyMainMethod,
//we should define it explicit
body.insertIdentityStmts();
Map<String, List<String>> callbackFunctions = new HashMap<String, List<String>>();
callbackFunctions.put(sootClassName, getCallbackFunctions(compSootClass));
AndroidEntryPointCreator androidEPCreator = new AndroidEntryPointCreator(androidClasses);
androidEPCreator.setCallbackFunctions(callbackFunctions);
return androidEPCreator.createDummyMain(mainMethod);
}
示例17
/**
* Creates a method body that throws an "unresolved compilation error"
* message
* @param declaringClass The class that was supposed to contain the method
* @return The created SootMethod
*/
private SootMethod createUnresolvedErrorMethod(SootClass declaringClass) {
SootMethod m = new SootMethod(name, parameterTypes, returnType, isStatic()?Modifier.STATIC:0);
int modifiers = Modifier.PUBLIC; // we don't know who will be calling us
if (isStatic())
modifiers |= Modifier.STATIC;
m.setModifiers(modifiers);
JimpleBody body = Jimple.v().newBody(m);
m.setActiveBody(body);
final LocalGenerator lg = new LocalGenerator(body);
// For producing valid Jimple code, we need to access all parameters.
// Otherwise, methods like "getThisLocal()" will fail.
if (!isStatic) {
RefType thisType = RefType.v(declaringClass);
Local lThis = lg.generateLocal(thisType);
body.getUnits().add(Jimple.v().newIdentityStmt(lThis, Jimple.v().newThisRef(thisType)));
}
for (int i = 0; i < m.getParameterCount(); i++) {
Type paramType = m.getParameterType(i);
Local lParam = lg.generateLocal(paramType);
body.getUnits().add(Jimple.v().newIdentityStmt(lParam, Jimple.v().newParameterRef(paramType, i)));
}
//exc = new Error
RefType runtimeExceptionType = RefType.v("java.lang.Error");
NewExpr newExpr = Jimple.v().newNewExpr(runtimeExceptionType);
Local exceptionLocal = lg.generateLocal(runtimeExceptionType);
AssignStmt assignStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr);
body.getUnits().add(assignStmt);
//exc.<init>(message)
SootMethodRef cref = Scene.v().makeConstructorRef(runtimeExceptionType.getSootClass(),
Collections.<Type>singletonList(RefType.v("java.lang.String")));
SpecialInvokeExpr constructorInvokeExpr = Jimple.v().newSpecialInvokeExpr(exceptionLocal, cref,
StringConstant.v("Unresolved compilation error: Method "+getSignature()+" does not exist!"));
InvokeStmt initStmt = Jimple.v().newInvokeStmt(constructorInvokeExpr);
body.getUnits().insertAfter(initStmt, assignStmt);
//throw exc
body.getUnits().insertAfter(Jimple.v().newThrowStmt(exceptionLocal), initStmt);
declaringClass.addMethod(m);
return m;
}
示例18
private void addCaching(Kind kind) {
SootClass c;
String methodName;
switch(kind) {
case ClassNewInstance:
c = Scene.v().getSootClass("java.lang.Class");
methodName = "knownClassNewInstance";
break;
case ConstructorNewInstance:
c = Scene.v().getSootClass("java.lang.reflect.Constructor");
methodName = "knownConstructorNewInstance";
break;
case MethodInvoke:
c = Scene.v().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);
}
SootClass reflCallsClass = Scene.v().getSootClass("soot.rtlib.tamiflex.ReflectiveCalls");
SootMethod m = reflCallsClass.getMethodByName(methodName);
JimpleBody body = (JimpleBody) m.retrieveActiveBody();
LocalGenerator localGen = new LocalGenerator(body);
Unit firstStmt = body.getFirstNonIdentityStmt();
firstStmt = body.getUnits().getPredOf(firstStmt);
Stmt jumpTarget = Jimple.v().newNopStmt();
Chain<Unit> newUnits = new HashChain<Unit>();
//alreadyCheckedLocal = m.alreadyChecked
InstanceFieldRef fieldRef = Jimple.v().newInstanceFieldRef(body.getParameterLocal(m.getParameterCount()-1), Scene.v().makeFieldRef(c, ALREADY_CHECKED_FIELDNAME, BooleanType.v(), false));
Local alreadyCheckedLocal = localGen.generateLocal(BooleanType.v());
newUnits.add(Jimple.v().newAssignStmt(alreadyCheckedLocal, fieldRef));
//if(!alreadyChecked) goto jumpTarget
newUnits.add(Jimple.v().newIfStmt(Jimple.v().newEqExpr(alreadyCheckedLocal, IntConstant.v(0)), jumpTarget));
//return
newUnits.add(Jimple.v().newReturnVoidStmt());
//jumpTarget: nop
newUnits.add(jumpTarget);
//m.alreadyChecked = true
InstanceFieldRef fieldRef2 = Jimple.v().newInstanceFieldRef(body.getParameterLocal(m.getParameterCount()-1), Scene.v().makeFieldRef(c, ALREADY_CHECKED_FIELDNAME, BooleanType.v(), false));
newUnits.add(Jimple.v().newAssignStmt(fieldRef2, IntConstant.v(1)));
body.getUnits().insertAfter(newUnits, firstStmt);
if(Options.v().validate()) body.validate();
}
示例19
public UseChecker(JimpleBody jb)
{
this.jb = jb;
}
示例20
public void collect(Stmt stmt, JimpleBody stmtBody) {
this.stmtBody = stmtBody;
stmt.apply(this);
}
示例21
public void collect(Stmt stmt, JimpleBody stmtBody) {
this.stmtBody = stmtBody;
stmt.apply(this);
}
示例22
/** Assign types to local variables. * */
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
if (b == null) {
throw new NullPointerException();
}
Date start = new Date();
if (Options.v().verbose())
G.v().out.println("[TypeAssigner] typing system started on "
+ start);
JBTROptions opt = new JBTROptions(options);
ignoreWrongStaticNess = opt.ignore_wrong_staticness();
/*
* Setting this guard to true enables comparison of the original and new
* type assigners. This will be slow since type assignment will always
* happen twice. The actual types used for Jimple are determined by the
* use-old-type-assigner option.
*
* Each comparison is written as a separate semicolon-delimited line to
* the standard output, and the first field is always 'cmp' for use in
* grep. The format is:
*
* cmp;Method Name;Stmt Count;Old Inference Time (ms); New Inference
* Time (ms);Typing Comparison
*
* The Typing Comparison field compares the old and new typings: -2 -
* Old typing contains fewer variables (BAD!) -1 - Old typing is tighter
* (BAD!) 0 - Typings are equal 1 - New typing is tighter 2 - New typing
* contains fewer variables 3 - Typings are incomparable (inspect
* manually)
*
* In a final release this guard, and anything in the first branch,
* would probably be removed.
*/
if (opt.compare_type_assigners()) {
compareTypeAssigners(b,opt.use_older_type_assigner());
} else {
if (opt.use_older_type_assigner())
TypeResolver.resolve((JimpleBody) b, Scene.v());
else
(new soot.jimple.toolkits.typing.fast.TypeResolver(
(JimpleBody) b)).inferTypes();
}
Date finish = new Date();
if (Options.v().verbose()) {
long runtime = finish.getTime() - start.getTime();
long mins = runtime / 60000;
long secs = (runtime % 60000) / 1000;
G.v().out.println("[TypeAssigner] typing system ended. It took "
+ mins + " mins and " + secs + " secs.");
}
replaceNullType(b);
if (typingFailed((JimpleBody) b))
throw new RuntimeException("type inference failed!");
}
示例23
public Body getBody(JimpleBody b) {
return b;
}
示例24
public Body getBody(JimpleBody b) {
return Baf.v().newBody(b);
}
示例25
public Body getBody(JimpleBody b) {
return Grimp.v().newBody(b, "gb");
}
示例26
public Body getBody(JimpleBody b) {
return Shimple.v().newBody(b);
}
示例27
public Body getBody(JimpleBody b) {
return Shimple.v().newJimpleBody(Shimple.v().newBody(b));
}
示例28
public static SootMethod mockSootMethod(String clsName, String methodSubSignature, boolean isStatic)
{
SootClass sc = mockSootClass(clsName);
SootMethod sm = null;
try
{
sm = sc.getMethod(methodSubSignature);
}
catch (Exception ex)
{
sm = null;
}
if (null == sm)
{
int m = Modifier.PUBLIC;
if (isStatic)
{
m = m | Modifier.STATIC;
}
List<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(ArrayType.v(RefType.v("java.lang.Object"), 1));
String[] strs = methodSubSignature.split(" ");
String methodName = strs[1].trim().substring(0, strs[1].trim().indexOf("("));
if (null == methodName || methodName.isEmpty())
{
return null;
}
sm = new SootMethod(methodName, paramTypes, RefType.v("java.lang.Object"), m);
sc.addMethod(sm);
//Add body of sm
JimpleBody b = Jimple.v().newBody(sm);
sm.setActiveBody(b);
//LocalGenerator lg = new LocalGenerator(b);
{
b.insertIdentityStmts();
//Local rtLoc = lg.generateLocal(RefType.v("java.lang.Object"));
//Local param0 = lg.generateLocal(ArrayType.v(RefType.v("java.lang.Object"), 1));
//Unit param0U = Jimple.v().newIdentityStmt(rtLoc, Jimple.v().newParameterRef(ArrayType.v(RefType.v("java.lang.Object"), 1), 0));
//Unit rtLocAssignU = Jimple.v().newAssignStmt(rtLoc, param0);
Unit returnU = Jimple.v().newReturnStmt(b.getParameterLocal(0));
//b.getUnits().add(param0U);
b.getUnits().add(returnU);
}
System.out.println("validation:" + b);
b.validate();
}
return sm;
}
示例29
public SootMethod generateMain(Set<String> components)
{
SootMethod mainMethod = new SootMethod(DUMMY_METHOD_NAME,
Arrays.asList(new Type[] {ArrayType.v(RefType.v("java.lang.String"), 1)}),
VoidType.v(),
Modifier.PUBLIC | Modifier.STATIC);
JimpleBody body = Jimple.v().newBody(mainMethod);
mainMethod.setActiveBody(body);
SootClass sootClass = new SootClass(DUMMY_CLASS_NAME);
sootClass.setSuperclass(Scene.v().getSootClass("java.lang.Object"));
sootClass.setPhantom(false);
sootClass.setApplicationClass();
sootClass.setInScene(true);
sootClass.addMethod(mainMethod);
LocalGenerator generator = new LocalGenerator(body);
body.insertIdentityStmts();
for (String str : components)
{
SootClass sc = Scene.v().getSootClass(str);
if (sc.isPhantom())
{
continue;
}
SootMethod method = ICCDummyMainCreator.v().generateDummyMainMethod(str);
instrumentDummyMainMethod(method);
SootClass cls = method.getDeclaringClass();
SootMethod sootMethod = cls.getMethod("<init>", new ArrayList<Type>());
if (null == sootMethod)
{
throw new RuntimeException("No default constructor for comp " + cls.getName());
}
Local al = generator.generateLocal(cls.getType());
Unit newU = (Unit) Jimple.v().newAssignStmt(al, Jimple.v().newNewExpr(cls.getType()));
Unit initU = (Unit) Jimple.v().newInvokeStmt(
Jimple.v().newSpecialInvokeExpr(al, sootMethod.makeRef()));
Unit callU = (Unit) Jimple.v().newInvokeStmt(
Jimple.v().newSpecialInvokeExpr(al, method.makeRef()));
body.getUnits().add(newU);
body.getUnits().add(initU);
body.getUnits().add(callU);
}
body.getUnits().add(Jimple.v().newReturnVoidStmt());
if (fullMethodCover)
{
mainMethod = appendNonComponents(mainMethod);
}
System.out.println(body);
body.validate();
return mainMethod;
}
示例30
public void createNonParameterConstruct()
{
for (String cls : classesContainStatic.keySet())
{
SootClass sc = Scene.v().getSootClass(cls);
boolean noConstructMethod = true;
boolean existNonParameterConstructMethod = false;
List<SootMethod> methods = sc.getMethods();
for (SootMethod sm : methods)
{
String methodName = sm.getName();
if (methodName.equals("<init>"))
{
noConstructMethod = false;
if (0 == sm.getParameterCount())
{
existNonParameterConstructMethod = true;
}
}
}
//Exist construct methods but all of them containing at least one parameter
//So we need to create a default non parameter construct method for this class
if (! noConstructMethod && !existNonParameterConstructMethod)
{
SootMethod npc = new SootMethod("<init>",
new ArrayList<Type>(),
VoidType.v(),
Modifier.PUBLIC);
JimpleBody body = Jimple.v().newBody(npc);
npc.setActiveBody(body);
sc.addMethod(npc);
{
try
{
LocalGenerator lg = new LocalGenerator(body);
Local thisLocal = lg.generateLocal(sc.getType());
Unit thisU = Jimple.v().newIdentityStmt(thisLocal,
Jimple.v().newThisRef(sc.getType()));
body.getUnits().add(thisU);
SootClass supperC = sc.getSuperclass();
InvokeExpr expr = Jimple.v().newSpecialInvokeExpr(thisLocal, supperC.getMethod("<init>", new ArrayList<Type>()).makeRef());
Unit specialCallU = Jimple.v().newInvokeStmt(expr);
body.getUnits().add(specialCallU);
Unit returnVoidU = Jimple.v().newReturnVoidStmt();
body.getUnits().add(returnVoidU);
System.out.println("Create non parameter construct method: " + body);
}
catch (Exception ex)
{
//couldn't find method <init>([]) in XXX.XXX
//some supper classes do not have a <init>() construment methods
}
}
}
}
}