Java Code Examples for soot.jimple.Stmt#getInvokeExpr()

The following examples show how to use soot.jimple.Stmt#getInvokeExpr() . 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: 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 2
Source File: SootToDexUtils.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public static int getOutWordCount(Collection<Unit> units) {
	int outWords = 0;
	for (Unit u : units) {
		Stmt stmt = (Stmt) u;
		if (stmt.containsInvokeExpr()) {
			int wordsForParameters = 0;
			InvokeExpr invocation = stmt.getInvokeExpr();
			List<Value> args = invocation.getArgs();
			for (Value arg : args) {
				wordsForParameters += getDexWords(arg.getType());
			}
			if (!invocation.getMethod().isStatic()) {
				wordsForParameters++; // extra word for "this"
			}
			if (wordsForParameters > outWords) {
				outWords = wordsForParameters;
			}
		}
	}
	return outWords;
}
 
Example 3
Source File: AuthorityValueAnalysis.java    From ic3 with Apache License 2.0 6 votes vote down vote up
@Override
public Set<Object> computeArgumentValues(Argument argument, Unit callSite) {
  ArgumentValueAnalysis stringAnalysis =
      ArgumentValueManager.v().getArgumentValueAnalysis(
          Constants.DefaultArgumentTypes.Scalar.STRING);

  Stmt stmt = (Stmt) callSite;
  if (!stmt.containsInvokeExpr()) {
    throw new RuntimeException("Statement " + stmt + " does not contain an invoke expression");
  }
  InvokeExpr invokeExpr = stmt.getInvokeExpr();

  Set<Object> hosts =
      stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[0]), stmt);
  Set<Object> ports =
      stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[1]), stmt);

  Set<Object> result = new HashSet<>();
  for (Object host : hosts) {
    for (Object port : ports) {
      result.add(new DataAuthority((String) host, (String) port));
    }
  }

  return result;
}
 
Example 4
Source File: EasyTaintWrapper.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean supportsCallee(Stmt callSite) {
	// We need an invocation expression
	if (!callSite.containsInvokeExpr())
		return false;

	SootMethod method = callSite.getInvokeExpr().getMethod();
	if (!supportsCallee(method))
		return false;
			
	// We need a method that can create a taint
	if (!aggressiveMode) {
		// Check for a cached wrap type
		final MethodWrapType wrapType = methodWrapCache.getUnchecked(method);
		if (wrapType != MethodWrapType.CreateTaint)
			return false;
	}
	
	// We need at least one non-constant argument or a tainted base
	if (callSite.getInvokeExpr() instanceof InstanceInvokeExpr)
		return true;
	for (Value val : callSite.getInvokeExpr().getArgs())
		if (!(val instanceof Constant))
			return true;
	return false;
}
 
Example 5
Source File: TypeStateMachineWeightFunctions.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
protected Collection<Val> generateAtConstructor(SootMethod m, Unit unit, Collection<SootMethod> calledMethod,
        MatcherTransition initialTrans) {
    boolean matches = false;
    for (SootMethod method : calledMethod) {
        if (initialTrans.matches(method)) {
            matches = true;
        }
    }
    if (!matches)
        return Collections.emptySet();
    if (unit instanceof Stmt) {
        Stmt stmt = (Stmt) unit;
        if (stmt.containsInvokeExpr())
            if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
                InstanceInvokeExpr iie = (InstanceInvokeExpr) stmt.getInvokeExpr();
                if (iie.getBase() instanceof Local) {
                    Local l = (Local) iie.getBase();
                    Set<Val> out = new HashSet<>();
                    out.add(new Val(l, m));
                    return out;
                }
            }
    }
    return Collections.emptySet();
}
 
Example 6
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 7
Source File: SmartConstantDataExtractorFuzzyAnalysis.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
private boolean isSemanticallyCorrect(String loggingPoint, Stmt stmt) {
	if(loggingPoint == null)
		return false;
	if(stmt.containsInvokeExpr()) {
		InvokeExpr inv = stmt.getInvokeExpr();
		String metSig = inv.getMethod().getSignature();
		if(metSig.equals("<android.telephony.TelephonyManager: java.lang.String getSimOperator()>") 
				|| metSig.equals("<android.telephony.TelephonyManager: java.lang.String getNetworkOperator()>")
			) {
			for(char c : loggingPoint.toCharArray()) {
				if(c < '0' || c > '9') 
					return false;
			}
		}
	}
	return true;
}
 
