soot.jimple.InvokeStmt Java Examples

The following examples show how to use soot.jimple.InvokeStmt. 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: TimingBombTransformer.java    From FuzzDroid with Apache License 2.0 7 votes vote down vote up
private void prepareAlarmManagerSet(Body body, InvokeStmt setStmt, SootMethodRef reportRef) {
	Value oldVal = setStmt.getInvokeExpr().getArg(1);
	
	Local longLocal = UtilInstrumenter.generateFreshLocal(body, LongType.v());
	SootMethod currentTimeMillis = Scene.v().getMethod("<java.lang.System: long currentTimeMillis()>");		
	StaticInvokeExpr timeInvoke = Jimple.v().newStaticInvokeExpr(currentTimeMillis.makeRef());		
	AssignStmt timeInitalize = Jimple.v().newAssignStmt(longLocal, timeInvoke);
	
	AddExpr addTime = Jimple.v().newAddExpr(longLocal, LongConstant.v(2000L));
	AssignStmt timeAssign = Jimple.v().newAssignStmt(longLocal, addTime);
			
	
	body.getUnits().insertBefore(timeInitalize, setStmt);
	body.getUnits().insertBefore(timeAssign, setStmt);
	
	InvokeExpr expr = setStmt.getInvokeExpr();
	expr.setArg(0, IntConstant.v(0));
	expr.setArg(1, longLocal);
	
	// Report the change
	InvokeStmt reportStmt = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(
			reportRef, oldVal, longLocal));
	reportStmt.addTag(new InstrumentedCodeTag());
	body.getUnits().insertAfter(reportStmt, setStmt);
}
 
Example #2
Source File: PathExecutionTransformer.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
	// Do not instrument methods in framework classes
	if (!canInstrumentMethod(body.getMethod()))
		return;
	
	instrumentInfoAboutNonAPICall(body);
	
	//important to use snapshotIterator here
	Iterator<Unit> iterator = body.getUnits().snapshotIterator();
	while(iterator.hasNext()){
		Unit unit = iterator.next();
		if(unit instanceof ReturnStmt || unit instanceof ReturnVoidStmt)
			instrumentInfoAboutReturnStmt(body, unit);
		else if(unit instanceof DefinitionStmt || unit instanceof InvokeStmt)
			instrumentInfoAboutNonApiCaller(body, unit);
		else if(unit instanceof IfStmt)
			instrumentEachBranchAccess(body, (IfStmt)unit);
	}				
}
 
Example #3
Source File: TimingBombTransformer.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
protected void internalTransform(Body body, String phaseName,
		Map<String, String> options) {
	
	if (!canInstrumentMethod(body.getMethod()))
		return;
	
	// Get a reference to the reporter method
	SootMethodRef reporterRef = Scene.v().getMethod("<de.tu_darmstadt.sse.additionalappclasses.tracing.BytecodeLogger: "
			+ "void reportTimingBomb(long,long)>").makeRef();
	
	for (Iterator<Unit> unitIt = body.getUnits().snapshotIterator(); unitIt.hasNext(); ) {
		Unit curUnit = unitIt.next();
		
		if(curUnit instanceof InvokeStmt) {
			InvokeStmt invokeStmt = (InvokeStmt) curUnit;
			InvokeExpr expr = invokeStmt.getInvokeExpr();
			String methodSig = expr.getMethod().getSignature();
			
			if(methodSig.equals("<android.app.AlarmManager: void set(int,long,android.app.PendingIntent)>"))
				prepareAlarmManagerSet(body, invokeStmt, reporterRef);
			else if(methodSig.equals("<android.os.Handler: boolean postDelayed(java.lang.Runnable,long)>"))
				prepareHandlerPostDelayed(body, invokeStmt, reporterRef);
		}
	}
	
}
 
Example #4
Source File: Util.java    From DroidForce with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Unit getSuperOnCreateUnit(Body b) {
	for(Unit u : b.getUnits()){
		if(u instanceof InvokeStmt){
			InvokeStmt invStmt = (InvokeStmt)u;
			if(invStmt.getInvokeExpr().getMethod().getSubSignature().equals("void onCreate(android.os.Bundle)"))
				return u;
		}
	}
	
	return null;
}
 
