Java Code Examples for soot.javaToJimple.LocalGenerator#generateLocal()

The following examples show how to use soot.javaToJimple.LocalGenerator#generateLocal() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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);
		}
	}
}
 
Example 18
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 19
Source File: DynamicValueTransformer.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
private void checkAndReport(Body b, Stmt curStmt, Value value, int paramIdx) {
	LocalGenerator localGenerator = new LocalGenerator(b);
	RefType stringType = RefType.v("java.lang.String");
	Value lhs = value;
	
	if(lhs instanceof StringConstant)
		return;
	else if(lhs instanceof IntConstant)
		return;
	
	// If this is a CharSequence, we need to convert it into a string
	if (lhs.getType() == RefType.v("java.lang.CharSequence") ||
			lhs.getType() == RefType.v("java.lang.StringBuilder") && lhs instanceof Local) {
		SootMethodRef toStringRef = Scene.v().getMethod("<java.lang.Object: "
				+ "java.lang.String toString()>").makeRef();
		Local stringLocal = localGenerator.generateLocal(stringType);
		Stmt stringAssignStmt = Jimple.v().newAssignStmt(stringLocal,
				Jimple.v().newVirtualInvokeExpr((Local) lhs, toStringRef));
		stringAssignStmt.addTag(new InstrumentedCodeTag());
		
		b.getUnits().insertBefore(stringAssignStmt, curStmt);
		lhs = stringLocal;
	}
	else if (lhs.getType() != IntType.v() && lhs.getType() != stringType)
		return;
	
	//new String() case
	if (value instanceof NewExpr)
		return;
	
	// Depending on the type of the value, we might need an intermediate local
	if (!(lhs instanceof Local)) {
		Local newLhs = localGenerator.generateLocal(lhs.getType());
		AssignStmt assignLocalStmt = Jimple.v().newAssignStmt(newLhs, lhs);
		assignLocalStmt.addTag(new InstrumentedCodeTag());
		b.getUnits().insertBefore(assignLocalStmt, curStmt);
		lhs = newLhs;
	}
	
	// Report the value
	Stmt reportValueStmt;
	if (lhs.getType() == stringType) {
		reportValueStmt = Jimple.v().newInvokeStmt(
				Jimple.v().newStaticInvokeExpr(refString, lhs, IntConstant.v(paramIdx)));
	}
	else if (lhs.getType() == IntType.v()) {
		reportValueStmt = Jimple.v().newInvokeStmt(
				Jimple.v().newStaticInvokeExpr(refInt, lhs, IntConstant.v(paramIdx)));
	}
	else
		return;
	reportValueStmt.addTag(new InstrumentedCodeTag());
	
	b.getUnits().insertBefore(reportValueStmt, curStmt);
}
 
Example 20
Source File: UtilInstrumenter.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
public static Local generateFreshLocal(Body body, Type type){
	LocalGenerator lg = new LocalGenerator(body);
	return lg.generateLocal(type);
}