soot.jimple.DefinitionStmt Java Examples

The following examples show how to use soot.jimple.DefinitionStmt. 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: LocalMustNotAliasAnalysis.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
protected void flowThrough(HashMap<Local,Set<NewExpr>> in, Unit unit,
		HashMap<Local,Set<NewExpr>> out)
{
    Stmt    s   = (Stmt)    unit;

    out.clear();
    out.putAll(in);

    if (s instanceof DefinitionStmt) {
        DefinitionStmt ds = (DefinitionStmt) s;
        Value lhs = ds.getLeftOp();
        Value rhs = ds.getRightOp();
        if (lhs instanceof Local) {
            HashSet<NewExpr> lv = new HashSet<NewExpr>();
            out.put((Local) lhs, lv);
            if (rhs instanceof NewExpr) {
                lv.add((NewExpr) rhs);
            } else if (rhs instanceof Local) {
                lv.addAll(in.get(rhs));
            } else lv.add(UNKNOWN);
        }
    }
}
 
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: AsmMethodSource.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
private void convertLabel(LabelNode ln) {
	if (!trapHandlers.containsKey(ln))
		return;
	StackFrame frame = getFrame(ln);
	Operand[] out = frame.out();
	Operand opr;
	if (out == null) {
		CaughtExceptionRef ref = Jimple.v().newCaughtExceptionRef();
		Local stack = newStackLocal();
		DefinitionStmt as = Jimple.v().newIdentityStmt(stack, ref);
		opr = new Operand(ln, ref);
		opr.stack = stack;
		frame.out(opr);
		setUnit(ln, as);
	} else {
		opr = out[0];
	}
	push(opr);
}
 
Example #4
Source File: AsmMethodSource.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
private void convertVarStoreInsn(VarInsnNode insn) {
	int op = insn.getOpcode();
	boolean dword = op == LSTORE || op == DSTORE;
	StackFrame frame = getFrame(insn);
	Operand opr = dword ? popDual() : pop();
	Local local = getLocal(insn.var);
	if (!units.containsKey(insn)) {
		DefinitionStmt as = Jimple.v().newAssignStmt(local, opr.stackOrValue());
		opr.addBox(as.getRightOpBox());
		frame.boxes(as.getRightOpBox());
		frame.in(opr);
		setUnit(insn, as);
	} else {
		frame.mergeIn(opr);
	}
	assignReadOps(local);
}
 
Example #5
Source File: NullnessAssumptionAnalysis.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
private void handleRefTypeAssignment(DefinitionStmt assignStmt,
		AnalysisInfo rhsInfo, AnalysisInfo out) {
	Value left = assignStmt.getLeftOp();
	Value right = assignStmt.getRightOp();
	
	//unbox casted value
	if(right instanceof JCastExpr) {
		JCastExpr castExpr = (JCastExpr) right;
		right = castExpr.getOp();
	}
	
	// An assignment invalidates any assumptions of null/non-null for lhs
	// We COULD be more accurate by assigning those assumptions to the rhs prior to this statement
	rhsInfo.put(right,BOTTOM);
	
	//assign from rhs to lhs
	out.put(left,rhsInfo.get(right));
}
 
Example #6
Source File: InitializationDeclarationShortcut.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public void inASTMethodNode(ASTMethodNode node){
	Stmt s = ofInterest.get_Stmt();
	//check this is a definition
	if(! (s instanceof DefinitionStmt )){
		possible=false;
		return;
	}
		
	Value defined = ((DefinitionStmt)s).getLeftOp();
	if(!(defined instanceof Local)){
		possible=false;
		return;
	}
	
	//check that this is a local defined in this method
	//its a sanity check
	List declaredLocals = node.getDeclaredLocals();
	if(!declaredLocals.contains(defined)){
		possible=false;
		return;
	}
	definedLocal = (Local)defined;
}
 