Example #5
Source File: MethodInvocationInstruction.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void finalize(DexBody body, DexlibAbstractInstruction successor) {
        // defer final jimplification to move result
        if (successor instanceof MoveResultInstruction) {
//            MoveResultInstruction i = (MoveResultInstruction)successor;
//            i.setExpr(invocation);
//            if (lineNumber != -1)
//                i.setTag(new SourceLineNumberTag(lineNumber));
          assign = Jimple.v().newAssignStmt(body.getStoreResultLocal(), invocation);
          setUnit(assign);
          addTags(assign);
          body.add(assign);
          unit = assign;
        // this is a invoke statement (the MoveResult had to be the direct successor for an expression)
        } else {
            InvokeStmt invoke = Jimple.v().newInvokeStmt(invocation);
            setUnit(invoke);
            addTags(invoke);
            body.add(invoke);
            unit = invoke;
        }

		if (IDalvikTyper.ENABLE_DVKTYPER) {
			Debug.printDbg(IDalvikTyper.DEBUG, "constraint special invoke: "+ assign);
			
          if (invocation instanceof InstanceInvokeExpr) {
            Type t = invocation.getMethodRef().declaringClass().getType();
            DalvikTyper.v().setType(((InstanceInvokeExpr) invocation).getBaseBox(), t, true);
            //DalvikTyper.v().setObjectType(assign.getLeftOpBox());
          }
          int i = 0;
          for (Type pt: (List<Type>)invocation.getMethodRef().parameterTypes()) {
            DalvikTyper.v().setType(invocation.getArgBox(i++), pt, true);
          }
          int op = (int)instruction.getOpcode().value;
          if (assign != null) {
              DalvikTyper.v().setType(assign.getLeftOpBox(), invocation.getType(), false);
          }
          
        }
    }
 
Example #6
Source File: ThisInliner.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private InvokeStmt getFirstSpecialInvoke(Body b){
    for (Unit u : b.getUnits()) {
        Stmt s = (Stmt)u;
        if (!(s instanceof InvokeStmt)) continue;

        InvokeExpr invokeExpr = ((InvokeStmt)s).getInvokeExpr();
        if (!(invokeExpr instanceof SpecialInvokeExpr)) continue;

        return (InvokeStmt)s;        
    }
    // but there will always be either a call to this() or to super()
    // from the constructor
    return null;
}
 
Example #7
Source File: InterproceduralConstantValuePropagator.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks whether the given method is a library stub method
 * @param method The method to check
 * @return True if the given method is an Android library stub, false
 * otherwise
 */
private boolean methodIsAndroidStub(SootMethod method) {		
	if (!(Options.v().src_prec() == Options.src_prec_apk
			&& method.getDeclaringClass().isLibraryClass()
			&& SystemClassHandler.isClassInSystemPackage(
					method.getDeclaringClass().getName())))
		return false;
	
	// Check whether there is only a single throw statement
	for (Unit u : method.getActiveBody().getUnits()) {
		if (u instanceof DefinitionStmt) {
			DefinitionStmt defStmt = (DefinitionStmt) u;
			if (!(defStmt.getRightOp() instanceof ThisRef)
					&& !(defStmt.getRightOp() instanceof ParameterRef)
					&& !(defStmt.getRightOp() instanceof NewExpr))
				return false;
		}
		else if (u instanceof InvokeStmt) {
			InvokeStmt stmt = (InvokeStmt) u;
			
			// Check for exception constructor invocations
			SootMethod callee = stmt.getInvokeExpr().getMethod();
			if (!callee.getSubSignature().equals("void <init>(java.lang.String)"))
				// Check for super class constructor invocation
				if (!(method.getDeclaringClass().hasSuperclass()
						&& callee.getDeclaringClass() == method.getDeclaringClass().getSuperclass()
						&& callee.getName().equals("<init>")))
					return false;
		}
		else if (!(u instanceof ThrowStmt))
			return false;
	}
	return true;
}
 
Example #8
Source File: TimingBombTransformer.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
private void prepareHandlerPostDelayed(Body body, Stmt invokeStmt, SootMethodRef reportRef) {
	InvokeExpr expr = invokeStmt.getInvokeExpr();
	
	Value oldValue = expr.getArg(1);
	Value newValue = LongConstant.v(2000L);
	
	expr.setArg(1, newValue);

	// Report the change
	InvokeStmt reportStmt = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(
			reportRef, oldValue, newValue));
	reportStmt.addTag(new InstrumentedCodeTag());
	body.getUnits().insertAfter(reportStmt, invokeStmt);
}
 
