Java Code Examples for soot.jimple.InvokeExpr#getMethod()

The following examples show how to use soot.jimple.InvokeExpr#getMethod() . 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: FileFuzzer.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
private AnalysisDecision getFileFormatFromDataflow(int codePosID ) {
	Unit unit = codePositionManager.getUnitForCodePosition(codePosID);
	if(unit instanceof Stmt) {		
		Stmt stmt = (Stmt)unit;
		if(stmt.containsInvokeExpr()) {
			InvokeExpr inv = stmt.getInvokeExpr();
			SootMethod sm = inv.getMethod();
			Pair<Integer, Object> paramValue = retrieveCorrectFileInformation(sm);
							
			ServerResponse response = new ServerResponse();
			response.setAnalysisName(getAnalysisName());
	        response.setResponseExist(true);      
	        response.setParamValues(Collections.singleton(paramValue));
			AnalysisDecision finalDecision = new AnalysisDecision();
			finalDecision.setAnalysisName(getAnalysisName());
			finalDecision.setDecisionWeight(8);
		    finalDecision.setServerResponse(response);		    
		    return finalDecision;
		}
		else
			return noResults();
	}
	else {
		return noResults();
	}
}
 
Example 2
Source File: TypeStateMachineWeightFunctions.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
public TransitionFunction callToReturn(Node<Statement, Val> curr, Node<Statement, Val> succ,
        InvokeExpr invokeExpr) {
    Set<Transition> res = Sets.newHashSet();
    if (invokeExpr instanceof InstanceInvokeExpr) {
        SootMethod method = invokeExpr.getMethod();
        InstanceInvokeExpr e = (InstanceInvokeExpr) invokeExpr;
        if (e.getBase().equals(succ.fact().value())) {
            for (MatcherTransition trans : transition) {
                if (trans.matches(method) && (trans.getType().equals(Type.OnCallToReturn)
                        || trans.getType().equals(Type.OnCallOrOnCallToReturn))) {
                    res.add(trans);
                }
            }
        }
    }
    return (res.isEmpty() ? getOne() : new TransitionFunction(res, Collections.singleton(succ.stmt())));
}
 
Example 3
Source File: Model.java    From DroidRA with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns the arguments for a potential COAL query.
 * 
 * @param stmt A program statement.
 * @return An array of arguments if the statement is for a COAL query, null otherwise.
 */
public Argument[] getArgumentsForQuery(Stmt stmt) {
  if (stmt.containsInvokeExpr()) {
    InvokeExpr invokeExpr = stmt.getInvokeExpr();
    SootMethod method = invokeExpr.getMethod();
    if (AnalysisParameters.v().isAnalysisClass(method.getDeclaringClass().getName())
        && method.isConcrete() && method.hasActiveBody()) {
      MethodDescription description = queryToMethodDescriptionMap.get(method.getSignature());
      if (description == null) {
        return null;
      } else {
        return description.getArguments();
      }
    }
    return getArgumentsFromMethodDescription(queryToMethodDescriptionMap, invokeExpr);
  }
  return null;
}
 
Example 4
Source File: PolicyEnforcementPoint.java    From DroidForce with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Return true if the method corresponding to the source 'si' is an
 * Inter Component Communication source method such as "Intent.getExtras()".
 * @param si
 * @param cfg
 * @return
 */
private boolean isInterComponentSourceNoCallback(ResultSourceInfo si, BiDiInterproceduralCFG<Unit, SootMethod> cfg){
	if(!si.getSource().containsInvokeExpr())
		return false;
	
	InvokeExpr invExpr = si.getSource().getInvokeExpr();
	SootMethod sm = invExpr.getMethod();
			
	for(SourceSinkDefinition meth : sources){
		AndroidMethod am = (AndroidMethod) meth.getMethod();
		if(am.getCategory() == CATEGORY.INTER_APP_COMMUNICATION){
			if(am.getSubSignature().equals(sm.getSubSignature())) {
				log.info("source is: "+ am);
				return true;
			}
		}
	}
	
	return false;
}
 