Example #7
Source File: StmtTranslator.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
void handleAssign(DefinitionStmt stmt) {
	Value lval = stmt.getLeftOp();
	Value rval = stmt.getRightOp();
	Variable rvar;
	if (lval instanceof Local) {
		rvar = getLocalVariable((Local)lval);
	} else {
		rvar = jt.makeVariable(rval);
	}
	et.translateExpr(rvar, stmt.getRightOpBox());
	if (lval instanceof ArrayRef) {
		notSupported("We do not support arrays");
	} else if (lval instanceof FieldRef) {
		notSupported("We do not support field references");
	}
}
 
Example #8
Source File: SourceSinkTests.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) {
	if (sCallSite.containsInvokeExpr()
			&& sCallSite instanceof DefinitionStmt
			&& sCallSite.getInvokeExpr().getMethod().getName().equals("getSecret")) {
		AccessPath ap = new AccessPath(((DefinitionStmt) sCallSite).getLeftOp(), false);
		return new SourceInfo(ap);
	}
	return null;
}
 
Example #9
Source File: InitializationDeclarationShortcut.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void inDefinitionStmt(DefinitionStmt s){
	if(definedLocal==null)
		return;
	
	Value defined = (s).getLeftOp();
	if(!(defined instanceof Local)){
		return;
	}
	
	if(defined.equals(definedLocal)){
		//the local of interest is being defined
		
		//if this is the augmentedStmt of interest set possible to true if not already seen
		if(s.equals(ofInterest.get_Stmt())){
			//it is the stmt of interest
			if(seenBefore==0)
				possible=true;
			else
				possible=false;
		}
		else{
			//its a definition of the local of interest but not by the stmt of interest
			seenBefore++;
		}

	}	
}
 
Example #10
Source File: TypeResolver.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public TypeResolver(JimpleBody jb)
{
	this.jb = jb;

	this.assignments = new ArrayList<DefinitionStmt>();
	this.depends = new HashMap<Local, BitSet>();
	for ( Local v : this.jb.getLocals() )
		this.addLocal(v);
	this.initAssignments();
}
 
Example #11
Source File: NullnessAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private void handleRefTypeAssignment(DefinitionStmt assignStmt, AnalysisInfo out) {
	Value left = assignStmt.getLeftOp();
	Value right = assignStmt.getRightOp();
	
	//unbox casted value
	if(right instanceof JCastExpr) {
		JCastExpr castExpr = (JCastExpr) right;
		right = castExpr.getOp();
	}
	
	//if we have a definition (assignment) statement to a ref-like type, handle it,
	if ( isAlwaysNonNull(right)
	|| right instanceof NewExpr || right instanceof NewArrayExpr
	|| right instanceof NewMultiArrayExpr || right instanceof ThisRef
	|| right instanceof StringConstant || right instanceof ClassConstant
	|| right instanceof CaughtExceptionRef) {
		//if we assign new... or @this, the result is non-null
		out.put(left,NON_NULL);
	} else if(right==NullConstant.v()) {
		//if we assign null, well, it's null
		out.put(left, NULL);
	} else if(left instanceof Local && right instanceof Local) {
		out.put(left, out.get(right));
	} else {
		out.put(left, TOP);
	}
}
 
Example #12
Source File: ShortcutArrayInit.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public boolean isInSequenceAssignment(Stmt s, Value leftOp, int index){
	//DEBUG=false;
	if(!(s instanceof DefinitionStmt))
		return false;
	
	DefinitionStmt ds = (DefinitionStmt)s;
	Value leftValue = ds.getLeftOp();
	if(! (leftValue instanceof ArrayRef))
		return false;
	
	if(DEBUG){
		System.out.println("Stmt number "+index + " is an array ref assignment"+leftValue);
		System.out.println("Array is"+leftOp);
	}

	ArrayRef leftRef = (ArrayRef)leftValue;
	if(! (leftOp.equals(leftRef.getBase()))){
		if(DEBUG)
			System.out.println("Not assigning to same array");
		return false;
	}
		
	if( ! (leftRef.getIndex() instanceof IntConstant)){
		if(DEBUG)
			System.out.println("Cant determine index of assignment");
		return false;
	}
	
	IntConstant leftIndex = (IntConstant)leftRef.getIndex();
	if(leftIndex.value != index){
		if(DEBUG)
			System.out.println("Out of order assignment");
		return false;
	}
	
	return true;
}
 