Example 8
Source File: SmartConstantDataExtractorFuzzyAnalysis.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
private String fixSMTSolverIntegerOutput(String loggingPoint, Stmt stmt) {
	if(stmt.containsInvokeExpr()) {
		InvokeExpr inv = stmt.getInvokeExpr();
		String metSig = inv.getMethod().getSignature();
		if(metSig.equals("<android.telephony.TelephonyManager: java.lang.String getSimOperator()>") 
				|| metSig.equals("<android.telephony.TelephonyManager: java.lang.String getNetworkOperator()>")
			) {
			String newLoggingPoint = "";
			for(char c : loggingPoint.toCharArray()) {
				if(c < '0' || c > '9') {
					Random rand = new Random();
					int num = rand.nextInt(10);
					newLoggingPoint += num;
				}
				else
					newLoggingPoint += c;
			}
			return newLoggingPoint;				
		}
	}
	return loggingPoint;
}
 
Example 9
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 10
Source File: ArgumentValueAnalysis.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Computes the possible argument values for a given statement and a given argument.
 * 
 * By default this simply calls {@link #computeArgumentValues(Argument, Unit)}.
 * 
 * @param argument An {@link Argument}.
 * @param callSite A call statement.
 * @return The set of possible values for the argument.
 */
public Set<Object> computeArgumentValues(Argument argument, Unit callSite) {
  if (argument.getArgnum() == null) {
    return null;
  }
  if (AnalysisParameters.v().useShimple()) {
    // Shimple is not supported.
    return Collections.singleton((Object) getTopValue());
  } else {
    Stmt stmt = (Stmt) callSite;
    if (!stmt.containsInvokeExpr()) {
      throw new RuntimeException("Statement " + stmt + " does not contain an invoke expression");
    }
    InvokeExpr invokeExpr = stmt.getInvokeExpr();
    int argnum = argument.getArgnum()[0];
    Value value = null;
    if (argnum == Constants.INSTANCE_INVOKE_BASE_INDEX) {
      if (invokeExpr instanceof InstanceInvokeExpr) {
        value = ((InstanceInvokeExpr) invokeExpr).getBase();
      } else {
        throw new RuntimeException("Invoke expression has no base: " + invokeExpr);
      }
    } else {
      value = stmt.getInvokeExpr().getArg(argnum);
    }

    return computeVariableValues(value, stmt);
  }
}
 
Example 11
Source File: SourceMethodReturnValueAnalysis.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Set<Object> computeMethodReturnValues(Call call) {
  Stmt stmt = call.stmt;
  if (!stmt.containsInvokeExpr() || !(stmt.getInvokeExpr() instanceof InstanceInvokeExpr)) {
    return Collections.singleton((Object) "(.*)");
  } else {
    return Collections.singleton((Object) new SourceDescriptor(((InstanceInvokeExpr) stmt
        .getInvokeExpr()).getBase(), stmt));
  }

}
 
Example 12
Source File: DefaultSourceSinkManager.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public SourceInfo getSourceInfo(Stmt sCallSite, InterproceduralCFG<Unit, SootMethod> cfg) {
	SootMethod callee = sCallSite.containsInvokeExpr() ?
			sCallSite.getInvokeExpr().getMethod() : null;
	
	AccessPath targetAP = null;
	if (callee != null && sources.contains(callee.toString())) {
		if (callee.getReturnType() != null 
				&& sCallSite instanceof DefinitionStmt) {
			// Taint the return value
			Value leftOp = ((DefinitionStmt) sCallSite).getLeftOp();
			targetAP = new AccessPath(leftOp, true);
		}
		else if (sCallSite.getInvokeExpr() instanceof InstanceInvokeExpr) {
			// Taint the base object
			Value base = ((InstanceInvokeExpr) sCallSite.getInvokeExpr()).getBase();
			targetAP = new AccessPath(base, true);
		}
	}
	// Check whether we need to taint parameters
	else if (sCallSite instanceof IdentityStmt) {
		IdentityStmt istmt = (IdentityStmt) sCallSite;
		if (istmt.getRightOp() instanceof ParameterRef) {
			ParameterRef pref = (ParameterRef) istmt.getRightOp();
			SootMethod currentMethod = cfg.getMethodOf(istmt);
			if (parameterTaintMethods.contains(currentMethod.toString()))
				targetAP = new AccessPath(currentMethod.getActiveBody()
						.getParameterLocal(pref.getIndex()), true);
		}
	}
	
	if (targetAP == null)
		return null;
	
	// Create the source information data structure
	return new SourceInfo(targetAP);
}
 
Example 13
Source File: ObservableDynamicICFG.java    From SPDS with Eclipse Public License 2.0 5 votes vote down vote up
private void queryForCallees(Unit unit) {
        // Construct BackwardQuery, so we know which types the object might have
        logger.debug("Queried for callees of '{}'.", unit);
        Stmt stmt = (Stmt) unit;
        InvokeExpr invokeExpr = stmt.getInvokeExpr();
        Value value = ((InstanceInvokeExpr) invokeExpr).getBase();
        Val val = new Val(value, getMethodOf(stmt));
        for (Unit pred : getPredsOf(stmt)) {
            Statement statement = new Statement((Stmt) pred, getMethodOf(unit));

            BackwardQuery query = new BackwardQuery(statement, val);

            // Execute that query
            solver.solve(query, false);
            forAnyAllocationSiteOfQuery(query, invokeExpr, stmt);
            
            // Go through possible types an add edges to implementations in possible types
//            Set<ForwardQuery> keySet = results.getAllocationSites().keySet();
//            for (ForwardQuery forwardQuery : keySet) {
//                
//            }

            // Fallback on Precompute if set was empty
//            if (options.fallbackOnPrecomputedOnEmpty() && keySet.isEmpty()) {
//                Iterator<Edge> precomputedCallers = precomputedCallGraph.edgesOutOf(unit);
//                while (precomputedCallers.hasNext()) {
//                    Edge methodCall = precomputedCallers.next();
//                    if (methodCall.srcUnit() == null)
//                        continue;
//                    addCallIfNotInGraph(methodCall.srcUnit(), methodCall.tgt(), methodCall.kind());
//                }
//            }
        }
    }
 
Example 14
Source File: OfflineProcessor.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void defaultFeedPtsRoutines()
{		
	switch (Parameters.seedPts) {
	case Constants.seedPts_allUser:
		setAllUserCodeVariablesUseful();
		break;
		
	case Constants.seedPts_all:
		// All pointers will be processed
		for (int i = 0; i < n_var; ++i) {
			IVarAbstraction pn = int2var.get(i);
			if ( pn != null &&
					pn.getRepresentative() == pn )
				pn.willUpdate = true;
		}
		return;
	}
	
	// We always refine the callsites that have multiple call targets
	Set<Node> multiBaseptrs = new HashSet<Node>();

	for (Stmt callsite : geomPTA.multiCallsites) {
		InstanceInvokeExpr iie = 
				(InstanceInvokeExpr) callsite.getInvokeExpr();
		VarNode vn = geomPTA.findLocalVarNode(iie.getBase());
		multiBaseptrs.add(vn);
	}

	addUserDefPts(multiBaseptrs);
}
 
Example 15
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 16
Source File: OnTheFlyJimpleBasedICFG.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Set<SootMethod> load(Unit u) throws Exception {
	Stmt stmt = (Stmt)u;
	InvokeExpr ie = stmt.getInvokeExpr();
	FastHierarchy fastHierarchy = Scene.v().getFastHierarchy();
	//FIXME Handle Thread.start etc.
	if(ie instanceof InstanceInvokeExpr) {
		if(ie instanceof SpecialInvokeExpr) {
			//special
			return Collections.singleton(ie.getMethod());
		} else {
			//virtual and interface
			InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
			Local base = (Local) iie.getBase();
			RefType concreteType = bodyToLMNAA.getUnchecked(unitToOwner.get(u)).concreteType(base, stmt);
			if(concreteType!=null) {
				//the base variable definitely points to a single concrete type 
				SootMethod singleTargetMethod = fastHierarchy.resolveConcreteDispatch(concreteType.getSootClass(), iie.getMethod());
				return Collections.singleton(singleTargetMethod);
			} else {
				SootClass baseTypeClass;
				if(base.getType() instanceof RefType) {
					RefType refType = (RefType) base.getType();
					baseTypeClass = refType.getSootClass();
				} else if(base.getType() instanceof ArrayType) {
					baseTypeClass = Scene.v().getSootClass("java.lang.Object");
				} else if(base.getType() instanceof NullType) {
					//if the base is definitely null then there is no call target
					return Collections.emptySet();
				} else {
					throw new InternalError("Unexpected base type:"+base.getType());
				}
				return fastHierarchy.resolveAbstractDispatch(baseTypeClass, iie.getMethod());
			}
		}
	} else {
		//static
		return Collections.singleton(ie.getMethod());
	}
}
 
Example 17
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 18
Source File: CallFlowFunctionFactory.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns a call flow function.
 * 
 * @param src A statement that is the source of a call edge in the call graph. This is generally a
 *          call statement, but field accesses can also lead to edges leading to class
 *          initializers.
 * @param dest The destination method.
 * @param zeroValue The zero value for the analysis, which represents the absence of a data flow
 *          fact.
 * @return The call flow function for the input statement.
 */
public FlowFunction<Value> getCallFlowFunction(Unit src, final SootMethod dest,
    final Value zeroValue) {
  if (logger.isDebugEnabled()) {
    logger.debug("Call: " + src);
  }

  String declaringClass = dest.getDeclaringClass().getName();

  if (!AnalysisParameters.v().isAnalysisClass(declaringClass)) {
    // Only propagate through analysis classes.
    return KillAll.v();
  }

  Stmt stmt = (Stmt) src;
  // Some statements other than call statements (e.g., field accesses) can lead to call edges to
  // class initializers.
  boolean containsInvokeExpr = stmt.containsInvokeExpr();

  final InvokeExpr ie = containsInvokeExpr ? stmt.getInvokeExpr() : null;

  if (containsInvokeExpr
      && (Model.v().getArgumentsForGenMethod(ie) != null || Model.v()
          .getArgumentsForCopyConstructor(ie.getMethodRef()) != null)) {
    return KillAll.v();
  }

  return new FlowFunction<Value>() {
    @Override
    public Set<Value> computeTargets(Value source) {
      if (logger.isDebugEnabled()) {
        logger.debug("Source: " + source);
      }

      if (dest.getName().equals(SootMethod.staticInitializerName)) {
        if (source instanceof FieldRef) {
          return Collections.singleton(source);
        } else {
          return Collections.emptySet();
        }
      }

      final List<Value> paramLocals = new ArrayList<Value>();

      for (int i = 0; i < dest.getParameterCount(); ++i) {
        // TODO (Damien): maybe activate again?
        // if (ie.getArg(i) instanceof NullConstant && source.equals(zeroValue)) {
        // return Collections.singleton((Value) dest.getActiveBody().getParameterLocal(i));
        // }
        paramLocals.add(dest.getActiveBody().getParameterLocal(i));
      }

      int argIndex = FunctionFactoryUtils.shouldPropagateSource(source, ie.getArgs());
      if (argIndex != -1) {
        if (logger.isDebugEnabled()) {
          logger.debug("Returning " + paramLocals.get(argIndex));
        }
        return Collections.singleton(paramLocals.get(argIndex));
      }

      if (source instanceof StaticFieldRef) {
        // Always propagate static fields.
        return Collections.singleton(source);
      } else if (source instanceof InstanceFieldRef) {
        if (FunctionFactoryUtils.shouldPropagateInstanceField((InstanceFieldRef) source, ie)) {
          return Collections.singleton(source);
        }
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Returning empty set");
      }
      return Collections.emptySet();
    }
  };
}
 
Example 19
Source File: NullnessAnalysis.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void flowThrough(AnalysisInfo in, Unit u, List<AnalysisInfo> fallOut, List<AnalysisInfo> branchOuts) {
	AnalysisInfo out = new AnalysisInfo(in);
	AnalysisInfo outBranch = new AnalysisInfo(in);
	
	Stmt s = (Stmt)u;
	
	//in case of an if statement, we neet to compute the branch-flow;
	//e.g. for a statement "if(x!=null) goto s" we have x==null for the fallOut and
	//x!=null for the branchOut
	//or for an instanceof expression
	if(s instanceof JIfStmt) {
		JIfStmt ifStmt = (JIfStmt) s;
		handleIfStmt(ifStmt, in, out, outBranch);
	}
	//in case of a monitor statement, we know that if it succeeds, we have a non-null value
	else if(s instanceof MonitorStmt) {
		MonitorStmt monitorStmt = (MonitorStmt) s;
		out.put(monitorStmt.getOp(), NON_NULL);
	}
	
	// if we have an array ref, set the base to non-null
	if(s.containsArrayRef()) {
		ArrayRef arrayRef = s.getArrayRef();
		handleArrayRef(arrayRef,out);
	}
	// for field refs, set the receiver object to non-null, if there is one
	if(s.containsFieldRef()) {
		FieldRef fieldRef = s.getFieldRef();
		handleFieldRef(fieldRef, out);
	}
	// for invoke expr, set the receiver object to non-null, if there is one
	if(s.containsInvokeExpr()) {
		InvokeExpr invokeExpr = s.getInvokeExpr();
		handleInvokeExpr(invokeExpr, out);
	}
	
	//if we have a definition (assignment) statement to a ref-like type, handle it,
	//i.e. assign it TOP, except in the following special cases:
	// x=null,               assign NULL
	// x=@this or x= new...  assign NON_NULL
	// x=y,                  copy the info for y (for locals x,y)
	if(s instanceof DefinitionStmt) {
		DefinitionStmt defStmt = (DefinitionStmt) s;
		if(defStmt.getLeftOp().getType() instanceof RefLikeType) {
			handleRefTypeAssignment(defStmt, out);
		}
	}
	
	// now copy the computed info to all successors
	for( Iterator<AnalysisInfo> it = fallOut.iterator(); it.hasNext(); ) {
		copy( out, it.next() );
	}
	for( Iterator<AnalysisInfo> it = branchOuts.iterator(); it.hasNext(); ) {
		copy( outBranch, it.next() );
	}
}
 
Example 20
Source File: DynamicValueTransformer.java    From FuzzDroid with Apache License 2.0 4 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;
	
	// Iterate over all statements. For each definition statement that
	// defines a string, report the string to the server.
	for (Iterator<Unit> unitIt = b.getUnits().snapshotIterator(); unitIt.hasNext(); ) {
		Unit curUnit = unitIt.next();
		
		// If we're still inside the IdentityStmt block, there's nothing to
		// instrument
		if (curUnit instanceof IdentityStmt ||
				// If this unit was instrumented by another transformer, there's nothing to instrument
				curUnit.hasTag(InstrumentedCodeTag.name))
			continue;			
		
		if (instrumentOnlyComparisons) {
			// Is this a comparison?
			Stmt curStmt = (Stmt) curUnit;
			if (!curStmt.containsInvokeExpr())
				continue;
			InvokeExpr invExpr = curStmt.getInvokeExpr();
			if (comparisonSignatures.contains(invExpr.getMethod().getSignature())) {					
				if (invExpr instanceof InstanceInvokeExpr)
					checkAndReport(b, curStmt, ((InstanceInvokeExpr) invExpr).getBase(), -1);
				for (int i = 0; i < invExpr.getArgCount(); i++)
					checkAndReport(b, curStmt, invExpr.getArg(i), i);
			}
			
			// Do not look for anything else
			continue;
		}
		
		// We only care about statements that define strings
		if (!(curUnit instanceof AssignStmt))
			continue;
		AssignStmt assignStmt = (AssignStmt) curUnit;
		checkAndReport(b, assignStmt, assignStmt.getLeftOp(), -1);
	}

}