Example 5
Source File: ClassLoaderTransformer.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
protected void internalTransform(Body b, String phaseName,
		Map<String, String> options) {
	// Do not instrument methods in framework classes
	if (!canInstrumentMethod(b.getMethod()))
		return;
	
	// Check for calls to DexFile.loadClass
	for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext(); ) {
		Stmt stmt = (Stmt) unitIt.next();
		if (stmt.hasTag(InstrumentedCodeTag.name))
			continue;
		if (!(stmt instanceof AssignStmt))
			continue;
		AssignStmt assignStmt = (AssignStmt) stmt;
		
		if (stmt.containsInvokeExpr()) {
			InvokeExpr iexpr = stmt.getInvokeExpr();
			if (iexpr.getMethod()  == methodDexFileLoadClass) {
				List<Value> args = new ArrayList<>();
				args.add(((InstanceInvokeExpr) iexpr).getBase());
				args.addAll(iexpr.getArgs());
				InvokeExpr newLoadExpr = Jimple.v().newStaticInvokeExpr(methodOwnLoader.makeRef(), args);
				b.getUnits().swapWith(stmt, Jimple.v().newAssignStmt(assignStmt.getLeftOp(), newLoadExpr));
			}
		}
	}
}
 
Example 6
Source File: FileFuzzer.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
private boolean fileFormatAvailable(int codePosID){
	Unit unit = codePositionManager.getUnitForCodePosition(codePosID);
	if(unit instanceof Stmt) {
		Stmt stmt = (Stmt)unit;
		if(stmt.containsInvokeExpr()) {
			InvokeExpr inv = stmt.getInvokeExpr();
			SootMethod sm = inv.getMethod();
			String methodSig = sm.getSignature();			

			switch(methodSig) {
				case "<android.content.Context: java.io.FileInputStream openFileInput(java.lang.String)>":  
				case "<java.io.File: void <init>(java.io.File,java.lang.String)>":
				case "<java.io.File: void <init>(java.lang.String,java.lang.String)>":
				case "<java.io.File: void <init>(java.lang.String)>":
				case "<java.io.File: void <init>(java.net.URI)>":
				case "<android.content.ContextWrapper: java.io.FileInputStream openFileInput(java.lang.String)>":
				case "<android.content.Context: java.io.File getFileStreamPath(java.lang.String)>":
				case "<android.content.Context: java.io.File getDir(java.lang.String,int)>":
				case "<android.content.Context: java.io.File getDatabasePath(java.lang.String)>":
				case "<android.content.ContextWrapper: java.io.File getFileStreamPath(java.lang.String)>":
				case "<android.content.ContextWrapper: java.io.File getDir(java.lang.String,int)>":
				case "<android.content.ContextWrapper: java.io.File getDatabasePath(java.lang.String)>":
				case "<android.database.sqlite.SQLiteDatabase: android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.io.File,android.database.sqlite.SQLiteDatabase$CursorFactory)>":
				case "<android.database.sqlite.SQLiteDatabase: android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String,android.database.sqlite.SQLiteDatabase$CursorFactory)>":
				case "<android.database.sqlite.SQLiteDatabase: android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String,android.database.sqlite.SQLiteDatabase$CursorFactory,android.database.DatabaseErrorHandler)>":
				case "<android.content.ContextWrapper: android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String,android.database.sqlite.SQLiteDatabase$CursorFactory)>":
				case "<android.content.ContextWrapper: android.database.sqlite.SQLiteDatabase openOrCreateDatabase(java.lang.String,android.database.sqlite.SQLiteDatabase$CursorFactory,android.database.DatabaseErrorHandler)>":
					return true;
				default:
					return false;
			}
		}
		else
			return false;
	}
	else
		return false;
}
 
Example 7
Source File: AbstractInfoflowProblem.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks whether the given call is a call to Executor.execute() or
 * AccessController.doPrivileged() and whether the callee matches
 * the expected method signature
 * @param ie The invocation expression to check
 * @param dest The callee of the given invocation expression
 * @return True if the given invocation expression and callee are a valid
 * call to Executor.execute() or AccessController.doPrivileged()
 */