Example #13
Source File: DexNullArrayRefTransformer.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks whether the given local is guaranteed to be always null at the
 * given statement
 * @param s The statement at which to check the local
 * @param base The local to check
 * @param defs The definition analysis object to use for the check
 * @return True if the given local is guaranteed to always be null at the
 * given statement, otherwise false
 */
private boolean isAlwaysNullBefore(Stmt s, Local base, LocalDefs defs) {
	List<Unit> baseDefs = defs.getDefsOfAt(base, s);
	if (baseDefs.isEmpty())
		return true;
	
	for (Unit u : baseDefs) {
		if (!(u instanceof DefinitionStmt))
			return false;
		DefinitionStmt defStmt = (DefinitionStmt) u;
		if (defStmt.getRightOp() != NullConstant.v())
			return false;
	}
	return true;
}
 
Example #14
Source File: SourceSinkTests.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) {
	if (sCallSite.containsInvokeExpr()
			&& sCallSite instanceof DefinitionStmt
			&& (sCallSite.getInvokeExpr().getMethod().getName().equals("getSecret")
					|| (sCallSite.getInvokeExpr().getMethod().getName().equals("getSecret2")))) {
		AccessPath ap = new AccessPath(((DefinitionStmt) sCallSite).getLeftOp(), true);
		return new SourceInfo(ap);
	}
	return null;
}
 
Example #15
Source File: SourceSinkTests.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) {
	if (sCallSite.containsInvokeExpr()
			&& sCallSite instanceof DefinitionStmt
			&& sCallSite.getInvokeExpr().getMethod().getName().equals("getSecret")) {
		AccessPath ap = new AccessPath(((DefinitionStmt) sCallSite).getLeftOp(), true);
		return new SourceInfo(ap);
	}
	return null;
}
 
Example #16
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 #17
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 #18
Source File: DexReturnValuePropagator.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks whether the given local has been redefined between the original
 * definition unitDef and the use unitUse.
 * @param l The local for which to check for redefinitions
 * @param unitUse The unit that uses the local
 * @param unitDef The unit that defines the local
 * @param graph The unit graph to use for the check
 * @return True if there is at least one path between unitDef and unitUse on
 * which local l gets redefined, otherwise false 
 */
   private boolean isRedefined(Local l, Unit unitUse, AssignStmt unitDef,
   		UnitGraph graph) {
   	List<Unit> workList = new ArrayList<Unit>();
   	workList.add(unitUse);
   	
   	Set<Unit> doneSet = new HashSet<Unit>();
   	
	// Check for redefinitions of the local between definition and use
   	while (!workList.isEmpty()) {
   		Unit curStmt = workList.remove(0);
   		if (!doneSet.add(curStmt))
   			continue;
   		
    	for (Unit u : graph.getPredsOf(curStmt)) {
    		if (u != unitDef) {
	    		if (u instanceof DefinitionStmt) {
	    			DefinitionStmt defStmt = (DefinitionStmt) u;
	    			if (defStmt.getLeftOp() == l)
	    				return true;
	    		}
	    		workList.add(u);
    		}
    	}
   	}
   	return false;
}
 
Example #19
Source File: IntValueAnalysis.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Return all possible values for an integer local variable.
 * 
 * @param start The statement where the analysis should start.
 * @param local The local variable whose values we are looking for.
 * @param visitedStmts The set of visited statement.
 * @return The set of possible values for the local variable.
 */
