soot.javaToJimple.LocalGenerator Java Examples

The following examples show how to use soot.javaToJimple.LocalGenerator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ICCInstrumentDestination.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 6 votes vote down vote up
public SootMethod generateFuzzyMethod(SootClass sootClass)
{
   	String name = "fuzzyMe";
    List<Type> parameters = new ArrayList<Type>();
    Type returnType = IntType.v();
    int modifiers = Modifier.PUBLIC;
    SootMethod fuzzyMeMethod = new SootMethod(name, parameters, returnType, modifiers);
    sootClass.addMethod(fuzzyMeMethod);
    
    {
    	Body b = Jimple.v().newBody(fuzzyMeMethod);
    	fuzzyMeMethod.setActiveBody(b);
    	LocalGenerator lg = new LocalGenerator(b);
        Local thisLocal = lg.generateLocal(sootClass.getType());
        Unit thisU = Jimple.v().newIdentityStmt(thisLocal, 
                Jimple.v().newThisRef(sootClass.getType()));
        Unit returnU = Jimple.v().newReturnStmt(IntConstant.v(1));
        b.getUnits().add(thisU);
        b.getUnits().add(returnU);
    }
        
    return fuzzyMeMethod;
}
 
Example #2
Source File: DummyMainGenerator.java    From DroidRA with GNU Lesser General Public License v2.1 6 votes vote down vote up
public SootMethod generateFuzzyMethod(SootClass sootClass)
{
   	String name = "fuzzyMe";
    List<Type> parameters = new ArrayList<Type>();
    Type returnType = IntType.v();
    int modifiers = Modifier.PUBLIC;
    SootMethod fuzzyMeMethod = new SootMethod(name, parameters, returnType, modifiers);
    sootClass.addMethod(fuzzyMeMethod);
    
    {
    	Body b = Jimple.v().newBody(fuzzyMeMethod);
    	fuzzyMeMethod.setActiveBody(b);
    	LocalGenerator lg = new LocalGenerator(b);
        Local thisLocal = lg.generateLocal(sootClass.getType());
        Unit thisU = Jimple.v().newIdentityStmt(thisLocal, 
                Jimple.v().newThisRef(sootClass.getType()));
        Unit returnU = Jimple.v().newReturnStmt(IntConstant.v(1));
        b.getUnits().add(thisU);
        b.getUnits().add(returnU);
    }
        
    return fuzzyMeMethod;
}
 
Example #3
Source File: BaseEntryPointCreator.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructs an array of the given type with a single element of this type
 * in the given method
 * @param body The body of the method in which to create the array
 * @param gen The local generator
 * @param tp The type of which to create the array
 * @param constructionStack Set of classes currently being built to avoid
 * constructor loops
 * @param parentClasses If a requested type is compatible with one of the
 * types in this list, the already-created object is used instead of
 * creating a new one.
 * @return The local referencing the newly created array, or null if the
 * array generation failed
 */
private Value buildArrayOfType(Body body, LocalGenerator gen, ArrayType tp,
		Set<SootClass> constructionStack, Set<SootClass> parentClasses) {
	Local local = gen.generateLocal(tp);

	// Generate a new single-element array
	NewArrayExpr newArrayExpr = Jimple.v().newNewArrayExpr(tp.getElementType(),
			IntConstant.v(1));
	AssignStmt assignArray = Jimple.v().newAssignStmt(local, newArrayExpr);
	body.getUnits().add(assignArray);
	
	// Generate a single element in the array
	AssignStmt assign = Jimple.v().newAssignStmt
			(Jimple.v().newArrayRef(local, IntConstant.v(0)),
			getValueForType(body, gen, tp.getElementType(), constructionStack, parentClasses));
	body.getUnits().add(assign);
	return local;
}
 
Example #4
Source File: ICCInstrumentDestination.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 5 votes vote down vote up
public SootMethod generateGetIBinderMethod(SootClass compSootClass, SootField ibinderSootField, Type binderType)
{
    String name = "getIBinderForIpc";
    List<Type> parameters = new ArrayList<Type>();
    Type returnType = binderType;
    int modifiers = Modifier.PUBLIC;
    SootMethod newGetIBinder = new SootMethod(name, parameters, returnType, modifiers);
    compSootClass.addMethod(newGetIBinder);
    {
    Body b = Jimple.v().newBody(newGetIBinder);
    newGetIBinder.setActiveBody(b);
    LocalGenerator lg = new LocalGenerator(b);
    Local thisLocal = lg.generateLocal(compSootClass.getType());
    Unit thisU = Jimple.v().newIdentityStmt(thisLocal, 
            Jimple.v().newThisRef(compSootClass.getType()));
    Local ibinderParameterLocal = lg.generateLocal(IBINDER_TYPE);
    Unit getIBinderU = Jimple.v().newAssignStmt(                 
    		ibinderParameterLocal,
            Jimple.v().newStaticFieldRef(ibinderSootField.makeRef()));
    Unit returnU = Jimple.v().newReturnStmt(ibinderParameterLocal);
    b.getUnits().add(thisU);
    b.getUnits().add(getIBinderU);
    b.getUnits().add(returnU);
    }
    
    return newGetIBinder;
}
 
Example #5
Source File: ICCInstrumentDestination.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * create getIntentForActivityResult method to be able to transfer the intent back to source component
 * 
 * @param compSootClass
 * @param intentSootField
 * @return
 */
public SootMethod generateGetIntentForActivityResultMethod(SootClass compSootClass, SootField intentSootField)
{
    String name = "getIntentForActivityResult";
    List<Type> parameters = new ArrayList<Type>();
    Type returnType = INTENT_TYPE;
    int modifiers = Modifier.PUBLIC;
    SootMethod newGetIntent = new SootMethod(name, parameters, returnType, modifiers);
    compSootClass.addMethod(newGetIntent);
    {
    Body b = Jimple.v().newBody(newGetIntent);
    newGetIntent.setActiveBody(b);
    LocalGenerator lg = new LocalGenerator(b);
    Local thisLocal = lg.generateLocal(compSootClass.getType());
    Unit thisU = Jimple.v().newIdentityStmt(thisLocal, 
            Jimple.v().newThisRef(compSootClass.getType()));
    Local intentParameterLocal = lg.generateLocal(INTENT_TYPE);
    Unit getIntentU = Jimple.v().newAssignStmt(                 
            intentParameterLocal,
            Jimple.v().newStaticFieldRef(intentSootField.makeRef()));
    Unit returnU = Jimple.v().newReturnStmt(intentParameterLocal);
    b.getUnits().add(thisU);
    b.getUnits().add(getIntentU);
    b.getUnits().add(returnU);
    }
    
    return newGetIntent;
}
 
Example #6
Source File: ICCInstrumentDestination.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Override getIntent method to be able to transfer the intent to the destination component
 * 
 * @param compSootClass
 * @param intentSootField
 * @return
 */