Example #9
Source File: ConstraintCollector.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void caseInvokeStmt(InvokeStmt stmt) {
	handleInvokeExpr(stmt.getInvokeExpr());
}
 
Example #10
Source File: Instrumenter.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
private void initializeHooking(ProcessManifest manifest) {						
	String applicationName = manifest.getApplicationName();
	//case 1
	if(applicationName != null) {
		if(applicationName.startsWith(".")) {
			String packageName = manifest.getPackageName();
			if(packageName == null)
				throw new RuntimeException("There is a problem with the package name");
			applicationName = packageName + applicationName;
		}
		SootClass applicationSootClass = Scene.v().getSootClass(applicationName);
		if(applicationSootClass != null) {				
			String attachMethodName = String.format("<%s: void attachBaseContext(android.content.Context)>", applicationName);
			SootMethod attachMethod = Scene.v().grabMethod(attachMethodName);	
			//case 1
			if(attachMethod != null) {
				Body body = attachMethod.getActiveBody();
				Local contextParam = body.getParameterLocal(0);
				
				List<Unit> unitsToInstrument = new ArrayList<Unit>();										
				String hookingHelperApplicationClassAttachMethodName = String.format("<%s: void initializeHooking(android.content.Context)>", UtilInstrumenter.HOOKER_CLASS);
				SootMethod hookingHelperApplicationClassAttachMethod = Scene.v().getMethod(hookingHelperApplicationClassAttachMethodName);
				if(hookingHelperApplicationClassAttachMethod == null)
					throw new RuntimeException("this should not happen");					
				SootMethodRef ref = hookingHelperApplicationClassAttachMethod.makeRef();					
				InvokeExpr invExpr = Jimple.v().newStaticInvokeExpr(ref, contextParam);
				unitsToInstrument.add(Jimple.v().newInvokeStmt(invExpr));
				
				
				Unit instrumentAfterUnit = null;
				for(Unit unit : body.getUnits()) {
					if(unit instanceof InvokeStmt) {
						InvokeStmt invStmt = (InvokeStmt)unit;
						if(invStmt.getInvokeExpr().getMethod().getSubSignature().equals("void attachBaseContext(android.content.Context)")) {
							instrumentAfterUnit = unit;
							break;
						}
					}
				}
				
				if(instrumentAfterUnit == null)
					throw new RuntimeException("this should not happen");
				body.getUnits().insertAfter(unitsToInstrument, instrumentAfterUnit);								
			}
			//case 2
			else {
				attachMethodName = String.format("<%s: void attachBaseContext(android.content.Context)>", UtilInstrumenter.HELPER_APPLICATION_FOR_HOOKING);	
				attachMethod = Scene.v().grabMethod(attachMethodName);
				if(attachMethod == null)
					throw new RuntimeException("this should not happen");
				
				List<Type> params = new ArrayList<Type>();
				SootClass contextClass = Scene.v().getSootClass("android.content.Context");
				params.add(contextClass.getType());
				SootMethod newAttachMethod = new SootMethod("attachBaseContext", params, VoidType.v());
				newAttachMethod.setModifiers(soot.Modifier.PROTECTED);
				newAttachMethod.setActiveBody(attachMethod.getActiveBody());
				applicationSootClass.addMethod(newAttachMethod);
			}
			
			//there is no need for our Application class
			Scene.v().getSootClass(UtilInstrumenter.HELPER_APPLICATION_FOR_HOOKING).setLibraryClass();
		}
		else {
			throw new RuntimeException("There is a problem with the Application class!");
		}
	}
	//case 3
	else{
		//there is no need for any instrumentation since the Application class is set to application-class.
	}
}
 