private Set<Object> findIntAssignmentsForLocal(Stmt start, Local local, Set<Stmt> visitedStmts) {
  List<DefinitionStmt> assignStmts =
      findAssignmentsForLocal(start, local, true, new HashSet<Pair<Unit, Local>>());
  Set<Object> result = new HashSet<>(assignStmts.size());

  for (DefinitionStmt assignStmt : assignStmts) {
    Value rhsValue = assignStmt.getRightOp();
    if (rhsValue instanceof IntConstant) {
      result.add(((IntConstant) rhsValue).value);
    } else if (rhsValue instanceof LongConstant) {
      result.add(((LongConstant) rhsValue).value);
    } else if (rhsValue instanceof ParameterRef) {
      ParameterRef parameterRef = (ParameterRef) rhsValue;
      Iterator<Edge> edges =
          Scene.v().getCallGraph()
              .edgesInto(AnalysisParameters.v().getIcfg().getMethodOf(assignStmt));
      while (edges.hasNext()) {
        Edge edge = edges.next();
        InvokeExpr invokeExpr = edge.srcStmt().getInvokeExpr();
        Value argValue = invokeExpr.getArg(parameterRef.getIndex());
        if (argValue instanceof IntConstant) {
          result.add(((IntConstant) argValue).value);
        } else if (argValue instanceof LongConstant) {
          result.add(((LongConstant) argValue).value);
        } else if (argValue instanceof Local) {
          Set<Object> newResults =
              findIntAssignmentsForLocal(edge.srcStmt(), (Local) argValue, visitedStmts);
          result.addAll(newResults);
        } else {
          result.add(TOP_VALUE);
        }
      }
    } else {
      return Collections.singleton((Object) TOP_VALUE);
    }
  }

  return result;
}
 
Example #20
Source File: StaticDefinitionFinder.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void inDefinitionStmt(DefinitionStmt s){
Value leftOp = s.getLeftOp();
if(leftOp instanceof FieldRef){
    //System.out.println("leftOp is a fieldRef:"+s);
    SootField field = ((FieldRef)leftOp).getField();
    //check if this is a final field
    if(field.isFinal()){
	//System.out.println("the field is a final variable");
	finalFieldDefined=true;
    }
}

   }
 
Example #21
Source File: ShortcutArrayInit.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public boolean isInSequenceAssignmentPatternTwo(Stmt one, Stmt two, Value leftOp, int index){
	if(!(two instanceof DefinitionStmt))
		return false;
	
	DefinitionStmt ds = (DefinitionStmt)two;
	Value leftValue = ds.getLeftOp();
	if(! (leftValue instanceof ArrayRef))
		return false;
	
	ArrayRef leftRef = (ArrayRef)leftValue;
	if(! (leftOp.equals(leftRef.getBase()))){
		if(DEBUG)
			System.out.println("Not assigning to same array");
		return false;
	}
		
	if( ! (leftRef.getIndex() instanceof IntConstant)){
		if(DEBUG)
			System.out.println("Cant determine index of assignment");
		return false;
	}
	
	IntConstant leftIndex = (IntConstant)leftRef.getIndex();
	if(leftIndex.value != index){
		if(DEBUG)
			System.out.println("Out of order assignment");
		return false;
	}

	Value rightOp = ds.getRightOp();
	
	if(!(one instanceof DShortcutAssignStmt))
		return false;
	
	DShortcutAssignStmt shortcut = (DShortcutAssignStmt)one;
	Value shortcutVar = shortcut.getLeftOp();
	if(!shortcutVar.equals(rightOp))
		return false;

	return true;
}
 