public SootMethod generateGetIntentMethod(SootClass compSootClass, SootField intentSootField)
{
    String name = "getIntent";
    List<Type> parameters = new ArrayList<Type>();
    Type returnType = INTENT_TYPE;
    int modifiers = Modifier.PUBLIC;
    SootMethod newGetIntent = new SootMethod(name, parameters, returnType, modifiers);
    compSootClass.addMethod(newGetIntent);
    {
    Body b = Jimple.v().newBody(newGetIntent);
    newGetIntent.setActiveBody(b);
    LocalGenerator lg = new LocalGenerator(b);
    Local thisLocal = lg.generateLocal(compSootClass.getType());
    Unit thisU = Jimple.v().newIdentityStmt(thisLocal, 
            Jimple.v().newThisRef(compSootClass.getType()));
    Local intentParameterLocal = lg.generateLocal(INTENT_TYPE);
    Unit getIntentU = Jimple.v().newAssignStmt(                 
            intentParameterLocal,
            Jimple.v().newStaticFieldRef(intentSootField.makeRef()));
    Unit returnU = Jimple.v().newReturnStmt(intentParameterLocal);
    b.getUnits().add(thisU);
    b.getUnits().add(getIntentU);
    b.getUnits().add(returnU);
    }
    
    return newGetIntent;
}
 
Example #7
Source File: OnFlyCallGraphBuilder.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private void insertGuard(Guard guard) {
	if(options.guards().equals("ignore")) return;
	
	SootMethod container = guard.container;
	Stmt insertionPoint = guard.stmt;
	if(!container.hasActiveBody()) {
		G.v().out.println("WARNING: Tried to insert guard into "+container+" but couldn't because method has no body.");
	} else {
		Body body = container.getActiveBody();
		
		//exc = new Error
		RefType runtimeExceptionType = RefType.v("java.lang.Error");
		NewExpr newExpr = Jimple.v().newNewExpr(runtimeExceptionType);
		LocalGenerator lg = new LocalGenerator(body);
		Local exceptionLocal = lg.generateLocal(runtimeExceptionType);
		AssignStmt assignStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr);
		body.getUnits().insertBefore(assignStmt, insertionPoint);
		
		//exc.<init>(message)
		SootMethodRef cref = runtimeExceptionType.getSootClass().getMethod("<init>", Collections.<Type>singletonList(RefType.v("java.lang.String"))).makeRef();
		SpecialInvokeExpr constructorInvokeExpr = Jimple.v().newSpecialInvokeExpr(exceptionLocal, cref, StringConstant.v(guard.message));
		InvokeStmt initStmt = Jimple.v().newInvokeStmt(constructorInvokeExpr);
		body.getUnits().insertAfter(initStmt, assignStmt);
		
		if(options.guards().equals("print")) {
			//exc.printStackTrace();
			VirtualInvokeExpr printStackTraceExpr = Jimple.v().newVirtualInvokeExpr(exceptionLocal, Scene.v().getSootClass("java.lang.Throwable").getMethod("printStackTrace", Collections.<Type>emptyList()).makeRef());
			InvokeStmt printStackTraceStmt = Jimple.v().newInvokeStmt(printStackTraceExpr);
			body.getUnits().insertAfter(printStackTraceStmt, initStmt);
		} else if(options.guards().equals("throw")) {
			body.getUnits().insertAfter(Jimple.v().newThrowStmt(exceptionLocal), initStmt);
		} else {
			throw new RuntimeException("Invalid value for phase option (guarding): "+options.guards());
		}
	}
}
 
Example #8
Source File: JimpleReduceStaticFieldsTransformer.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void replaceSootField(SootClass sc, Body b, AssignStmt aStmt, SootField sf)
{
	SootClass sfClass = sf.getDeclaringClass();
	
	LocalGenerator lg = new LocalGenerator(b);
	Local sfLocal = lg.generateLocal(sc.getType());
	Unit sfLocalAssignU = Jimple.v().newAssignStmt(
               sfLocal, 
               Jimple.v().newStaticFieldRef(sc.getField("instance", sc.getType()).makeRef()));
	
	Local sfLocal2 = lg.generateLocal(sfClass.getType());
	Unit sfLocalAssignU2 = Jimple.v().newAssignStmt(
               sfLocal2, 
               Jimple.v().newInstanceFieldRef(sfLocal, sc.getField(sfClass.getName(), sfClass.getType()).makeRef()));

	Unit assignU = null;
	
	if (aStmt.getLeftOp() instanceof FieldRef)
	{
		assignU = Jimple.v().newAssignStmt(Jimple.v().newInstanceFieldRef(sfLocal2, sf.makeRef()), aStmt.getRightOp());
	}
	else
	{
		assignU = Jimple.v().newAssignStmt(aStmt.getLeftOp(), Jimple.v().newInstanceFieldRef(sfLocal2, sf.makeRef()));
	}
	
	b.getUnits().insertBefore(sfLocalAssignU, aStmt);
	b.getUnits().insertBefore(sfLocalAssignU2, aStmt);
	b.getUnits().insertBefore(assignU, aStmt);
	b.getUnits().remove(aStmt);
	
	System.out.println(b);
}
 
Example #9
Source File: DefaultInstrumentation.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void injectedStmtWrapper(Body body, LocalGenerator localGenerator, Stmt stmt, Stmt nextStmt)
{
	Local opaqueLocal = localGenerator.generateLocal(IntType.v());
	Unit assignU = Jimple.v().newAssignStmt(opaqueLocal, Jimple.v().newStaticInvokeExpr(Alteration.v().getTryMethod().makeRef(), IntConstant.v(0)));
	Unit ifU = Jimple.v().newIfStmt(Jimple.v().newEqExpr(IntConstant.v(1), opaqueLocal), nextStmt);

	body.getUnits().insertAfter(ifU, stmt);
	body.getUnits().insertAfter(assignU, stmt);
}
 