Example #11
Source File: PolicyEnforcementPoint.java    From DroidForce with GNU Lesser General Public License v2.1 4 votes vote down vote up
private List<Unit> instrumentIntentAddings(BiDiInterproceduralCFG<Unit, SootMethod> cfg,
		Unit unit, InvokeExpr sinkExpr, Set<ResultSourceInfo> sourceInfo){
	if(isMethodInterComponentSink(sinkExpr.getMethod())){
		SootMethod method = cfg.getMethodOf(unit);
		Body body = null;
		if(method.hasActiveBody())
			body = method.retrieveActiveBody();
		else
			throw new RuntimeException("No body found!");
		
		Set<String> sourceCategories = getDataIdList(sourceInfo);
		
		final String hashSetType = "java.util.HashSet";
		List<Unit> generated = new ArrayList<Unit>();
		
		//HashSet initialization
		Local hashSetLocal = generateFreshLocal(body, RefType.v(hashSetType));
		NewExpr newExpr = Jimple.v().newNewExpr(RefType.v(hashSetType));
		AssignStmt assignStmt = Jimple.v().newAssignStmt(hashSetLocal, newExpr);
		generated.add(assignStmt);
		
		//constructor call
		SpecialInvokeExpr constructorCall = Jimple.v().newSpecialInvokeExpr(hashSetLocal, Scene.v().getMethod("<java.util.HashSet: void <init>()>").makeRef());
		InvokeStmt constructorCallStmt = Jimple.v().newInvokeStmt(constructorCall);
		generated.add(constructorCallStmt);
		
		//add categories to HashSet
		for(String cat : sourceCategories){
			InterfaceInvokeExpr addCall = Jimple.v().newInterfaceInvokeExpr(hashSetLocal, Scene.v().getMethod("<java.util.Set: boolean add(java.lang.Object)>").makeRef(), StringConstant.v(cat));
			InvokeStmt addCallStmt = Jimple.v().newInvokeStmt(addCall);
			generated.add(addCallStmt);
		}
		
		//get Intent
		Value intent = sinkExpr.getArg(0);
		List<Object> args = new ArrayList<Object>();
		args.add(RefType.v("android.content.Intent"));
		args.add(intent);
		args.add(RefType.v(hashSetType));
		args.add(hashSetLocal);
		StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
				Settings.INSTRUMENTATION_HELPER_JAVA,
				"addTaintInformationToIntent",
				args);
		InvokeStmt invStmt = Jimple.v().newInvokeStmt(sie);
		generated.add(invStmt);
		
		return generated;
	}
	return Collections.emptyList();
}
 
Example #12
Source File: ConstructorFolder.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/** This method change all new Obj/<init>(args) pairs to new Obj(args) idioms. */
protected void internalTransform(Body b, String phaseName, Map options)
{
    GrimpBody body = (GrimpBody)b;

    if(Options.v().verbose())
        G.v().out.println("[" + body.getMethod().getName() +
            "] Folding constructors...");

  Chain units = body.getUnits();
  List<Unit> stmtList = new ArrayList<Unit>();
  stmtList.addAll(units);

  Iterator<Unit> it = stmtList.iterator();
  
  LocalUses localUses = LocalUses.Factory.newLocalUses(b);

  /* fold in NewExpr's with specialinvoke's */
  while (it.hasNext())
    {
      Stmt s = (Stmt)it.next();
        
      if (!(s instanceof AssignStmt))
        continue;
        
      /* this should be generalized to ArrayRefs */
      Value lhs = ((AssignStmt)s).getLeftOp();
      if (!(lhs instanceof Local))
        continue;
        
      Value rhs = ((AssignStmt)s).getRightOp();
      if (!(rhs instanceof NewExpr))
        continue;

      /* TO BE IMPLEMENTED LATER: move any copy of the object reference
         for lhs down beyond the NewInvokeExpr, with the rationale
         being that you can't modify the object before the constructor
         call in any case.

         Also, do note that any new's (object creation) without
         corresponding constructors must be dead. */
       
      List lu = localUses.getUsesOf(s);
      Iterator luIter = lu.iterator();
      boolean MadeNewInvokeExpr = false;
       
      while (luIter.hasNext())
        {
          Unit use = ((UnitValueBoxPair)(luIter.next())).unit;
          if (!(use instanceof InvokeStmt))
            continue;
          InvokeStmt is = (InvokeStmt)use;
          if (!(is.getInvokeExpr() instanceof SpecialInvokeExpr) ||
              lhs != ((SpecialInvokeExpr)is.getInvokeExpr()).getBase())
            continue;
          
          SpecialInvokeExpr oldInvoke = 
            ((SpecialInvokeExpr)is.getInvokeExpr());
          LinkedList invokeArgs = new LinkedList();
          for (int i = 0; i < oldInvoke.getArgCount(); i++)
            invokeArgs.add(oldInvoke.getArg(i));
          
          AssignStmt constructStmt = Grimp.v().newAssignStmt
            ((AssignStmt)s);
          constructStmt.setRightOp
            (Grimp.v().newNewInvokeExpr
             (((NewExpr)rhs).getBaseType(), oldInvoke.getMethodRef(), invokeArgs));
          MadeNewInvokeExpr = true;
          
          use.redirectJumpsToThisTo(constructStmt);
          units.insertBefore(constructStmt, use);
          units.remove(use);
        }
      if (MadeNewInvokeExpr)
        {
          units.remove(s);
        }
    }
}
 