Example #22
Source File: TypeCastingError.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void inASTStatementSequenceNode(ASTStatementSequenceNode node){
	List<Object> stmts = node.getStatements();
	Iterator<Object> stmtIt = stmts.iterator();
	while(stmtIt.hasNext()){
		AugmentedStmt as = (AugmentedStmt)stmtIt.next();
		Stmt s = as.get_Stmt();
		if(! (s instanceof DefinitionStmt))
			continue;
		
		DefinitionStmt ds = (DefinitionStmt)s;
		if(myDebug) System.out.println("Definition stmt"+ds);			
		
		ValueBox rightBox = ds.getRightOpBox();
		ValueBox leftBox = ds.getLeftOpBox();
		
		Value right = rightBox.getValue();
		Value left = leftBox.getValue();
			
		if(! (left.getType() instanceof PrimType && right.getType() instanceof PrimType )){
			//only interested in prim type casting errors
			if(myDebug) System.out.println("\tDefinition stmt does not contain prims no need to modify");
			continue;
		}
		
		Type leftType = left.getType();
		Type rightType = right.getType();
		if(myDebug) System.out.println("Left type is: "+leftType);
		if(myDebug) System.out.println("Right type is: "+rightType);
		if(leftType.equals(rightType)){
			if(myDebug) System.out.println("\tTypes are the same");
			if(myDebug) System.out.println("Right value is of instance"+right.getClass());
		}
		if(!leftType.equals(rightType)){
			if(myDebug) System.out.println("\tDefinition stmt has to be modified");	
			// ByteType, DoubleType, FloatType, IntType, LongType, ShortType
			/*
			 * byte  	 Byte-length integer  	8-bit two's complement
			 * short 	Short integer 	16-bit two's complement
			 * int 	Integer 	32-bit two's complement
			 * long 	Long integer 	64-bit two's complement
			 * float 	Single-precision floating point 	32-bit IEEE 754
			 * double Double-precision floating point  	64-bit IEEE 754 	
			 */
		    if(leftType instanceof ByteType && (rightType instanceof DoubleType || 
	    			rightType instanceof FloatType || rightType instanceof IntType || rightType instanceof LongType
	    			|| rightType instanceof ShortType)) {
	    	//loss of precision do explicit casting
	    	
		    	if(DEBUG) System.out.println("Explicit casting to BYTE required");
		    	rightBox.setValue(new GCastExpr(right,ByteType.v()));
		    	if(DEBUG)System.out.println("New right expr is "+rightBox.getValue().toString());
		    	continue;
		    }
	    	
		    if(leftType instanceof ShortType && (rightType instanceof DoubleType || 
	    			rightType instanceof FloatType || rightType instanceof IntType || rightType instanceof LongType)) {
		    	//loss of precision do explicit casting
	    	
		    	if(DEBUG)System.out.println("Explicit casting to SHORT required");
		    	rightBox.setValue(new GCastExpr(right,ShortType.v()));
		    	if(DEBUG)System.out.println("New right expr is "+rightBox.getValue().toString());
		    	continue;
		    }

		    
		    if(leftType instanceof IntType && (rightType instanceof DoubleType || 
	    			rightType instanceof FloatType || rightType instanceof LongType)) {
		    	//loss of precision do explicit casting
	    	
		    	if(myDebug)System.out.println("Explicit casting to INT required");
		    	rightBox.setValue(new GCastExpr(right,IntType.v()));
		    	if(myDebug)System.out.println("New right expr is "+rightBox.getValue().toString());
		    	continue;
		    }
		    
		    
		    if(leftType instanceof LongType && (rightType instanceof DoubleType || 
	    			rightType instanceof FloatType )) {
		    	//loss of precision do explicit casting
	    	
		    	if(DEBUG)System.out.println("Explicit casting to LONG required");
		    	rightBox.setValue(new GCastExpr(right,LongType.v()));
		    	if(DEBUG)System.out.println("New right expr is "+rightBox.getValue().toString());
		    	continue;
		    }
		    
		    
		    if(leftType instanceof FloatType && rightType instanceof DoubleType) {
		    	//loss of precision do explicit casting
	    	
		    	if(DEBUG)System.out.println("Explicit casting to FLOAT required");
		    	rightBox.setValue(new GCastExpr(right,FloatType.v()));
		    	if(DEBUG)System.out.println("New right expr is "+rightBox.getValue().toString());
		    	continue;
		    }		    	
	    }
		
	}
	
}
 
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: ShortcutIfGenerator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void inASTStatementSequenceNode(ASTStatementSequenceNode node){
	List<Object> stmts = node.getStatements();
	Iterator<Object> stmtIt = stmts.iterator();
	while(stmtIt.hasNext()){
		AugmentedStmt as = (AugmentedStmt)stmtIt.next();
		Stmt s = as.get_Stmt();
		if(! (s instanceof DefinitionStmt))
			continue;
		
		DefinitionStmt ds = (DefinitionStmt)s;
		ValueBox rightBox = ds.getRightOpBox();
			
		Value right = rightBox.getValue();
			
		/*
		 * Going to match int i = (int) z where z is a boolean
		 * or int i= z i.e. without the cast
		 */
		
		//right type should contain the expected type on the left
		//in the case of the cast this is the cast type else just get the left type
		Type rightType=null;
		ValueBox OpBox = null;
			
		if(right instanceof CastExpr){
			rightType = ((CastExpr)right).getCastType();
			OpBox = ((CastExpr)right).getOpBox();
		}
		else{
			rightType = ds.getLeftOp().getType();
			OpBox = rightBox;
		}
			
		if(! (rightType instanceof IntType )){
			continue;
		}				
			
		Value Op = OpBox.getValue();
		if(! (Op.getType() instanceof BooleanType)){
			continue;
		}

		//ready for the switch
		ImmediateBox trueBox = new ImmediateBox(IntConstant.v(1));
		ImmediateBox falseBox = new ImmediateBox(IntConstant.v(0));
			
		DShortcutIf shortcut = new DShortcutIf(OpBox,trueBox,falseBox);
		if(DEBUG)
			System.out.println("created: "+shortcut);
		rightBox.setValue(shortcut);
	}
	
}
 