Example #10
Source File: ICCRedirectionCreator.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SootMethod generateRedirectMethodForContentProvider(Stmt iccStmt, SootClass destProvider) {
    System.out.println("create method to call dest class: "+ destProvider);
    
    SootMethod iccMethod = iccStmt.getInvokeExpr().getMethod();
    
    String newSM_name = "redirector" + num++;
    List<Type> newSM_parameters = iccMethod.getParameterTypes();
    Type newSM_return_type = iccMethod.getReturnType();
    int modifiers = Modifier.STATIC | Modifier.PUBLIC;
            
    SootMethod newSM = new SootMethod(newSM_name, newSM_parameters, newSM_return_type, modifiers);
    ipcSC.addMethod(newSM);
    JimpleBody b = Jimple.v().newBody(newSM);
    newSM.setActiveBody(b);
    
    LocalGenerator lg = new LocalGenerator(b);
    
    // all parameters
    List<Unit> units = new ArrayList<Unit>();
    List<Local> locals = new ArrayList<Local>();
    for (int i = 0; i < newSM_parameters.size(); i++)
    {
    	Type type = newSM_parameters.get(i);
    	Local local = lg.generateLocal(type);
    	Unit localU = Jimple.v().newIdentityStmt(local, Jimple.v().newParameterRef(type, i));
    	
    	locals.add(local);
    	units.add(localU);
    }
    
    // new
    Local al = lg.generateLocal(destProvider.getType());
    Unit newU = (Unit) Jimple.v().newAssignStmt(al, 
            Jimple.v().newNewExpr(destProvider.getType())
            );
    
    // init
    List<Type> parameters = new ArrayList<Type>();
    List<Value> args = new ArrayList<Value>();
    SootMethod method = destProvider.getMethod("<init>", parameters, VoidType.v());
    Unit initU = (Unit) Jimple.v().newInvokeStmt(
            Jimple.v().newSpecialInvokeExpr(al, method.makeRef(), args));
    
    Local rtLocal = lg.generateLocal(newSM_return_type);
    
    
    // call related method and assign the result to return local, may optimize it to dummyMain method as well
    parameters = iccMethod.getParameterTypes();
    method = destProvider.getMethodByName(iccMethod.getName());
       InvokeExpr invoke = Jimple.v().newVirtualInvokeExpr(al, method.makeRef(), locals);
       //Unit callU = (Unit) Jimple.v().newInvokeStmt(invoke);
       Unit assignU = (Unit) Jimple.v().newAssignStmt(rtLocal, invoke);
       
       // return statement
       Unit returnU = (Unit) Jimple.v().newReturnStmt(rtLocal);
    
       for (Unit unit : units)
       {
       	b.getUnits().add(unit);
       }
    b.getUnits().add(newU);
    b.getUnits().add(initU);
    b.getUnits().add(assignU);
    b.getUnits().add(returnU);
    
    System.out.println("new lifecypcle method: "+ newSM +" body: "+ newSM.retrieveActiveBody());
    
    return newSM;
    
}
 
Example #11
Source File: ICCRedirectionCreator.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SootMethod generateFakeOnActivityResult(SootClass sootClass)
{
	List<Type> parameters = new ArrayList<Type>();
	parameters.add(IntType.v());
	parameters.add(IntType.v());
	parameters.add(INTENT_TYPE);
    SootMethod newOnActivityResult = new SootMethod("onActivityResult", 
    		parameters, 
    		VoidType.v(), 
    		Modifier.PUBLIC);
    sootClass.addMethod(newOnActivityResult);
    
    Body b = Jimple.v().newBody(newOnActivityResult);
    
    //generate identityStmt
    LocalGenerator lg = new LocalGenerator(b);
    
    //this
    Local thisLocal = lg.generateLocal(sootClass.getType());
    Unit thisU = Jimple.v().newIdentityStmt(thisLocal, 
            Jimple.v().newThisRef(sootClass.getType()));
    
    //parameter1
    Local int1ParameterLocal = lg.generateLocal(IntType.v());
    Unit int1ParameterU = Jimple.v().newIdentityStmt(int1ParameterLocal, Jimple.v().newParameterRef(IntType.v(), 0));
    
    //parameter2
    Local int2ParameterLocal = lg.generateLocal(IntType.v());
    Unit int2ParameterU = Jimple.v().newIdentityStmt(int2ParameterLocal, Jimple.v().newParameterRef(IntType.v(), 1));
    
    
    
    //parameter
    Type intentType = RefType.v("android.content.Intent");
    Local intentParameterLocal = lg.generateLocal(intentType);
    Unit intentParameterU = Jimple.v().newIdentityStmt(intentParameterLocal, Jimple.v().newParameterRef(intentType, 2));
       
    //return
    Unit returnU = Jimple.v().newReturnVoidStmt();
    
    b.getUnits().add(thisU);
    b.getUnits().add(int1ParameterU);
    b.getUnits().add(int2ParameterU);
    b.getUnits().add(intentParameterU);
    b.getUnits().add(returnU);

    newOnActivityResult.setActiveBody(b);
    return newOnActivityResult;
}
 
Example #12
Source File: ICCRedirectionCreator.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SootMethod generateRedirectMethodForStartActivity(SootClass wrapper) {
    System.out.println("create method to call wrapper class: "+ wrapper);
    String newSM_name = "redirector" + num++;
    List<Type> newSM_parameters = new ArrayList<Type>();
    newSM_parameters.add(INTENT_TYPE);
    Type newSM_return_type = VoidType.v();
    int modifiers = Modifier.STATIC | Modifier.PUBLIC;

    SootMethod newSM = new SootMethod(newSM_name, newSM_parameters, newSM_return_type, modifiers);
    ipcSC.addMethod(newSM);
    JimpleBody b = Jimple.v().newBody(newSM);
    newSM.setActiveBody(b);

    LocalGenerator lg = new LocalGenerator(b);

    // identity
    Local intentParameterLocal = lg.generateLocal(INTENT_TYPE);
    Unit intentParameterU = Jimple.v().newIdentityStmt(
            intentParameterLocal,
            Jimple.v().newParameterRef(INTENT_TYPE, 0));

    // new
    Local al = lg.generateLocal(wrapper.getType());
    Unit newU = (Unit) Jimple.v().newAssignStmt(al,
            Jimple.v().newNewExpr(wrapper.getType())
            );
    // init
    List<Type> parameters = new ArrayList<Type>();
    parameters.add(INTENT_TYPE);
    SootMethod method = wrapper.getMethod("<init>", parameters, VoidType.v());
    List<Value> args = new ArrayList<Value>();
    args.add(intentParameterLocal);
    Unit initU = (Unit) Jimple.v().newInvokeStmt(
            Jimple.v().newSpecialInvokeExpr(al, method.makeRef(), args));

    // call dummyMainMethod
    //method = wrapper.getMethodByName(ICCDummyMainCreator.DUMMY_MAIN_METHOD);
    method = wrapper.getMethodByName("onCreate");
    args = new ArrayList<Value>();
    Local pLocal = lg.generateLocal(RefType.v("android.os.Bundle"));
    Unit nullParamU = (Unit) Jimple.v().newAssignStmt(pLocal, NullConstant.v());
    args.add(pLocal);
    InvokeExpr invoke = Jimple.v().newVirtualInvokeExpr(al, method.makeRef(), args);
    Unit callU = (Unit) Jimple.v().newInvokeStmt(invoke);

    b.getUnits().add(intentParameterU);
    b.getUnits().add(newU);
    b.getUnits().add(initU);
    b.getUnits().add(nullParamU);
    b.getUnits().add(callU);
    b.getUnits().add(Jimple.v().newReturnVoidStmt());

    System.out.println("new lifecypcle method: "+ newSM +" body: "+ newSM.retrieveActiveBody());

    return newSM;

}
 
