soot.jimple.CastExpr Java Examples

The following examples show how to use soot.jimple.CastExpr. 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: BaseSelector.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * the operations that are not relevant for analysis like "not" or casts
 * are removed - array refs are only removed if explicitly stated
 * @param val the value which should be pruned
 * @param keepArrayRef if false then array refs are pruned to the base array object
 * @return the value (possibly pruned to base object)
 */ //we want to keep ArrayRef for objects on the right side of the assignment
public static Value selectBase(Value val, boolean keepArrayRef){
	//we taint base of array instead of array elements
	if (val instanceof ArrayRef && !keepArrayRef) {
		return selectBase(((ArrayRef) val).getBase(), keepArrayRef);
	}
	
	if (val instanceof CastExpr) {
		return selectBase(((CastExpr) val).getOp(), keepArrayRef);
	}
	
	// Check for unary operators like "not" or "length"
	if (val instanceof UnopExpr)
		return selectBase(((UnopExpr) val).getOp(), keepArrayRef);
	
	return val;
}
 
Example #2
Source File: CastInstruction.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public void jimplify (DexBody body) {
     TwoRegisterInstruction i = (TwoRegisterInstruction)instruction;
     int dest = i.getRegisterA();
     int source = i.getRegisterB();
     Type targetType = getTargetType();
     CastExpr cast = Jimple.v().newCastExpr(body.getRegisterLocal(source), targetType);
     assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), cast);
     assign.addTag (getTag());
     setUnit(assign);
     addTags(assign);
     body.add(assign);
     
     if (IDalvikTyper.ENABLE_DVKTYPER) {
Debug.printDbg(IDalvikTyper.DEBUG, "constraint cast: "+ assign +" castexpr type: "+ cast.getType()+" cast type: "+ cast.getCastType());
       int op = (int)instruction.getOpcode().value;
       DalvikTyper.v().setType(assign.getLeftOpBox(), cast.getType(), false);
       //DalvikTyper.v().captureAssign((JAssignStmt)assign, op);
     }
 }
 
Example #3
Source File: CheckCastInstruction.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public void jimplify (DexBody body) {
      if(!(instruction instanceof Instruction21c))
          throw new IllegalArgumentException("Expected Instruction21c but got: "+instruction.getClass());

      Instruction21c checkCastInstr = (Instruction21c)instruction;

      Local castValue = body.getRegisterLocal(checkCastInstr.getRegisterA());
      Type checkCastType = DexType.toSoot((TypeReference) checkCastInstr.getReference());

      CastExpr castExpr =  Jimple.v().newCastExpr(castValue, checkCastType);

      //generate "x = (Type) x"
      //splitter will take care of the rest
      assign = Jimple.v().newAssignStmt(castValue, castExpr);

      setUnit(assign);
      addTags(assign);
      body.add(assign);
      

      if (IDalvikTyper.ENABLE_DVKTYPER) {
	Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ assign);
          DalvikTyper.v().setType(assign.getLeftOpBox(), checkCastType, false);
}

  }
 
Example #4
Source File: DavaBody.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
private void javafy_expr(ValueBox vb) {
	Expr e = (Expr) vb.getValue();

	if (e instanceof BinopExpr)
		javafy_binop_expr(vb);
	else if (e instanceof UnopExpr)
		javafy_unop_expr(vb);
	else if (e instanceof CastExpr)
		javafy_cast_expr(vb);
	else if (e instanceof NewArrayExpr)
		javafy_newarray_expr(vb);
	else if (e instanceof NewMultiArrayExpr)
		javafy_newmultiarray_expr(vb);
	else if (e instanceof InstanceOfExpr)
		javafy_instanceof_expr(vb);
	else if (e instanceof InvokeExpr)
		javafy_invoke_expr(vb);
	else if (e instanceof NewExpr)
		javafy_new_expr(vb);
}
 
Example #5
Source File: UnitThrowAnalysis.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public void caseCastExpr(CastExpr expr) {
    result = result.add(mgr.RESOLVE_CLASS_ERRORS);
    Type fromType = expr.getOp().getType();
    Type toType = expr.getCastType();
    if (toType instanceof RefLikeType) {
	// fromType might still be unknown when we are called,
	// but toType will have a value.
	FastHierarchy h = Scene.v().getOrMakeFastHierarchy();
	if (fromType == null || fromType instanceof UnknownType ||
	    ((! (fromType instanceof NullType)) &&
	     (! h.canStoreType(fromType, toType)))) {
	    result = result.add(mgr.CLASS_CAST_EXCEPTION);
	}
    }
    result = result.add(mightThrow(expr.getOp()));
}
 