Example #13
Source File: UnitThrowAnalysis.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void caseInvokeStmt(InvokeStmt s) {
    result = result.add(mightThrow(s.getInvokeExpr()));
}
 
Example #14
Source File: MethodCallFinder.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public List<ASTStatementSequenceNode> createChangedBodyPart(InvokeStmt s, List body, ASTParentNodeFinder finder){
//get parent node of invoke stmt
Object parent = finder.getParentOf(s);
if(parent == null){
    throw new RuntimeException ("MethodCall FInder: parent of invoke stmt not found");
}

ASTNode parentNode = (ASTNode)parent;
if(!(parentNode instanceof ASTStatementSequenceNode)){
    throw new RuntimeException ("MethodCall FInder: parent node not a stmt seq node");
}    

ASTStatementSequenceNode orignal = (ASTStatementSequenceNode)parentNode;


//copying the stmts till above the inoke stmt into one stmt sequence node
List<Object> newInitialNode = new ArrayList<Object>();
Iterator<Object> it = orignal.getStatements().iterator();
while(it.hasNext()){
    AugmentedStmt as = (AugmentedStmt)it.next();
    Stmt tempStmt = as.get_Stmt();
    if(tempStmt != s){
    	newInitialNode.add(as);
    }
    else{
    	//the first time we get to a stmt which points to the invoke stmt we break
    	break;
    }
}

//copy remaining stmts into the AFTER stmt sequence node
List<Object> newSecondNode = new ArrayList<Object>();
while(it.hasNext()){
    newSecondNode.add(it.next());
}

List<ASTStatementSequenceNode> toReturn = new ArrayList<ASTStatementSequenceNode>();

if(newInitialNode.size()!=0)
    toReturn.add(new ASTStatementSequenceNode(newInitialNode));

//add inline methods body
toReturn.addAll(body);

if(newSecondNode.size()!=0)
    toReturn.add(new ASTStatementSequenceNode(newSecondNode));

return toReturn;
   }
 