Example #13
Source File: ICCRedirectionCreator.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SootMethod generateRedirectMethod(SootClass wrapper) {
    System.out.println("create method to call wrapper class: "+ wrapper);
    String newSM_name = "redirector" + num++;
    List<Type> newSM_parameters = new ArrayList<Type>();
    newSM_parameters.add(INTENT_TYPE);
    Type newSM_return_type = VoidType.v();
    int modifiers = Modifier.STATIC | Modifier.PUBLIC;
            
    SootMethod newSM = new SootMethod(newSM_name, newSM_parameters, newSM_return_type, modifiers);
    ipcSC.addMethod(newSM);
    JimpleBody b = Jimple.v().newBody(newSM);
    newSM.setActiveBody(b);
    
    LocalGenerator lg = new LocalGenerator(b);
    
    // identity
    Local intentParameterLocal = lg.generateLocal(INTENT_TYPE);
    Unit intentParameterU = Jimple.v().newIdentityStmt(
            intentParameterLocal,
            Jimple.v().newParameterRef(INTENT_TYPE, 0));
    
    // new
    Local al = lg.generateLocal(wrapper.getType());
    Unit newU = (Unit) Jimple.v().newAssignStmt(al, 
            Jimple.v().newNewExpr(wrapper.getType())
            );
    // init
    List<Type> parameters = new ArrayList<Type>();
    parameters.add(INTENT_TYPE);
    SootMethod method = wrapper.getMethod("<init>", parameters, VoidType.v());
    List<Value> args = new ArrayList<Value>();
    args.add(intentParameterLocal);
    Unit initU = (Unit) Jimple.v().newInvokeStmt(
            Jimple.v().newSpecialInvokeExpr(al, method.makeRef(), args));
    
    // call dummyMainMethod
    method = wrapper.getMethodByName(ICCDummyMainCreator.DUMMY_MAIN_METHOD);
    //args = new ArrayList<Value>();
    //Local pLocal = lg.generateLocal(RefType.v("android.os.Bundle"));
    //Unit nullParamU = (Unit) Jimple.v().newAssignStmt(pLocal, NullConstant.v());
    //args.add(pLocal);
    InvokeExpr invoke = Jimple.v().newVirtualInvokeExpr(al, method.makeRef());
    Unit callU = (Unit) Jimple.v().newInvokeStmt(invoke);
    
    b.getUnits().add(intentParameterU);
    b.getUnits().add(newU);
    b.getUnits().add(initU);
    //b.getUnits().add(nullParamU);
    b.getUnits().add(callU);
    b.getUnits().add(Jimple.v().newReturnVoidStmt());
    
    System.out.println("new lifecypcle method: "+ newSM +" body: "+ newSM.retrieveActiveBody());
    
    return newSM;
    
}
 
Example #14
Source File: ICCRedirectionCreator.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SootMethod generateRedirectMethodForStartActivityForResult(SootClass originActivity, SootClass destComp)
{
	String newSM_name = "redirector" + num++;
	
    List<Type> newSM_parameters = new ArrayList<Type>();
    newSM_parameters.add(originActivity.getType());
    newSM_parameters.add(INTENT_TYPE);
    Type newSM_return_type = VoidType.v();
    int modifiers = Modifier.STATIC | Modifier.PUBLIC;
            
    SootMethod newSM = new SootMethod(newSM_name, newSM_parameters, newSM_return_type, modifiers);
    ipcSC.addMethod(newSM);
    JimpleBody b = Jimple.v().newBody(newSM);
    newSM.setActiveBody(b);
    
    LocalGenerator lg = new LocalGenerator(b);
	
    Local originActivityParameterLocal = lg.generateLocal(originActivity.getType());
    Unit originActivityParameterU = Jimple.v().newIdentityStmt(
    		originActivityParameterLocal, 
    		Jimple.v().newParameterRef(originActivity.getType(), 0));
    
    Local intentParameterLocal = lg.generateLocal(INTENT_TYPE);
    Unit intentParameterU = Jimple.v().newIdentityStmt(
            intentParameterLocal,
            Jimple.v().newParameterRef(INTENT_TYPE, 1));
    
    // new dest component
    Local destCompLocal = lg.generateLocal(destComp.getType());
    Unit newU = (Unit) Jimple.v().newAssignStmt(destCompLocal, 
            Jimple.v().newNewExpr(destComp.getType())
            );
    
    //call <init> method
    List<Type> parameters = new ArrayList<Type>();
    parameters.add(INTENT_TYPE);
    SootMethod method = destComp.getMethod("<init>", parameters, VoidType.v());
    List<Value> args = new ArrayList<Value>();
    args.add(intentParameterLocal);
    Unit initU = (Unit) Jimple.v().newInvokeStmt(
            Jimple.v().newSpecialInvokeExpr(destCompLocal, method.makeRef(), args));
    
    List<SootMethod> sms = destComp.getMethods();
    for (SootMethod sm : sms)
    {
    	System.out.println(sm);
    }
    
    // call onCreate
    method = destComp.getMethodByName(ICCDummyMainCreator.DUMMY_MAIN_METHOD);
    InvokeExpr invoke = Jimple.v().newVirtualInvokeExpr(destCompLocal, method.makeRef());
    Unit callU = (Unit) Jimple.v().newInvokeStmt(invoke);
    
    
    //call sc.getIntentForActivityResult
    Local arIntentLocal = lg.generateLocal(INTENT_TYPE);
    Unit nullarIntentLocalParamU = (Unit) Jimple.v().newAssignStmt(
    		arIntentLocal, NullConstant.v());
    method = destComp.getMethodByName("getIntentForActivityResult");
    invoke = Jimple.v().newVirtualInvokeExpr(destCompLocal, method.makeRef());
    Unit destCompCallU = (Unit) Jimple.v().newAssignStmt(arIntentLocal, invoke);
    
    //some apps do not have an onActivityResult method even they use startActivityForResult to communicate with other components.
    try
    {
    	method = originActivity.getMethodByName("onActivityResult");
    }
    catch (Exception ex)
    {
    	method = generateFakeOnActivityResult(originActivity);
    }
    
    Local iLocal1 = lg.generateLocal(IntType.v());
    Local iLocal2 = lg.generateLocal(IntType.v());
    Unit defaultValueParamU1 = (Unit) Jimple.v().newAssignStmt(iLocal1, IntConstant.v(-1));
    Unit defaultValueParamU2 = (Unit) Jimple.v().newAssignStmt(iLocal2, IntConstant.v(-1));
    args = new ArrayList<Value>();
    args.add(iLocal1);
    args.add(iLocal2);
    args.add(arIntentLocal);
    invoke = Jimple.v().newVirtualInvokeExpr(originActivityParameterLocal, method.makeRef(), args);
    Unit onActivityResultCall = (Unit) Jimple.v().newInvokeStmt(invoke);
    
    b.getUnits().add(originActivityParameterU);
    b.getUnits().add(intentParameterU);
    b.getUnits().add(newU);
    b.getUnits().add(initU);
    //b.getUnits().add(nullParamU);
    b.getUnits().add(callU);
    b.getUnits().add(nullarIntentLocalParamU);
    b.getUnits().add(destCompCallU); 
    b.getUnits().add(defaultValueParamU1);
    b.getUnits().add(defaultValueParamU2);
    b.getUnits().add(onActivityResultCall);
    b.getUnits().add(Jimple.v().newReturnVoidStmt());
    
    System.out.println("new lifecypcle method: "+ newSM +" body: "+ newSM.retrieveActiveBody());
    
	return newSM;
}
 