Example #6
Source File: CopyConstantAnalysis.java    From vasco with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void assign(Local lhs, Value rhs, Map<Local, Constant> input, Map<Local, Constant> output) {
	// First remove casts, if any.
	if (rhs instanceof CastExpr) {
		rhs = ((CastExpr) rhs).getOp();
	}
	// Then check if the RHS operand is a constant or local
	if (rhs instanceof Constant) {
		// If RHS is a constant, it is a direct gen
		output.put(lhs, (Constant) rhs);
	} else if (rhs instanceof Local) {
		// Copy constant-status of RHS to LHS (indirect gen), if exists
		if(input.containsKey(rhs)) {
			output.put(lhs, input.get(rhs));
		}
	} else {
		// RHS is some compound expression, then LHS is non-constant (only kill)
		output.put(lhs, null);
	}			
}
 
Example #7
Source File: JimpleExprVisitorImpl.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
public void caseCastExpr(CastExpr v) {
	//just propagate the taint value of previous statement
	Stmt prevStmt = stmtVisitor.getPreviousDataFlowPathElement(currentStatement);
	if(prevStmt == null)
		throw new RuntimeException("there is no previous statement");
	else{			
		this.result = stmtVisitor.getBindingForTaintedValue(prevStmt);
		if(this.result == null)
			throw new RuntimeException("double check this here");
	}
}
 
Example #8
Source File: ValueTemplatePrinter.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void caseCastExpr(CastExpr v) {
	String oldName = varName;
	
	suggestVariableName("type");
	String lhsName = varName;
	ttp.setVariableName(varName);
	v.getType().apply(ttp);
	
	String rhsName = printValueAssignment(v.getOp(), "op");
	
	p.println("Value "+oldName+" = Jimple.v().newCastExpr("+lhsName+","+rhsName+");");
	
	varName = oldName;		
}
 
Example #9
Source File: ExprVisitor.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void caseCastExpr(CastExpr ce) {
	Type castType = ce.getCastType();
	Value source = ce.getOp();
	constantV.setOrigStmt(origStmt);
	Register sourceReg = regAlloc.asImmediate(source, constantV);
	if (SootToDexUtils.isObject(castType)) {
		castObject(sourceReg, castType);
	} else {
		castPrimitive(sourceReg, source, castType);
	}
}
 
Example #10
Source File: CastAndReturnInliner.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void internalTransform(Body body, String phaseName,
		Map<String, String> options) {
	Iterator<Unit> it = body.getUnits().snapshotIterator();
	while (it.hasNext()) {
		Unit u = it.next();
		if (u instanceof GotoStmt) {
			GotoStmt gtStmt = (GotoStmt) u;
			if (gtStmt.getTarget() instanceof AssignStmt) {
				AssignStmt assign = (AssignStmt) gtStmt.getTarget();
				if (assign.getRightOp() instanceof CastExpr) {
					CastExpr ce = (CastExpr) assign.getRightOp();
					// We have goto that ends up at a cast statement
					Unit nextStmt = body.getUnits().getSuccOf(assign);
					if (nextStmt instanceof ReturnStmt) {
						ReturnStmt retStmt = (ReturnStmt) nextStmt;
						if (retStmt.getOp() == assign.getLeftOp()) {
							// We need to replace the GOTO with the return
							ReturnStmt newStmt = (ReturnStmt) retStmt.clone();
							newStmt.setOp(ce.getOp());

							for (Trap t : body.getTraps())
								for (UnitBox ubox : t.getUnitBoxes())
									if (ubox.getUnit() == gtStmt)
										ubox.setUnit(newStmt);
							
							while (!gtStmt.getBoxesPointingToThis().isEmpty())
								gtStmt.getBoxesPointingToThis().get(0).setUnit(newStmt);
							body.getUnits().swapWith(gtStmt, newStmt);
						}
					}
				}
			}
		}
	}
}
 
Example #11
Source File: AbstractBoomerangSolver.java    From SPDS with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isCastNode(Node<Statement, Val> node) {
    Stmt stmt = node.stmt().getUnit().get();
    AssignStmt x;
    if (stmt instanceof AssignStmt && (x = (AssignStmt) stmt).getRightOp() instanceof CastExpr) {
        CastExpr c = (CastExpr) x.getRightOp();
        if (c.getOp().equals(node.fact().value())) {
            return true;
        }
    }
    return false;
}
 
Example #12
Source File: SignAnalysis.java    From vasco with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void assign(Local lhs, Value rhs, Map<Local, SignAnalysis.Sign> input, Map<Local, SignAnalysis.Sign> output) {
	// We only care about numeric locals
	if (lhs.getType() instanceof IntType) {			
		// First remove casts, if any.
		if (rhs instanceof CastExpr) {
			rhs = ((CastExpr) rhs).getOp();
		}	
		// Determine the sign of the RHS and add it to the map
		Sign sign = signOf(rhs, input);
		output.put(lhs, sign);
	}
}
 