protected boolean isExecutorExecute(InvokeExpr ie, SootMethod dest) {
	if (ie == null || dest == null)
		return false;
	
	SootMethod ieMethod = ie.getMethod();
	if (!ieMethod.getName().equals("execute") && !ieMethod.getName().equals("doPrivileged"))
		return false;
	
	final String ieSubSig = ieMethod.getSubSignature();
	final String calleeSubSig = dest.getSubSignature();
	
	if (ieSubSig.equals("void execute(java.lang.Runnable)")
			&& calleeSubSig.equals("void run()"))
		return true;
	
	if (calleeSubSig.equals("java.lang.Object run()")) {
		if (ieSubSig.equals("java.lang.Object doPrivileged(java.security.PrivilegedAction)"))
			return true;
		if (ieSubSig.equals("java.lang.Object doPrivileged(java.security.PrivilegedAction,"
				+ "java.security.AccessControlContext)"))
			return true;
		if (ieSubSig.equals("java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction)"))
			return true;
		if (ieSubSig.equals("java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction,"
				+ "java.security.AccessControlContext)"))
			return true;
	}
	return false;
}
 
Example 8
Source File: Model.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the arguments associated with a method descriptor.
 * 
 * @param signatureToMethodDescriptionMap A map from signatures to method descriptors.
 * @param invokeExpr An invoke expression.
 * @return An array of arguments if arguments are found for the method descriptor, null otherwise.
 */
private Argument[] getArgumentsFromMethodDescription(
    Map<String, MethodDescription> signatureToMethodDescriptionMap, InvokeExpr invokeExpr) {
  SootMethod method = invokeExpr.getMethod();
  String signature = method.getSignature();
  MethodDescription methodDescription = signatureToMethodDescriptionMap.get(signature);
  if (methodDescription != null) {
    return methodDescription.getArguments();
  }
  signature = method.getSubSignature();
  methodDescription = signatureToMethodDescriptionMap.get(signature);
  if (methodDescription == null) {
    return null;
  }
  String superclassName = methodDescription.getBaseClass();
  if (superclassName == null || !Scene.v().containsClass(superclassName)
      || invokeExpr instanceof InterfaceInvokeExpr) {
    return null;
  }
  SootClass superclass = Scene.v().getSootClass(superclassName);
  String baseType;
  if (invokeExpr instanceof InstanceInvokeExpr) {
    Value baseValue = ((InstanceInvokeExpr) invokeExpr).getBase();
    baseType = baseValue.getType().toString();
  } else {
    baseType = invokeExpr.getMethod().getDeclaringClass().getName();
  }
  if (Scene.v().containsClass(baseType)
      && Scene.v().getActiveHierarchy()
          .isClassSubclassOfIncluding(Scene.v().getSootClass(baseType), superclass)) {
    return methodDescription.getArguments();
  } else {
    return null;
  }
}
 
Example 9
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));
	}
	
}
 