Example #15
Source File: PolicyEnforcementPoint.java    From DroidForce with GNU Lesser General Public License v2.1 4 votes vote down vote up
private Local generateFreshLocal(Body b, Type type){
	LocalGenerator lg = new LocalGenerator(b);
	return lg.generateLocal(type);
}
 
Example #16
Source File: Alteration.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void init()
{
	if (Scene.v().containsClass(CLASS_ALTERATION))
	{
		return;
	}
	
	SootClass sootClass = new SootClass(CLASS_ALTERATION);
   	sootClass.setSuperclass(Scene.v().getSootClass("java.lang.Object"));
   	sootClass.setPhantom(false);
   	sootClass.setApplicationClass();
   	sootClass.setInScene(true);
   	
   	//sootClass.addMethod(mainMethod);
	
    List<Type> parameters = new ArrayList<Type>();
    parameters.add(IntType.v());
    Type returnType = IntType.v();
    int modifiers = Modifier.PUBLIC | Modifier.STATIC;

    SootMethod tryMethod = new SootMethod(METHOD_TRY, parameters, returnType, modifiers);
    sootClass.addMethod(tryMethod);
    
    {
    	Body b = Jimple.v().newBody(tryMethod);
    	tryMethod.setActiveBody(b);
    	
    	LocalGenerator lg = new LocalGenerator(b);
    	
    	Local paramLocal = lg.generateLocal(IntType.v());
        Unit paramLocalU = Jimple.v().newIdentityStmt(
        		paramLocal, 
        		Jimple.v().newParameterRef(IntType.v(), 0));
    	
        Local returnLocal = lg.generateLocal(IntType.v());
        
        Unit callCheckU = Jimple.v().newAssignStmt(returnLocal, Jimple.v().newStaticInvokeExpr(tryMethod.makeRef(), IntConstant.v(1)));
        Unit assignU = Jimple.v().newAssignStmt(returnLocal, IntConstant.v(0));
        Unit returnU = Jimple.v().newReturnStmt(returnLocal);
        
        Unit ifU = Jimple.v().newIfStmt(Jimple.v().newEqExpr(IntConstant.v(0), paramLocal), callCheckU);
        Unit jimpleU = Jimple.v().newGotoStmt(returnU);
        
        b.getUnits().add(paramLocalU);
        b.getUnits().add(ifU);
        b.getUnits().add(assignU);
        b.getUnits().add(jimpleU);
        b.getUnits().add(callCheckU);
        b.getUnits().add(returnU);
        
        System.out.println(b);
        b.validate();
    }
}
 
Example #17
Source File: JimpleReduceStaticFieldsTransformer.java    From soot-infoflow-android-iccta with GNU Lesser General Public License v2.1 4 votes vote down vote up
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
	    		}
	    		
	    	}
		}
	}
}
 
Example #18
Source File: Util.java    From DroidForce with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static Local generateFreshLocal(Body b, Type type){
	LocalGenerator lg = new LocalGenerator(b);
	return lg.generateLocal(type);
}
 
Example #19
Source File: DummyMainGenerator.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SootMethod addMethod(SootMethod mainMethod, String methodSignature)
{
	Body body = mainMethod.getActiveBody();
   	
	Stmt returnStmt = null;
	
   	PatchingChain<Unit> units = body.getUnits();
   	for (Iterator<Unit> iter = units.snapshotIterator(); iter.hasNext(); )
   	{
   		Stmt stmt = (Stmt) iter.next();
   		
   		if (stmt instanceof ReturnStmt || stmt instanceof ReturnVoidStmt)
   		{
   			returnStmt = stmt;
   		}
   	}
   	
   	SootMethod sm = Scene.v().getMethod(methodSignature);
   	
   	List<Type> paramTypes = sm.getParameterTypes();
   	List<Value> paramValues = new ArrayList<Value>();
   	for (int i = 0; i < paramTypes.size(); i++)
   	{
   		paramValues.add(InstrumentationUtils.toDefaultSootTypeValue(paramTypes.get(i)));
   	}
   	
   	
   	if (sm.isStatic())    //No need to construct its obj ref
   	{
   		InvokeExpr expr = Jimple.v().newStaticInvokeExpr(sm.makeRef(), paramValues);
   		Unit callU = Jimple.v().newInvokeStmt(expr);
   		units.insertBefore(callU, returnStmt);
   	}
   	else
   	{
   		//new obj first and then call the method
   		
   		SootClass sc = sm.getDeclaringClass();
   		List<SootMethod> methods = sc.getMethods();
   		
   		SootMethod init = null;
   		SootMethod clinit = null;
   		
   		for (SootMethod method : methods)
   		{
   			if (method.getName().equals("<clinit>"))
   			{
   				clinit = method;
   			}
   			
   			if (method.getName().equals("<init>"))
   			{
   				init = method;
   			}
   		}
   		
   		LocalGenerator localGenerator = new LocalGenerator(body);
   		
   		Local obj = localGenerator.generateLocal(sc.getType());
   		
   		Unit newU = Jimple.v().newAssignStmt(obj, Jimple.v().newNewExpr(sc.getType())); 
   		units.insertBefore(newU, returnStmt);
   		
   		if (null != clinit)
   		{
   			Unit clinitCallU = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(clinit.makeRef()));
   			units.insertBefore(clinitCallU, returnStmt);
   		}
   		
   		if (null != init)
   		{
   			List<Type> initParamTypes = init.getParameterTypes();
   	    	List<Value> initParamValues = new ArrayList<Value>();
   	    	for (int i = 0; i < initParamTypes.size(); i++)
   	    	{
   	    		initParamValues.add(InstrumentationUtils.toDefaultSootTypeValue(initParamTypes.get(i)));
   	    	}
   	    	
   	    	Unit initCallU = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(obj, init.makeRef(), initParamValues));
   	    	units.insertBefore(initCallU, returnStmt);
   		}
   		else
   		{
   			throw new RuntimeException("Is it possible that a class does not contain an <init> method?");
   		}
   	}
   	
   	System.out.println(body);
   	body.validate();
   	
   	return mainMethod;
}
 
Example #20
Source File: DummyMainGenerator.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
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;
}
 