Example #13
Source File: GeomEvaluator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Count how many static casts can be determined safe.
 */
public void checkCastsSafety() 
{
	

	for (SootMethod sm : ptsProvider.getAllReachableMethods()) {
		if (sm.isJavaLibraryMethod())
			continue;
		if (!sm.isConcrete())
			continue;
		if (!sm.hasActiveBody()) {
			sm.retrieveActiveBody();
		}
		if (!ptsProvider.isValidMethod(sm))
			continue;

		// All the statements in the method
		for (Iterator<Unit> stmts = sm.getActiveBody().getUnits().iterator(); stmts
				.hasNext();) {
			Stmt st = (Stmt) stmts.next();

			if (st instanceof AssignStmt) {
				Value rhs = ((AssignStmt) st).getRightOp();
				Value lhs = ((AssignStmt) st).getLeftOp();
				if (rhs instanceof CastExpr
						&& lhs.getType() instanceof RefLikeType) {

					Value v = ((CastExpr) rhs).getOp();
					VarNode node = ptsProvider.findLocalVarNode(v);
					if (node == null)
						continue;
					IVarAbstraction pn = ptsProvider.findInternalNode(node);
					if (pn == null)
						continue;

					pn = pn.getRepresentative();
					if ( !pn.hasPTResult() ) continue;
					
					evalRes.total_casts++;
					final Type targetType = 
							(RefLikeType) ((CastExpr) rhs).getCastType();

					// We first use the geometric points-to result to
					// evaluate
					solved = true;
					Set<AllocNode> set = pn.get_all_points_to_objects();
					for (AllocNode obj : set) {
						solved = ptsProvider.castNeverFails(obj.getType(),
								targetType);
						if (solved == false)
							break;
					}

					if (solved)
						evalRes.geom_solved_casts++;

					// Second is the SPARK result
					solved = true;
					node.getP2Set().forall(new P2SetVisitor() {
						public void visit(Node arg0) {
							if (solved == false)
								return;
							solved = ptsProvider.castNeverFails(
									arg0.getType(), targetType);
						}
					});

					if (solved)
						evalRes.spark_solved_casts++;
				}
			}
		}
	}

	ptsProvider.ps.println();
	ptsProvider.ps
			.println("-----------> Static Casts Safety Evaluation <------------");
	ptsProvider.ps.println("Total casts (app code): " + evalRes.total_casts);
	ptsProvider.ps.println("Safe casts: Geom = " + evalRes.geom_solved_casts
			+ ", SPARK = " + evalRes.spark_solved_casts);
}
 
Example #14
Source File: DavaBody.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void javafy_cast_expr(ValueBox vb) {
	CastExpr ce = (CastExpr) vb.getValue();
	javafy(ce.getOpBox());
}
 
Example #15
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 #16
Source File: AsmMethodSource.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void convertPrimCastInsn(InsnNode insn) {
	int op = insn.getOpcode();
	boolean tod = op == I2L || op == I2D ||
			op == F2L || op == F2D ||
			op == D2L || op == L2D;
	boolean fromd = op == D2L || op == L2D ||
			op == D2I || op == L2I ||
			op == D2F || op == L2F;
	StackFrame frame = getFrame(insn);
	Operand[] out = frame.out();
	Operand opr;
	if (out == null) {
		Type totype;
		if (op == I2L || op == F2L || op == D2L)
			totype = LongType.v();
		else if (op == L2I || op == F2I || op == D2I)
			totype = IntType.v();
		else if (op == I2F || op == L2F || op == D2F)
			totype = FloatType.v();
		else if (op == I2D || op == L2D || op == F2D)
			totype = DoubleType.v();
		else if (op == I2B)
			totype = ByteType.v();
		else if (op == I2S)
			totype = ShortType.v();
		else if (op == I2C)
			totype = CharType.v();
		else
			throw new AssertionError("Unknonw prim cast op: " + op);
		Operand val = fromd ? popImmediateDual() : popImmediate();
		CastExpr cast = Jimple.v().newCastExpr(val.stackOrValue(), totype);
		opr = new Operand(insn, cast);
		val.addBox(cast.getOpBox());
		frame.in(val);
		frame.boxes(cast.getOpBox());
		frame.out(opr);
	} else {
		opr = out[0];
		frame.mergeIn(fromd ? popDual() : pop());
	}
	if (tod)
		pushDual(opr);
	else
		push(opr);
}