Example #15
Source File: MethodCallFinder.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void inInvokeStmt(InvokeStmt s){
   	InvokeExpr invokeExpr = s.getInvokeExpr();
   	SootMethod maybeInline = invokeExpr.getMethod();

   	//check whether we want to inline
   	ASTMethodNode toInlineASTMethod = cleaner.inline(maybeInline);
   	if(toInlineASTMethod ==null){
   		//not to inline
   		return;
   	}
   	else{//yes we want to inline 
   		// we know that the method to be inlined has no declarations.
   		List<Object> subBodies = toInlineASTMethod.get_SubBodies();
   		if(subBodies.size() != 1){
   			throw new RuntimeException ("Found ASTMEthod node with more than one subBodies");
   		}
   		List body = (List)subBodies.get(0);

    
   		ASTParentNodeFinder finder = new ASTParentNodeFinder();
   		underAnalysis.apply(finder);
    
   		List<ASTStatementSequenceNode> newChangedBodyPart = createChangedBodyPart(s,body,finder);


   		boolean replaced = replaceSubBody(s,newChangedBodyPart,finder);

    
   		if(replaced){
   			//so the invoke stmt has been replaced with the body of the method invoked

   			/*
   			 * if the inlined method contained an assignment to a static field
   			 * we want to replace that with a throw stmt
   			 */
   			StaticDefinitionFinder defFinder = new StaticDefinitionFinder(maybeInline);
   			toInlineASTMethod.apply(defFinder);
   			
   			if(defFinder.anyFinalFieldDefined()){
   				//create throw stmt to be added to inlined method

   				//create a SootMethodRef
   				SootClass runtime = Scene.v().loadClassAndSupport("java.lang.RuntimeException");
   				if(runtime.declaresMethod("void <init>(java.lang.String)")){
		SootMethod sootMethod = runtime.getMethod("void <init>(java.lang.String)");
		SootMethodRef methodRef = sootMethod.makeRef();
		RefType myRefType = RefType.v(runtime);
		StringConstant tempString = StringConstant.v("This method used to have a definition of a final variable. "+
							     "Dava inlined the definition into the static initializer");
		List list = new ArrayList();
		list.add(tempString);
		
		GNewInvokeExpr newInvokeExpr = new GNewInvokeExpr(myRefType,methodRef,list);

		GThrowStmt throwStmt = new GThrowStmt(newInvokeExpr);
					
		AugmentedStmt augStmt = new AugmentedStmt(throwStmt);
		List<Object> sequence = new ArrayList<Object>();
		sequence.add(augStmt);
		ASTStatementSequenceNode seqNode = new ASTStatementSequenceNode(sequence);
		List<Object> subBody = new ArrayList<Object>();
		subBody.add(seqNode);

		toInlineASTMethod.replaceBody(subBody);
	    }
	}
    }

}
   }
 
Example #16
Source File: StmtVisitor.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
       exprV.setOrigStmt(stmt);
	stmt.getInvokeExpr().apply(exprV);
}
 
Example #17
Source File: TypeResolverBV.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void split_new()
 {
LocalDefs defs = LocalDefs.Factory.newLocalDefs(stmtBody);
   PatchingChain<Unit> units = stmtBody.getUnits();
   Stmt[] stmts = new Stmt[units.size()];

   units.toArray(stmts);
   
   for (Stmt stmt : stmts) {
if(stmt instanceof InvokeStmt)
  {
    InvokeStmt invoke = (InvokeStmt) stmt;
    
    if(invoke.getInvokeExpr() instanceof SpecialInvokeExpr)
      {
	SpecialInvokeExpr special = (SpecialInvokeExpr) invoke.getInvokeExpr();
	
	if(special.getMethodRef().name().equals("<init>"))
	  {
	    List<Unit> deflist = defs.getDefsOfAt((Local) special.getBase(), invoke);
	    
	    while(deflist.size() == 1)
	      {
		Stmt stmt2 = (Stmt) deflist.get(0);
		
		if(stmt2 instanceof AssignStmt)
		  {
		    AssignStmt assign = (AssignStmt) stmt2;
		    
		    if(assign.getRightOp() instanceof Local)
		      {
			deflist = defs.getDefsOfAt((Local) assign.getRightOp(), assign);
			continue;
		      }
		    else if(assign.getRightOp() instanceof NewExpr)
		      {			
			// We split the local.
			//G.v().out.println("split: [" + assign + "] and [" + stmt + "]");
			Local newlocal = Jimple.v().newLocal("tmp", null);
			stmtBody.getLocals().add(newlocal);
			
			special.setBase(newlocal);
			
			units.insertAfter(Jimple.v().newAssignStmt(assign.getLeftOp(), newlocal), assign);
			assign.setLeftOp(newlocal);
		      }
		  }
		break;
	      }
	  }
      }
  }
     }
 }
 
Example #18
Source File: ConstraintCollector.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void caseInvokeStmt(InvokeStmt stmt) {
	handleInvokeExpr(stmt.getInvokeExpr());
}
 
Example #19
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 #20
Source File: ConstraintChecker.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void caseInvokeStmt(InvokeStmt stmt) {
	handleInvokeExpr(stmt.getInvokeExpr(), stmt);
}
 