Example #21
Source File: CustomEntryPointCreator.java    From steady with Apache License 2.0 4 votes vote down vote up
private SootMethod generateMethodImplementation(SootMethod methodToImplement,
                                                final SootClass generatedDummyClass) {
    SootMethod generatedMethod = new SootMethod(methodToImplement.getName(), methodToImplement.getParameterTypes(), methodToImplement.getReturnType());
    Body body = Jimple.v().newBody();
    body.setMethod(generatedMethod);
    generatedMethod.setActiveBody(body);

    // add locals for Parameter
    // Add a parameter reference to the body
    LocalGenerator lg = new LocalGenerator(body);

    //create a local for the this reference
    if (!methodToImplement.isStatic()) {
        Local thisLocal = lg.generateLocal(generatedDummyClass.getType());
        body.getUnits().addFirst(Jimple.v().newIdentityStmt(thisLocal, Jimple.v().newThisRef(generatedDummyClass.getType())));
    }

    int i = 0;
    for (Type type : generatedMethod.getParameterTypes()) {
        Local paramLocal = lg.generateLocal(type);
        body.getUnits().add(Jimple.v().newIdentityStmt(paramLocal,
                Jimple.v().newParameterRef(type, i)));
        i++;
    }

    JNopStmt startStmt = new JNopStmt();
    JNopStmt endStmt = new JNopStmt();

    body.getUnits().add(startStmt);


    //check if return type is void (check first, since next call includes void)
    if (methodToImplement.getReturnType() instanceof VoidType) {
        body.getUnits().add(Jimple.v().newReturnVoidStmt());
    }
    // if sootClass is simpleClass
    else if (isSimpleType(methodToImplement.getReturnType().toString())) {
        Local varLocal = lg.generateLocal(getSimpleTypeFromType(methodToImplement.getReturnType()));

        AssignStmt aStmt = Jimple.v().newAssignStmt(varLocal, getSimpleDefaultValue(methodToImplement.getReturnType()));
        body.getUnits().add(aStmt);
        body.getUnits().add(Jimple.v().newReturnStmt(varLocal));
    } else {
        body.getUnits().add(Jimple.v().newReturnStmt(NullConstant.v()));

    }

    //remove the abstract Modifier from the new implemented method
    generatedMethod.setModifiers(methodToImplement.getModifiers() ^ Modifier.ABSTRACT);

    return generatedMethod;
}
 
Example #22
Source File: ClassNewInstanceCallInstrumentation.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void instrument() 
{
	SootMethod sootMethod = stmtKey.getMethod();
	Stmt stmt = stmtKey.getStmt();
	
	Body body = sootMethod.retrieveActiveBody();
	
	Stmt nextStmt = getNextStmt(body, stmt);
	
	LocalGenerator localGenerator = new LocalGenerator(body);
	
	if (StmtType.CLASS_NEW_INSTANCE != stmtValue.getType())
	{
		return;
	}
	
	List<Unit> injectedUnits = new ArrayList<Unit>();
	
	//for (ClassDescription clsDesc : stmtValue.getClsSet())
	//{
	ClassDescription clsDesc = stmtValue.getClsDesc();
		SootClass sc = Scene.v().getSootClass(clsDesc.name);
		

		Local local = localGenerator.generateLocal(sc.getType());
		
		Unit newU = Jimple.v().newAssignStmt(local, Jimple.v().newNewExpr(sc.getType()));
		injectedUnits.add(newU);
		
		List<SootMethod> cinitList = InstrumentationUtils.getMethodByName(sc, "<clinit>");
		if (cinitList.size() > 0)
		{
			SootMethod cinit = cinitList.get(0);
			
			Unit cinitCallU = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(cinit.makeRef()));
			injectedUnits.add(cinitCallU);
		}
		
		
		try
		{
			SootMethod init = sc.getMethod("void <init>()");
			InvokeExpr invokeExpr = Jimple.v().newVirtualInvokeExpr(local, init.makeRef());
			Unit initU = Jimple.v().newInvokeStmt(invokeExpr);
			injectedUnits.add(initU);
			
			AssignStmt assignStmt = (AssignStmt) stmt;
			Unit assignU = Jimple.v().newAssignStmt(assignStmt.getLeftOp(), local);
			injectedUnits.add(assignU);
			
		}
		catch (Exception ex)
		{
			//It does not make sense to come here.
			System.out.println("There is no <init> method for class " + sc.getName());
		}
	//}
	
	for (int i = injectedUnits.size()-1; i >= 0; i--)
	{
		body.getUnits().insertAfter(injectedUnits.get(i), stmt);
	}
	
	injectedStmtWrapper(body, localGenerator, stmt, nextStmt);
	
	System.out.println(body);
	body.validate();
}
 
Example #23
Source File: AccessManager.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private static void createSetAccessor(SootMethod container, AssignStmt as, FieldRef ref) {
   	java.util.List parameterTypes=new LinkedList();
   	java.util.List<SootClass> thrownExceptions=new LinkedList<SootClass>();
   	
   	Body accessorBody = Jimple.v().newBody();
   	soot.util.Chain accStmts=accessorBody.getUnits();
   	LocalGenerator lg=new LocalGenerator(accessorBody);
   	
   	Body containerBody=container.getActiveBody();
   	soot.util.Chain containerStmts=containerBody.getUnits();
   	
	SootClass target=ref.getField().getDeclaringClass();
	SootMethod accessor;
	
	String name=createAccessorName(ref.getField(), true);
	accessor = target.getMethodByNameUnsafe(name);
	if (accessor == null) {			
		Local thisLocal=lg.generateLocal(target.getType());
		int paramID=0;
		if (ref instanceof InstanceFieldRef) {
			accStmts.add(
					Jimple.v().newIdentityStmt(thisLocal, 
							Jimple.v().newParameterRef(target.getType(),paramID)));    			
			parameterTypes.add(target.getType());
			paramID++;
		}
		parameterTypes.add(ref.getField().getType());
		Local l=lg.generateLocal(ref.getField().getType());
		accStmts.add(
				Jimple.v().newIdentityStmt(l, 
				Jimple.v().newParameterRef(ref.getField().getType(),paramID)));
		paramID++;
		if (ref instanceof InstanceFieldRef) {
			accStmts.add(Jimple.v().newAssignStmt(
				Jimple.v().newInstanceFieldRef(thisLocal,ref.getFieldRef()), l));
		} else {
			accStmts.add(Jimple.v().newAssignStmt(
					Jimple.v().newStaticFieldRef(ref.getFieldRef()), l));
		}
		accStmts.addLast(Jimple.v().newReturnVoidStmt());
		Type returnType=VoidType.v();
		
		accessor=new SootMethod(name, parameterTypes, returnType, 
				Modifier.PUBLIC | Modifier.STATIC,
				thrownExceptions);    	
		accessorBody.setMethod(accessor);    	
		accessor.setActiveBody(accessorBody);
		target.addMethod(accessor);
	}
	
	java.util.List args=new LinkedList();
	if (ref instanceof InstanceFieldRef) {
		args.add(((InstanceFieldRef)ref).getBase());
	}
	args.add(as.getRightOp());
	InvokeExpr newExpr= 
		Jimple.v().newStaticInvokeExpr(accessor.makeRef(), args);
	
	Stmt newStmt=Jimple.v().newInvokeStmt(newExpr);
	
 	    containerStmts.insertAfter(newStmt, as);
	containerStmts.remove(as);
}
 
Example #24
Source File: ReflectiveCallsInliner.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
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();
}
 
Example #25
Source File: SootMethodRefImpl.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
    * 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;
}
 