Example #25
Source File: BackwardValueAnalysis.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns all assignments for a local variable. This walks the interprocedural control flow graph
 * back from a statement looking for all assignments to a given local variable.
 * 
 * @param start The statement where the analysis should start.
 * @param local The local variable whose assignments should be found.
 * @param init A boolean that indicates whether the analysis should be initialized. This should
 *          always be true for non-recursive calls.
 * @param visitedUnits The set of statements visited by the analysis.
 * @return The set of assignment statements for the local variable.
 */
protected List<DefinitionStmt> findAssignmentsForLocal(Unit start, Local local, boolean init,
    Set<Pair<Unit, Local>> visitedUnits) {
  if (logger.isDebugEnabled()) {
    logger.debug("Finding assignments for local " + local);
  }
  SootMethod method = AnalysisParameters.v().getIcfg().getMethodOf(start);
  ExceptionalUnitGraph graph = new ExceptionalUnitGraph(method.getActiveBody());
  List<DefinitionStmt> result = new ArrayList<DefinitionStmt>();

  Stack<Unit> stack = new Stack<Unit>();
  stack.push(start);
  if (init) {
    visitedUnits.clear();
  }

  while (!stack.empty()) {
    Unit current = stack.pop();
    if (logger.isDebugEnabled()) {
      logger.debug(current + " " + current.getClass());
    }
    Pair<Unit, Local> pair = new Pair<Unit, Local>(current, local);
    if (visitedUnits.contains(pair)) {
      continue;
    }
    visitedUnits.add(pair);
    if (current instanceof IdentityStmt) {
      IdentityStmt identityStmt = (IdentityStmt) current;
      // method.
      if (identityStmt.getLeftOp().equivTo(local)) {
        result.add(identityStmt);
      }
    } else if (current instanceof AssignStmt) {
      AssignStmt assignStmt = (AssignStmt) current;
      if (assignStmt.getLeftOp().equivTo(local)) {
        if (assignStmt.getRightOp() instanceof Local) {
          result.addAll(findAssignmentsForLocal(current, (Local) assignStmt.getRightOp(), false,
              visitedUnits));
        } else {
          result.add(assignStmt);
        }
        // The assignment generates the local on that path.
        // Anything before is irrelevant.
        continue;
      }
    }
    for (Unit pred : graph.getPredsOf(current)) {
      stack.push(pred);
    }
  }

  return result;
}
 
Example #26
Source File: ClassValueAnalysis.java    From DroidRA with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns the variable values that are associated with an call statement.
 * 
 * @param sourceStmt The statement at which we should start.
 * @param visitedStmts The set of visited statements.
 * @return The set of possible values.
 */