Example #21
Source File: TypeResolver.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void split_new()
 {
LocalDefs defs = LocalDefs.Factory.newLocalDefs(stmtBody);
   PatchingChain<Unit> units = stmtBody.getUnits();
   Stmt[] stmts = new Stmt[units.size()];

   units.toArray(stmts);
   
   for (Stmt stmt : stmts) {
if(stmt instanceof InvokeStmt)
  {
    InvokeStmt invoke = (InvokeStmt) stmt;
    
    if(invoke.getInvokeExpr() instanceof SpecialInvokeExpr)
      {
	SpecialInvokeExpr special = (SpecialInvokeExpr) invoke.getInvokeExpr();
	
	if("<init>".equals(special.getMethodRef().name()))
	  {
	    List<Unit> deflist = defs.getDefsOfAt((Local) special.getBase(), invoke);
	    
	    while(deflist.size() == 1)
	      {
		Stmt stmt2 = (Stmt) deflist.get(0);
		
		if(stmt2 instanceof AssignStmt)
		  {
		    AssignStmt assign = (AssignStmt) stmt2;
		    
		    if(assign.getRightOp() instanceof Local)
		      {
			deflist = defs.getDefsOfAt((Local) assign.getRightOp(), assign);
			continue;
		      }
		    else if(assign.getRightOp() instanceof NewExpr)
		      {			
			// We split the local.
			//G.v().out.println("split: [" + assign + "] and [" + stmt + "]");
			Local newlocal = Jimple.v().newLocal("tmp", null);
			stmtBody.getLocals().add(newlocal);
			
			special.setBase(newlocal);
			
			units.insertAfter(Jimple.v().newAssignStmt(assign.getLeftOp(), newlocal), assign);
			assign.setLeftOp(newlocal);
		      }
		  }
		break;
	      }
	  }
      }
  }
     }
 }
 
Example #22
Source File: UseChecker.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void caseInvokeStmt(InvokeStmt stmt)
{
	this.handleInvokeExpr(stmt.getInvokeExpr(), stmt);
}
 
Example #23
Source File: TypeResolver.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void split_new()
{		
	LocalDefs defs = LocalDefs.Factory.newLocalDefs(jb);
	PatchingChain<Unit> units = this.jb.getUnits();
	Stmt[] stmts = new Stmt[units.size()];
	
	units.toArray(stmts);
	
	for ( Stmt stmt : stmts )
	{
		if ( stmt instanceof InvokeStmt )
		{
			InvokeStmt invoke = (InvokeStmt)stmt;
			
			if ( invoke.getInvokeExpr() instanceof SpecialInvokeExpr )
			{
				SpecialInvokeExpr special
					= (SpecialInvokeExpr)invoke.getInvokeExpr();
				
				if ( special.getMethodRef().name().equals("<init>") )
				{
					List<Unit> deflist = defs.getDefsOfAt(
						(Local)special.getBase(), invoke);
					
					while ( deflist.size() == 1 )
					{
						Stmt stmt2 = (Stmt)deflist.get(0);
						
						if ( stmt2 instanceof AssignStmt )
						{
							AssignStmt assign = (AssignStmt)stmt2;
							
							if ( assign.getRightOp() instanceof Local )
							{
								deflist = defs.getDefsOfAt(
									(Local)assign.getRightOp(), assign);
								continue;
							}
							else if ( assign.getRightOp()
								instanceof NewExpr )
							{
								Local newlocal = Jimple.v().newLocal(
									"tmp", null);
								newlocal.setName("tmp$" + System.identityHashCode(newlocal));
								this.jb.getLocals().add(newlocal);
								
								special.setBase(newlocal);
								
								DefinitionStmt assignStmt
									= Jimple.v().newAssignStmt(
									assign.getLeftOp(), newlocal);
								Unit u = Util.findLastIdentityUnit(jb, assign);
								units.insertAfter(assignStmt, u);
								assign.setLeftOp(newlocal);
								
								this.addLocal(newlocal);
								this.initAssignment(assignStmt);
							}
						}
						break;
					}
				}
			}
		}
	}
}
 