Example #26
Source File: InterproceduralConstantValuePropagator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void fixExceptions(SootMethod caller, Unit callSite, Set<SootClass> doneSet) {
	ThrowAnalysis ta = Options.v().src_prec() == Options.src_prec_apk
			? DalvikThrowAnalysis.v() : UnitThrowAnalysis.v();
	ThrowableSet throwSet = ta.mightThrow(callSite);
	
	for (final Trap t : caller.getActiveBody().getTraps())
		if (doneSet.add(t.getException())
				&& throwSet.catchableAs(t.getException().getType())) {
			SootMethod thrower = exceptionThrowers.get(t.getException());
			if (thrower == null) {
				if (exceptionClass == null) {
					exceptionClass = new SootClass("FLOWDROID_EXCEPTIONS", Modifier.PUBLIC);
					Scene.v().addClass(exceptionClass);
				}
				
				// Create the new method
				thrower = new SootMethod("throw" + exceptionThrowers.size(),
						Collections.<Type>emptyList(), VoidType.v());
				thrower.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
				
				final Body body = Jimple.v().newBody(thrower);
				thrower.setActiveBody(body);
				final SootMethod meth = thrower;
				
				IEntryPointCreator epc = new BaseEntryPointCreator() {
	
					@Override
					public Collection<String> getRequiredClasses() {
						return Collections.emptySet();
					}
	
					@Override
					protected SootMethod createDummyMainInternal(SootMethod emptySootMethod) {
				 		LocalGenerator generator = new LocalGenerator(body);
						
				 		// Create the counter used for the opaque predicate
						int conditionCounter = 0;
						Value intCounter = generator.generateLocal(IntType.v());
						AssignStmt assignStmt = new JAssignStmt(intCounter, IntConstant.v(conditionCounter));
						body.getUnits().add(assignStmt);
						
						Stmt afterEx = Jimple.v().newNopStmt();
						IfStmt ifStmt = Jimple.v().newIfStmt(Jimple.v().newEqExpr(intCounter,
								IntConstant.v(conditionCounter)), afterEx);
						body.getUnits().add(ifStmt);
						conditionCounter++;
						
						Local lcEx = generator.generateLocal(t.getException().getType());
						AssignStmt assignNewEx = Jimple.v().newAssignStmt(lcEx,
								Jimple.v().newNewExpr(t.getException().getType()));
						body.getUnits().add(assignNewEx);

						InvokeStmt consNewEx = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(lcEx,
								Scene.v().makeConstructorRef(exceptionClass, Collections.<Type>emptyList())));
						body.getUnits().add(consNewEx);
						
						ThrowStmt throwNewEx = Jimple.v().newThrowStmt(lcEx);
						body.getUnits().add(throwNewEx);
						
						body.getUnits().add(afterEx);
						return meth;
					}
									
				};
				epc.createDummyMain(thrower);
				exceptionThrowers.put(t.getException(), thrower);
				exceptionClass.addMethod(thrower);
			}
			
			// Call the exception thrower after the old call site
			Stmt throwCall = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(thrower.makeRef()));
			caller.getActiveBody().getUnits().insertBefore(throwCall, callSite);
		}
}
 
Example #27
Source File: BaseEntryPointCreator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
protected Stmt buildMethodCall(SootMethod methodToCall, Body body,
		Local classLocal, LocalGenerator gen,
		Set<SootClass> parentClasses){
	assert methodToCall != null : "Current method was null";
	assert body != null : "Body was null";
	assert gen != null : "Local generator was null";
	
	if (classLocal == null && !methodToCall.isStatic()) {
		logger.warn("Cannot call method {}, because there is no local for base object: {}", 
				methodToCall, methodToCall.getDeclaringClass());
		failedMethods.add(methodToCall);
		return null;
	}
	
	final InvokeExpr invokeExpr;
	List<Value> args = new LinkedList<Value>();
	if(methodToCall.getParameterCount()>0){
		for (Type tp : methodToCall.getParameterTypes())
			args.add(getValueForType(body, gen, tp, new HashSet<SootClass>(), parentClasses));
		
		if(methodToCall.isStatic())
			invokeExpr = Jimple.v().newStaticInvokeExpr(methodToCall.makeRef(), args);
		else {
			assert classLocal != null : "Class local method was null for non-static method call";
			if (methodToCall.isConstructor())
				invokeExpr = Jimple.v().newSpecialInvokeExpr(classLocal, methodToCall.makeRef(),args);
			else
				invokeExpr = Jimple.v().newVirtualInvokeExpr(classLocal, methodToCall.makeRef(),args);
		}
	}else{
		if(methodToCall.isStatic()){
			invokeExpr = Jimple.v().newStaticInvokeExpr(methodToCall.makeRef());
		}else{
			assert classLocal != null : "Class local method was null for non-static method call";
			if (methodToCall.isConstructor())
				invokeExpr = Jimple.v().newSpecialInvokeExpr(classLocal, methodToCall.makeRef());
			else
				invokeExpr = Jimple.v().newVirtualInvokeExpr(classLocal, methodToCall.makeRef());
		}
	}
	 
	Stmt stmt;
	if (!(methodToCall.getReturnType() instanceof VoidType)) {
		Local returnLocal = gen.generateLocal(methodToCall.getReturnType());
		stmt = Jimple.v().newAssignStmt(returnLocal, invokeExpr);
		
	} else {
		stmt = Jimple.v().newInvokeStmt(invokeExpr);
	}
	body.getUnits().add(stmt);
	
	// Clean up
	for (Object val : args)
		if (val instanceof Local && ((Value) val).getType() instanceof RefType)
			body.getUnits().add(Jimple.v().newAssignStmt((Value) val, NullConstant.v()));
	
	return stmt;
}
 
Example #28
Source File: SequentialEntryPointCreator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected SootMethod createDummyMainInternal(SootMethod mainMethod) {
	Map<String, Set<String>> classMap =
			SootMethodRepresentationParser.v().parseClassNames(methodsToCall, false);
	
	// create new class:
	Body body = mainMethod.getActiveBody();
		LocalGenerator generator = new LocalGenerator(body);
	
	// Create the classes
	for (String className : classMap.keySet()) {
		SootClass createdClass = Scene.v().forceResolve(className, SootClass.BODIES);
		createdClass.setApplicationClass();
		Local localVal = generateClassConstructor(createdClass, body);
		if (localVal == null) {
			logger.warn("Cannot generate constructor for class: {}", createdClass);
			continue;
		}
		
		// Create the method calls
		for (String method : classMap.get(className)) {
			SootMethodAndClass methodAndClass =
					SootMethodRepresentationParser.v().parseSootMethodString(method);
			SootMethod methodToInvoke = findMethod(Scene.v().getSootClass(
					methodAndClass.getClassName()), methodAndClass.getSubSignature());
			
			if (methodToInvoke == null)
				System.err.println("Method " + methodAndClass + " not found, skipping");
			else if (methodToInvoke.isConcrete()) {
				// Load the method
				methodToInvoke.retrieveActiveBody();
				buildMethodCall(methodToInvoke, body, localVal, generator);
			}
		}
	}
	
	// Jimple needs an explicit return statement
	body.getUnits().add(Jimple.v().newReturnVoidStmt());
	
	return mainMethod;
}
 