Example 10
Source File: StringToPrimitiveTypeExtractorDataflowHandler.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
@Override
public void onResultsAvailable(IInfoflowCFG cfg, InfoflowResults results) {
	for(ResultSinkInfo sinkInfo : results.getResults().keySet()) {
		Stmt sink = sinkInfo.getSink();
		InvokeExpr sinkExpr = sink.getInvokeExpr();
		SootMethod sinkMethod = sinkExpr.getMethod();
		
		Set<Object> values = new HashSet<Object>();			
		
		switch(sinkMethod.getSignature()) {
			case "<java.lang.Boolean: boolean parseBoolean(java.lang.String)>":
				values.add("true");
				values.add("false");
				break;
			
			//we add two random values
			case "<java.lang.Byte: byte parseByte(java.lang.String)>":
				values.add("0");
				values.add("42");
				break;
				
				//we add two random values
			case "<java.lang.Byte: byte parseByte(java.lang.String, int)>":
				values.add("0");
				values.add("42");
				break;
			
			//we add two random values
			case "<java.lang.Short: short parseShort(java.lang.String)>":
				values.add("0");
				values.add("42");
				break;
				
				//we add two random values
			case "<java.lang.Short: short parseShort(java.lang.String, int)>":
				values.add("0");
				values.add("42");
				break;
				
			//we add two random values
			case "<java.lang.Integer: int parseInteger(java.lang.String)>":
				values.add("0");
				values.add("42");
				break;
				
				//we add two random values
			case "<java.lang.Integer: int parseInteger(java.lang.String, int)>":
				values.add("0");
				values.add("42");
				break;
				
				//we add two random values
			case "<java.lang.Long: long parseLong(java.lang.String)>":
				values.add("0");
				values.add("42");
				break;
				
				//we add two random values
			case "<java.lang.Long: long parseLong(java.lang.String, int)>":
				values.add("0");
				values.add("42");
				break;
				
			//we add two random values
			case "<java.lang.Double: double parseDouble(java.lang.String)>":
				values.add("0");
				values.add("42.0");
				break;
				
			//we add two random values
			case "<java.lang.Float: float parseFloat(java.lang.String)>":
				values.add("0");
				values.add("20.75f");
				break;					
		}						
		
		//all sources
		Set<ResultSourceInfo> sourceInfos = results.getResults().get(sinkInfo);
		for(ResultSourceInfo sourceInfo : sourceInfos) {
			Stmt source = sourceInfo.getSource();
			int sourceID = codePositionManager.getCodePositionForUnit(source).getID();
			valuesToFuzz.put(sourceID, values);
		}
	}
	
}
 
Example 11
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 12
Source File: PointsToAnalysis.java    From vasco with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Computes the targets of an invoke expression using a given points-to graph.
 * 
 * <p>For static invocations, there is only target. For instance method
 * invocations, the targets depend on the type of receiver objects pointed-to
 * by the instance variable whose method is being invoked.</p>
 * 
 * <p>If the instance variable points to a summary node, then the returned
 * value is <tt>null</tt> signifying a <em>default</em> call-site.</p>
 */
private Set<SootMethod> getTargets(SootMethod callerMethod, Stmt callStmt, InvokeExpr ie, PointsToGraph ptg) {
	Set<SootMethod> targets = new HashSet<SootMethod>();
	SootMethod invokedMethod = ie.getMethod();
	String subsignature = invokedMethod.getSubSignature();
	
	// Static and special invocations refer to the target method directly
	if (ie instanceof StaticInvokeExpr || ie instanceof SpecialInvokeExpr) {
		targets.add(invokedMethod);
		return targets;
	} else {
		assert (ie instanceof InterfaceInvokeExpr || ie instanceof VirtualInvokeExpr);
		// Get the receiver
		Local receiver = (Local) ((InstanceInvokeExpr) ie).getBase();
		// Get what objects the receiver points-to
		Set<AnyNewExpr> heapNodes = ptg.getTargets(receiver);
		if (heapNodes != null) {
			// For each object, find the invoked method for the declared type
			for (AnyNewExpr heapNode : heapNodes) {
				if (heapNode == PointsToGraph.SUMMARY_NODE) {						
					// If even one pointee is a summary node, then this is a default site
					return null;
				} else if (heapNode instanceof NewArrayExpr) {
					// Probably getClass() or something like that on an array
					return null;
				}
				// Find the top-most class that declares a method with the given
				// signature and add it to the resulting targets
				SootClass sootClass = ((RefType) heapNode.getType()).getSootClass();
				do {
					if (sootClass.declaresMethod(subsignature)) {
						targets.add(sootClass.getMethod(subsignature));
						break;
					} else if (sootClass.hasSuperclass()) {
						sootClass = sootClass.getSuperclass();
					} else {
						sootClass = null;
					}
				} while (sootClass != null);
			}
		}
		if (targets.isEmpty()) {
			// System.err.println("Warning! Null call at: " + callStmt+ " in " + callerMethod);
		}
		return targets;
	}
}