protected Set<Object> handleInvokeExpression(Stmt sourceStmt, Set<Stmt> visitedStmts) {
  if (visitedStmts.contains(sourceStmt)) {
    return Collections.emptySet();
  } else {
    visitedStmts.add(sourceStmt);
  }
  Iterator<Edge> edges = Scene.v().getCallGraph().edgesOutOf(sourceStmt);
  Set<Object> result = new HashSet<>();

  while (edges.hasNext()) {
    Edge edge = edges.next();
    SootMethod target = edge.getTgt().method();
    if (target.isConcrete()) {
      for (Unit unit : target.getActiveBody().getUnits()) {
        if (unit instanceof ReturnStmt) {
          ReturnStmt returnStmt = (ReturnStmt) unit;

          Value returnValue = returnStmt.getOp();
          if (returnValue instanceof StringConstant) {
            result.add(((StringConstant) returnValue).value);
          } else if (returnValue instanceof ClassConstant) {
            result.add(((ClassConstant) returnValue).value);
          } else if (returnValue instanceof Local) {
            List<DefinitionStmt> assignStmts =
                findAssignmentsForLocal(returnStmt, (Local) returnValue, true,
                    new HashSet<Pair<Unit, Local>>());
            Set<Object> classConstants = processClassAssignments(assignStmts, visitedStmts);
            if (classConstants == null || classConstants.contains(TOP_VALUE)
                || classConstants.contains(Constants.ANY_STRING)) {
              return null;
            } else {
              result.addAll(classConstants);
            }
          } else {
            return null;
          }
        }
      }
    }
  }

  return result;
}
 
Example #27
Source File: CP.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
@Override
public DavaFlowSet processStatement(Stmt s, DavaFlowSet input) {
	if (!(input instanceof CPFlowSet))
		throw new RuntimeException("processStatement is not implemented for other flowSet types");

	CPFlowSet inSet = (CPFlowSet) input;
	if (inSet == NOPATH)
		return inSet;

	if (!(s instanceof DefinitionStmt))
		return inSet;

	DefinitionStmt defStmt = (DefinitionStmt) s;
	// x = expr;
	// confirm that the left side is a local with a primitive type
	Value left = defStmt.getLeftOp();
	if (!(left instanceof Local && ((Local) left).getType() instanceof PrimType))
		return inSet;

	// left is a primitive primitive local
	CPFlowSet toReturn = (CPFlowSet) cloneFlowSet(inSet);

	/*
	 * KILL ANY PREVIOUS VALUE OF this local as this is an assignment
	 * Remember the returned value can be null if the element was not found
	 * or it was TOP
	 */
	Object killedValue = killButGetValueForUse((Local) left, toReturn);

	Value right = defStmt.getRightOp();

	Object value = CPHelper.isAConstantValue(right);
	if (value != null) {
		// EXPR IS A CONSTANT
		if (left.getType() instanceof BooleanType) {
			Integer tempValue = (Integer) value;
			if (tempValue.intValue() == 0)
				value = new Boolean(false);
			else
				value = new Boolean(true);
		}
		addOrUpdate(toReturn, (Local) left, value);
	} else {
		// EXPR IS NOT A CONSTANT
		handleMathematical(toReturn, (Local) left, right, killedValue);
	}
	return toReturn;
}
 
Example #28
Source File: IFDSReachingDefinitions.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public Pair<Value, Set<DefinitionStmt>> createZeroValue() {
	return new Pair<Value, Set<DefinitionStmt>>(new JimpleLocal("<<zero>>", NullType.v()), Collections.<DefinitionStmt> emptySet());
}
 
Example #29
Source File: IFDSReachingDefinitions.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public Map<Unit, Set<Pair<Value, Set<DefinitionStmt>>>> initialSeeds() {
	return DefaultSeeds.make(Collections.singleton(Scene.v().getMainMethod().getActiveBody().getUnits().getFirst()), zeroValue());
}
 
Example #30
Source File: TypeResolver.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void initAssignments()
{
	for ( Unit stmt : this.jb.getUnits() )
		if ( stmt instanceof DefinitionStmt )
			this.initAssignment((DefinitionStmt)stmt);
}