Example #24
Source File: PathExecutionTransformer.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
private void instrumentInfoAboutNonApiCaller(Body body, Unit unit)
{	
	//our instrumented code
	if(unit.hasTag(InstrumentedCodeTag.name))
		return;
	
	InvokeExpr invokeExpr = null;
	if(unit instanceof DefinitionStmt)
	{
		DefinitionStmt defStmt = (DefinitionStmt)unit;
		if(defStmt.containsInvokeExpr())
		{
			invokeExpr = defStmt.getInvokeExpr();
		}
	}					
	else if(unit instanceof InvokeStmt)
	{
		InvokeStmt invokeStmt = (InvokeStmt)unit;
		invokeExpr = invokeStmt.getInvokeExpr();
	}				
	
	if(invokeExpr != null)
	{			
		if(!UtilInstrumenter.isApiCall(invokeExpr))
		{
			String invokeExprMethodSignature = invokeExpr.getMethod().getSignature();
			
			List<Value> parameter = invokeExpr.getArgs();
			List<Unit> generated = new ArrayList<Unit>();
			Pair<Value, List<Unit>> arrayRefAndInstrumentation = UtilInstrumenter.generateParameterArray(parameter, body);
			
			List<Unit> generatedArrayInstrumentation = arrayRefAndInstrumentation.getSecond();
			Value arrayRef = arrayRefAndInstrumentation.getFirst();
			
			Unit generatedInvokeStmt = UtilInstrumenter.makeJimpleStaticCallForPathExecution("logInfoAboutNonApiMethodCaller", 	
					RefType.v("java.lang.String"), StringConstant.v(body.getMethod().getSignature()),
					RefType.v("java.lang.String"), StringConstant.v(invokeExprMethodSignature),
					UtilInstrumenter.getParameterArrayType(), (parameter.isEmpty())? NullConstant.v() : arrayRef);
			generatedInvokeStmt.addTag(new InstrumentedCodeTag());
			generated.addAll(generatedArrayInstrumentation);
			generated.add(generatedInvokeStmt);

			body.getUnits().insertBefore(generated, unit);
		}
	}		
}
 
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: StmtTemplatePrinter.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void caseInvokeStmt(InvokeStmt stmt) {
	String varName = printValueAssignment(stmt.getInvokeExpr(), "ie");
	printStmt(stmt,varName);
}
 
Example #27
Source File: StmtTranslator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void caseInvokeStmt(InvokeStmt stmt) {
	InvokeExpr expr = stmt.getInvokeExpr();
	Variable lvar = jt.makeVariable(expr);
	et.translateExpr(lvar, stmt.getInvokeExprBox());
}
 
Example #28
Source File: JimpleStmtVisitorImpl.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
@Override
public void caseInvokeStmt(InvokeStmt stmt) {
	InvokeExpr invokeExpr = stmt.getInvokeExpr();
	SootClass declaringClass = invokeExpr.getMethod().getDeclaringClass();
	if(exprVisitor.isExpressionThatNeedsToBeConvertedToSMT(invokeExpr))
		exprVisitor.convertSpecialExpressionsToSMT(invokeExpr, stmt);
	else if(UtilInstrumenter.isAppDeveloperCode(declaringClass)) {
		SootMethod method = invokeExpr.getMethod();
		Body body = method.retrieveActiveBody();
		
		SMTBinding newRhs = getBindingForTaintedValue(stmt);
		//if there is no taint-tracking involved (newRhs == null), we do not have to do anything here
		if(newRhs == null)
			return;
		
		int indexOfInterest = -1;
		for(int i = 0; i < invokeExpr.getArgCount(); i++) {
			if(newRhs.getVariableName().equals(invokeExpr.getArg(i).toString())) {
				indexOfInterest = i;
				break;
			}
		}
		
		if(indexOfInterest == -1)
			return;
		
		
		for(Unit unit : body.getUnits()) {
			if(unit instanceof IdentityStmt) {
				IdentityStmt identity = (IdentityStmt)unit;
				Value rhs = identity.getRightOp();
				if(rhs instanceof ParameterRef) {
					ParameterRef param = (ParameterRef)rhs;
					if(param.getIndex() == indexOfInterest) {
						Value lhs = identity.getLeftOp();
						SMTBinding newLhs = createNewBindingForValue(lhs);
						addValueBindingToVariableDeclaration(lhs, newLhs);
						SMTSimpleAssignment simpleAssignment = new SMTSimpleAssignment(newLhs, new SMTBindingValue(newRhs));
						SMTAssertStatement assignmentAssert = new SMTAssertStatement(simpleAssignment);
						addAssertStmtToAllPrograms(assignmentAssert);
					}
				}					
			}
		}
	}		
	else {
		System.err.println(String.format("Double-Check if the following method contains useful information which can be extracted: \n%s", stmt));
	}
	
}