Example #29
Source File: DefaultEntryPointCreator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected SootMethod createDummyMainInternal(SootMethod mainMethod) {
	Map<String, Set<String>> classMap =
			SootMethodRepresentationParser.v().parseClassNames(methodsToCall, false);
	
	// create new class:
	Body body = mainMethod.getActiveBody();
		LocalGenerator generator = new LocalGenerator(body);
	HashMap<String, Local> localVarsForClasses = new HashMap<String, Local>();
	
	// create constructors:
	for(String className : classMap.keySet()){
		SootClass createdClass = Scene.v().forceResolve(className, SootClass.BODIES);
		createdClass.setApplicationClass();
		
		Local localVal = generateClassConstructor(createdClass, body);
		if (localVal == null) {
			logger.warn("Cannot generate constructor for class: {}", createdClass);
			continue;
		}
		localVarsForClasses.put(className, localVal);
	}
	
	// add entrypoint calls
	int conditionCounter = 0;
	JNopStmt startStmt = new JNopStmt();
	JNopStmt endStmt = new JNopStmt();
	Value intCounter = generator.generateLocal(IntType.v());
	body.getUnits().add(startStmt);
	for (Entry<String, Set<String>> entry : classMap.entrySet()){
		Local classLocal = localVarsForClasses.get(entry.getKey());
		for (String method : entry.getValue()){
			SootMethodAndClass methodAndClass =
					SootMethodRepresentationParser.v().parseSootMethodString(method);
			SootMethod currentMethod = findMethod(Scene.v().getSootClass(methodAndClass.getClassName()),
					methodAndClass.getSubSignature());
			if (currentMethod == null) {
				logger.warn("Entry point not found: {}", method);
				continue;
			}
			
			JEqExpr cond = new JEqExpr(intCounter, IntConstant.v(conditionCounter));
			conditionCounter++;
			JNopStmt thenStmt = new JNopStmt();
			JIfStmt ifStmt = new JIfStmt(cond, thenStmt);
			body.getUnits().add(ifStmt);
			buildMethodCall(currentMethod, body, classLocal, generator);
			body.getUnits().add(thenStmt);
		}
	}
	body.getUnits().add(endStmt);
	JGotoStmt gotoStart = new JGotoStmt(startStmt);
	body.getUnits().add(gotoStart);
	
	body.getUnits().add(Jimple.v().newReturnVoidStmt());
	NopEliminator.v().transform(body);
	eliminateSelfLoops(body);
	return mainMethod;
}
 
Example #30
Source File: GlobalInstanceTransformer.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
@Override
protected void internalTransform(String phaseName, Map<String, String> options) {
	// Get some system components
	SootClass scActivity = Scene.v().getSootClassUnsafe("android.app.Activity");
	SootClass scService = Scene.v().getSootClassUnsafe("android.app.Service");
	SootClass scBroadcastReceiver = Scene.v().getSootClassUnsafe("android.app.BroadcastReceiver");
	SootClass scContentProvider = Scene.v().getSootClassUnsafe("android.app.ContentProvider");
	
	// Get the registration class
	SootClass scRegistrar = Scene.v().getSootClassUnsafe("de.tu_darmstadt.sse.additionalappclasses.ComponentCallerService");
	SootMethodRef smRegistrarRef = scRegistrar.getMethodByName("registerGlobalInstance").makeRef();
	
	// Get the getClass() method
	Type classType = Scene.v().getType("java.lang.Class");
	SootMethodRef smGetClass = Scene.v().getObjectType().getSootClass().getMethod("java.lang.Class getClass()").makeRef();
	
	// Is this an Android component?
	for (SootClass sc : Scene.v().getApplicationClasses()) {
		// We only instrument user code
		if (!UtilInstrumenter.isAppDeveloperCode(sc))
			continue;
		
		// Is this class a component?
		if (Scene.v().getOrMakeFastHierarchy().canStoreType(sc.getType(), scActivity.getType())
				|| Scene.v().getOrMakeFastHierarchy().canStoreType(sc.getType(), scService.getType())
				|| Scene.v().getOrMakeFastHierarchy().canStoreType(sc.getType(), scBroadcastReceiver.getType())
				|| Scene.v().getOrMakeFastHierarchy().canStoreType(sc.getType(), scContentProvider.getType())) {
			Body b = null;
			Local locThis = null;
			Unit lastUnit = null;
			
			// Do we already have a constructor?
			SootMethod cons = sc.getMethodUnsafe("void <init>()");
			if (cons == null) {
				SootMethod smSuperClassCons = sc.getSuperclass().getMethodUnsafe("void <init>()");
				if (smSuperClassCons == null)
					continue;
				
				// Create the new constructor
				cons = new SootMethod("<init>", Collections.<Type>emptyList(), VoidType.v());
				sc.addMethod(cons);
				cons.setActiveBody(b = Jimple.v().newBody(cons));
				
				// Add a reference to the "this" object
				locThis = Jimple.v().newLocal("this", sc.getType());
				b.getLocals().add(locThis);
				b.getUnits().add(Jimple.v().newIdentityStmt(locThis, Jimple.v().newThisRef(sc.getType())));
				
				// Add a call to the superclass constructor
				b.getUnits().add(Jimple.v().newInvokeStmt(Jimple.v().newSpecialInvokeExpr(locThis,
						smSuperClassCons.makeRef())));
				
				// Add a return statement
				b.getUnits().add(lastUnit = Jimple.v().newReturnVoidStmt());
			}
			else {
				b = cons.getActiveBody();
				locThis = b.getThisLocal();
				
				// Find where we can inject out code. We must have called
				// the super constructor first, or the Dalvik verifier will
				// complain that the "this" local is not yet initialized.
				for (Unit u : b.getUnits()) {
					Stmt s = (Stmt) u;
					if (s.containsInvokeExpr()) {
						InvokeExpr iexpr = s.getInvokeExpr();
						if (iexpr instanceof SpecialInvokeExpr) {
							if (iexpr.getMethod().getName().equals("<init>")
									&& ((SpecialInvokeExpr) iexpr).getBase() == locThis) {
								lastUnit = b.getUnits().getSuccOf(u);
								break;
							}
						}
					}
				}
			}
			
			// Get the class
			LocalGenerator localGen = new LocalGenerator(b);
			Local locClass = localGen.generateLocal(classType);
			Stmt stmtAssignClass = Jimple.v().newAssignStmt(locClass, Jimple.v().newVirtualInvokeExpr(
					locThis, smGetClass));
			stmtAssignClass.addTag(new InstrumentedCodeTag());
			b.getUnits().insertBefore(stmtAssignClass, lastUnit);
			
			// Register the instance
			List<Value> argList = new ArrayList<>();
			argList.add(locClass);
			argList.add(locThis);
			Stmt stmtRegister = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(
					smRegistrarRef, argList));
			stmtRegister.addTag(new InstrumentedCodeTag());
			b.getUnits().insertBefore(stmtRegister, lastUnit);
		}
	}
}