Java Code Examples for soot.jimple.IntConstant#v()

The following examples show how to use soot.jimple.IntConstant#v() . 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: CPHelper.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public static Value createConstant(Object toConvert){
	if(toConvert instanceof Long){
		return LongConstant.v( ((Long)toConvert).longValue() );
	}
	else if(toConvert instanceof Double){
		return DoubleConstant.v( ((Double)toConvert).doubleValue());
	}
	else if(toConvert instanceof Boolean){
		boolean val = ((Boolean)toConvert).booleanValue();
		if(val)
			return DIntConstant.v(1,BooleanType.v());
		else
			return DIntConstant.v(0,BooleanType.v());
	}	
	else if(toConvert instanceof Float){
		return FloatConstant.v( ((Float)toConvert).floatValue());
	}
	else if(toConvert instanceof Integer){
		return IntConstant.v( ((Integer)toConvert).intValue());
	}
	else
		return null;
}
 
Example 2
Source File: PointsToAnalysis.java    From vasco with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns a points-to graph with the locals of main initialised to
 * <tt>null</tt>, except the command-line arguments which are
 * initialised to an array of strings.
 */
@Override
public PointsToGraph boundaryValue(SootMethod entryPoint) {
	// For now we only support entry to the main method
	assert(entryPoint == Scene.v().getMainMethod());
	
	// Ok, start setting up entry value
	PointsToGraph entryValue = new PointsToGraph();		

	// Locals of main... (only reference types)
	SootMethod mainMethod = Scene.v().getMainMethod();
	for (Local local : mainMethod.getActiveBody().getLocals()) {
		if (local.getType() instanceof RefLikeType) {
			entryValue.assign(local, null);
		}
	}		
	
	// Command-line arguments to main...
	Local argsLocal = mainMethod.getActiveBody().getParameterLocal(0);
	NewArrayExpr argsExpr = new JNewArrayExpr(Scene.v().getRefType("java.lang.String"), IntConstant.v(0));
	entryValue.assignNew(argsLocal, argsExpr);
	entryValue.setFieldConstant(argsLocal, PointsToGraph.ARRAY_FIELD, PointsToGraph.STRING_CONST);
	

	return entryValue;
}
 
Example 3
Source File: PolicyEnforcementPoint.java    From DroidForce with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 
 * @param parameter
 * @param body
 * @return
 */
private Pair<Value, List<Unit>> generateParameterArray(List<Value> parameter, Body body){
	List<Unit> generated = new ArrayList<Unit>();
	
	NewArrayExpr arrayExpr = Jimple.v().newNewArrayExpr(RefType.v("java.lang.Object"), IntConstant.v(parameter.size()));
	
	Value newArrayLocal = generateFreshLocal(body, getParameterArrayType());
	Unit newAssignStmt = Jimple.v().newAssignStmt(newArrayLocal, arrayExpr);
	generated.add(newAssignStmt);
	
	for(int i = 0; i < parameter.size(); i++){
		Value index = IntConstant.v(i);
		ArrayRef leftSide = Jimple.v().newArrayRef(newArrayLocal, index);
		Value rightSide = generateCorrectObject(body, parameter.get(i), generated);
		
		Unit parameterInArray = Jimple.v().newAssignStmt(leftSide, rightSide);
		generated.add(parameterInArray);
	}
	
	return new Pair<Value, List<Unit>>(newArrayLocal, generated);
}
 
Example 4
Source File: AsmMethodSource.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
private Value toSootValue(Object val) throws AssertionError {
	Value v;
	if (val instanceof Integer)
		v = IntConstant.v((Integer) val);
	else if (val instanceof Float)
		v = FloatConstant.v((Float) val);
	else if (val instanceof Long)
		v = LongConstant.v((Long) val);
	else if (val instanceof Double)
		v = DoubleConstant.v((Double) val);
	else if (val instanceof String)
		v = StringConstant.v(val.toString());
	else if (val instanceof org.objectweb.asm.Type)
		v = ClassConstant.v(((org.objectweb.asm.Type) val).getInternalName());
	else if (val instanceof Handle)
		v = MethodHandle.v(toSootMethodRef((Handle) val), ((Handle)val).getTag());
	else
		throw new AssertionError("Unknown constant type: " + val.getClass());
	return v;
}
 
Example 5
Source File: UtilInstrumenter.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
public static Pair<Value, List<Unit>> generateParameterArray(List<Value> parameterList, Body body){
	List<Unit> generated = new ArrayList<Unit>();
	
	NewArrayExpr arrayExpr = Jimple.v().newNewArrayExpr(RefType.v("java.lang.Object"), IntConstant.v(parameterList.size()));
	
	Value newArrayLocal = generateFreshLocal(body, getParameterArrayType());
	Unit newAssignStmt = Jimple.v().newAssignStmt(newArrayLocal, arrayExpr);
	generated.add(newAssignStmt);
	
	for(int i = 0; i < parameterList.size(); i++){
		Value index = IntConstant.v(i);
		ArrayRef leftSide = Jimple.v().newArrayRef(newArrayLocal, index);
		Value rightSide = generateCorrectObject(body, parameterList.get(i), generated);
		
		Unit parameterInArray = Jimple.v().newAssignStmt(leftSide, rightSide);
		generated.add(parameterInArray);
	}
	
	return new Pair<Value, List<Unit>>(newArrayLocal, generated);
}
 
Example 6
Source File: BaseEntryPointCreator.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
protected Value getSimpleDefaultValue(String t) {
	if (t.equals("java.lang.String"))
		return StringConstant.v("");
	if (t.equals("char"))
		return DIntConstant.v(0, CharType.v());
	if (t.equals("byte"))
		return DIntConstant.v(0, ByteType.v());
	if (t.equals("short"))
		return DIntConstant.v(0, ShortType.v());
	if (t.equals("int"))
		return IntConstant.v(0);
	if (t.equals("float"))
		return FloatConstant.v(0);
	if (t.equals("long"))
		return LongConstant.v(0);
	if (t.equals("double"))
		return DoubleConstant.v(0);
	if (t.equals("boolean"))
		return DIntConstant.v(0, BooleanType.v());

	//also for arrays etc.
	return G.v().soot_jimple_NullConstant();
}
 
Example 7
Source File: BinopLitInstruction.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void jimplify (DexBody body) {
     if(!(instruction instanceof Instruction22s) && !(instruction instanceof Instruction22b))
         throw new IllegalArgumentException("Expected Instruction22s or Instruction22b but got: "+instruction.getClass());

     NarrowLiteralInstruction binOpLitInstr = (NarrowLiteralInstruction) this.instruction;
     int dest = ((TwoRegisterInstruction) instruction).getRegisterA();
     int source = ((TwoRegisterInstruction) instruction).getRegisterB();

     Local source1 = body.getRegisterLocal(source);

     IntConstant constant = IntConstant.v((int)binOpLitInstr.getNarrowLiteral());

     expr = getExpression(source1, constant);

     assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), expr);
     assign.addTag(getTag());

     setUnit(assign);
     addTags(assign);
     body.add(assign);
     
     if (IDalvikTyper.ENABLE_DVKTYPER) {
Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ assign);
         int op = (int)instruction.getOpcode().value;
       if (op >= 0xd8) {
         op -= 0xd8;
       } else {
         op -= 0xd0;
       }
       BinopExpr bexpr = (BinopExpr)expr;
       //body.dvkTyper.setType((op == 1) ? bexpr.getOp2Box() : bexpr.getOp1Box(), op1BinType[op]);
       DalvikTyper.v().setType(((JAssignStmt)assign).leftBox, op1BinType[op], false);
     }
 }
 
Example 8
Source File: ExprVisitor.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private Value fixNullConstant(Value potentialNullConstant) {
	/*
	 * The bytecode spec says: "In terms of bitwise representation, (Object) null == (int) 0."
	 * So use an IntConstant(0) for null comparison in if-*z opcodes.
	 */
	if (potentialNullConstant instanceof NullConstant) {
		return IntConstant.v(0);
	}
	return potentialNullConstant;
}
 
Example 9
Source File: AsmMethodSource.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private void convertConstInsn(InsnNode insn) {
	int op = insn.getOpcode();
	StackFrame frame = getFrame(insn);
	Operand[] out = frame.out();
	Operand opr;
	if (out == null) {
		Value v;
		if (op == ACONST_NULL)
			v = NullConstant.v();
		else if (op >= ICONST_M1 && op <= ICONST_5)
			v = IntConstant.v(op - ICONST_0);
		else if (op == LCONST_0 || op == LCONST_1)
			v = LongConstant.v(op - LCONST_0);
		else if (op >= FCONST_0 && op <= FCONST_2)
			v = FloatConstant.v(op - FCONST_0);
		else if (op == DCONST_0 || op == DCONST_1)
			v = DoubleConstant.v(op - DCONST_0);
		else
			throw new AssertionError("Unknown constant opcode: " + op);
		opr = new Operand(insn, v);
		frame.out(opr);
	} else {
		opr = out[0];
	}
	if (op == LCONST_0 || op == LCONST_1 ||
			op == DCONST_0 || op == DCONST_1) {
		pushDual(opr);
	} else {
		push(opr);
	}
}
 
Example 10
Source File: InstrumentationUtils.java    From DroidRA with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Value toDefaultSootTypeValue(Type sootType)
{
	String type = sootType.toString();
	
	if ("boolean".equals(type))
	{
		IntConstant.v(0);
	}
	else if ("byte".equals(type))
	{
		return IntConstant.v(0);
	}
	else if ("char".equals(type))
	{
		return IntConstant.v(0);
	}
	else if ("short".equals(type))
	{
		return IntConstant.v(0);
	}
	else if ("int".equals(type))
	{
		return IntConstant.v(0);
	}
	else if ("long".equals(type))
	{
		return LongConstant.v(0);
	}
	else if ("float".equals(type))
	{
		return FloatConstant.v(0);
	}
	else if ("double".equals(type))
	{
		return DoubleConstant.v(0);
	}

	return NullConstant.v();
}
 
Example 11
Source File: UntypedIntOrFloatConstant.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public IntConstant toIntConstant() {
    return IntConstant.v(value);
}
 
Example 12
Source File: ConstInstruction.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Return the literal constant for this instruction.
 *
 * @param register the register number to fill
 * @param body the body containing the instruction
 */
private Constant getConstant(int dest, DexBody body) {

    long literal = 0;

    if (instruction instanceof WideLiteralInstruction) {
        literal = ((WideLiteralInstruction)instruction).getWideLiteral();
    } else if (instruction instanceof NarrowLiteralInstruction) {
        literal = ((NarrowLiteralInstruction)instruction).getNarrowLiteral();
    } else {
        throw new RuntimeException("literal error: expected narrow or wide literal.");
    }
    

    // floats are handled later in DexBody by calling DexNumtransformer
    Opcode opcode = instruction.getOpcode();
    switch (opcode) {
    case CONST:
    case CONST_4:
    case CONST_16:
        if (IDalvikTyper.ENABLE_DVKTYPER) {
            return UntypedIntOrFloatConstant.v((int)literal);
        } else {
            return IntConstant.v((int) literal);
        }

    case CONST_HIGH16:
        if (IDalvikTyper.ENABLE_DVKTYPER) {
            //
            //return UntypedIntOrFloatConstant.v((int)literal<<16).toFloatConstant();
            // seems that dexlib correctly puts the 16bits into the topmost bits.
            //
            return UntypedIntOrFloatConstant.v((int)literal);//.toFloatConstant();
        } else {
            return IntConstant.v((int) literal);
        }

    case CONST_WIDE_HIGH16:
        if (IDalvikTyper.ENABLE_DVKTYPER) {
            //return UntypedLongOrDoubleConstant.v((long)literal<<48).toDoubleConstant();
            // seems that dexlib correctly puts the 16bits into the topmost bits.
            //
            return UntypedLongOrDoubleConstant.v((long)literal);//.toDoubleConstant();
        } else {
        	return LongConstant.v(literal);
        }

    case CONST_WIDE:
    case CONST_WIDE_16:
    case CONST_WIDE_32:
        if (IDalvikTyper.ENABLE_DVKTYPER) {
            return UntypedLongOrDoubleConstant.v(literal);
        } else {
        	return LongConstant.v(literal);
        }
    default:
        throw new IllegalArgumentException("Expected a const or a const-wide instruction, got neither.");
    }
}
 
Example 13
Source File: CONSTANT_Integer_info.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public Value createJimpleConstantValue(cp_info[] constant_pool) {
return IntConstant.v((int) bytes);
 }
 
Example 14
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 15
Source File: AsmMethodSource.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void convertIntInsn(IntInsnNode insn) {
	int op = insn.getOpcode();
	StackFrame frame = getFrame(insn);
	Operand[] out = frame.out();
	Operand opr;
	if (out == null) {
		Value v;
		if (op == BIPUSH || op == SIPUSH) {
			v = IntConstant.v(insn.operand);
		} else {
			Type type;
			switch (insn.operand) {
			case T_BOOLEAN:
				type = BooleanType.v();
				break;
			case T_CHAR:
				type = CharType.v();
				break;
			case T_FLOAT:
				type = FloatType.v();
				break;
			case T_DOUBLE:
				type = DoubleType.v();
				break;
			case T_BYTE:
				type = ByteType.v();
				break;
			case T_SHORT:
				type = ShortType.v();
				break;
			case T_INT:
				type = IntType.v();
				break;
			case T_LONG:
				type = LongType.v();
				break;
			default:
				throw new AssertionError("Unknown NEWARRAY type!");
			}
			Operand size = popImmediate();
			NewArrayExpr anew = Jimple.v().newNewArrayExpr(type, size.stackOrValue());
			size.addBox(anew.getSizeBox());
			frame.in(size);
			frame.boxes(anew.getSizeBox());
			v = anew;
		}
		opr = new Operand(insn, v);
		frame.out(opr);
	} else {
		opr = out[0];
		if (op == NEWARRAY)
			frame.mergeIn(pop());
	}
	push(opr);
}
 
Example 16
Source File: InterproceduralConstantValuePropagator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
private void fixExceptions(SootMethod caller, Unit callSite, Set<SootClass> doneSet) {
	ThrowAnalysis ta = Options.v().src_prec() == Options.src_prec_apk
			? DalvikThrowAnalysis.v() : UnitThrowAnalysis.v();
	ThrowableSet throwSet = ta.mightThrow(callSite);
	
	for (final Trap t : caller.getActiveBody().getTraps())
		if (doneSet.add(t.getException())
				&& throwSet.catchableAs(t.getException().getType())) {
			SootMethod thrower = exceptionThrowers.get(t.getException());
			if (thrower == null) {
				if (exceptionClass == null) {
					exceptionClass = new SootClass("FLOWDROID_EXCEPTIONS", Modifier.PUBLIC);
					Scene.v().addClass(exceptionClass);
				}
				
				// Create the new method
				thrower = new SootMethod("throw" + exceptionThrowers.size(),
						Collections.<Type>emptyList(), VoidType.v());
				thrower.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
				
				final Body body = Jimple.v().newBody(thrower);
				thrower.setActiveBody(body);
				final SootMethod meth = thrower;
				
				IEntryPointCreator epc = new BaseEntryPointCreator() {
	
					@Override
					public Collection<String> getRequiredClasses() {
						return Collections.emptySet();
					}
	
					@Override
					protected SootMethod createDummyMainInternal(SootMethod emptySootMethod) {
				 		LocalGenerator generator = new LocalGenerator(body);
						
				 		// Create the counter used for the opaque predicate
						int conditionCounter = 0;
						Value intCounter = generator.generateLocal(IntType.v());
						AssignStmt assignStmt = new JAssignStmt(intCounter, IntConstant.v(conditionCounter));
						body.getUnits().add(assignStmt);
						
						Stmt afterEx = Jimple.v().newNopStmt();
						IfStmt ifStmt = Jimple.v().newIfStmt(Jimple.v().newEqExpr(intCounter,
								IntConstant.v(conditionCounter)), afterEx);
						body.getUnits().add(ifStmt);
						conditionCounter++;
						
						Local lcEx = generator.generateLocal(t.getException().getType());
						AssignStmt assignNewEx = Jimple.v().newAssignStmt(lcEx,
								Jimple.v().newNewExpr(t.getException().getType()));
						body.getUnits().add(assignNewEx);

						InvokeStmt consNewEx = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(lcEx,
								Scene.v().makeConstructorRef(exceptionClass, Collections.<Type>emptyList())));
						body.getUnits().add(consNewEx);
						
						ThrowStmt throwNewEx = Jimple.v().newThrowStmt(lcEx);
						body.getUnits().add(throwNewEx);
						
						body.getUnits().add(afterEx);
						return meth;
					}
									
				};
				epc.createDummyMain(thrower);
				exceptionThrowers.put(t.getException(), thrower);
				exceptionClass.addMethod(thrower);
			}
			
			// Call the exception thrower after the old call site
			Stmt throwCall = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(thrower.makeRef()));
			caller.getActiveBody().getUnits().insertBefore(throwCall, callSite);
		}
}
 
Example 17
Source File: SignAnalysis.java    From vasco with GNU Lesser General Public License v2.1 4 votes vote down vote up
private Sign signOf(Value value, Map<Local, Sign> dfv) {
	if (value instanceof Local) {
		// if the value is a local variable, then look-up the data-flow map
		Local local = (Local) value;
		if (dfv.containsKey(local)) {
			return dfv.get(local);
		} else {
			return Sign.TOP;
		}
	} else if (value instanceof NumericConstant) {
		// If the value is a constant, we can get a definite sign
		NumericConstant num = (NumericConstant) value;
		NumericConstant zero = IntConstant.v(0);
		NumericConstant one = IntConstant.v(1);
		if (num.lessThan(zero).equals(one)) {
			return NEGATIVE;
		} else if (num.greaterThan(zero).equals(one)) {
			return POSITIVE;
		} else {
			return ZERO;
		}
	} else if (value instanceof BinopExpr) {
		BinopExpr expr = (BinopExpr) value;
		Value op1 = expr.getOp1();
		Value op2 = expr.getOp2();
		Sign sign1 = signOf(op1, dfv);
		Sign sign2 = signOf(op2, dfv);
		if (value instanceof AddExpr) {
			// Handle arithmetic plus
			return sign1.plus(sign2);
		} else if (value instanceof MulExpr) {
			// Handle arithmetic multiplication
			return sign1.mult(sign2);
		} else {
			// We do not handle other types of binary expressions
			return BOTTOM;
		}
	} else if (value instanceof UnopExpr) { 
		if (value instanceof AbstractNegExpr) {
			// Handle unary minus
			Value op = ((AbstractNegExpr) value).getOp();
			Sign sign = signOf(op, dfv);
			return sign.negate();
		} else {
			// We do not handle other types of binary expressions
			return BOTTOM;
		}
	} else {
		// We do not handle other types of compound expressions
		return BOTTOM;
	}
}
 
Example 18
Source File: DefaultEntryPointCreator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected SootMethod createDummyMainInternal(SootMethod mainMethod) {
	Map<String, Set<String>> classMap =
			SootMethodRepresentationParser.v().parseClassNames(methodsToCall, false);
	
	// create new class:
	Body body = mainMethod.getActiveBody();
		LocalGenerator generator = new LocalGenerator(body);
	HashMap<String, Local> localVarsForClasses = new HashMap<String, Local>();
	
	// create constructors:
	for(String className : classMap.keySet()){
		SootClass createdClass = Scene.v().forceResolve(className, SootClass.BODIES);
		createdClass.setApplicationClass();
		
		Local localVal = generateClassConstructor(createdClass, body);
		if (localVal == null) {
			logger.warn("Cannot generate constructor for class: {}", createdClass);
			continue;
		}
		localVarsForClasses.put(className, localVal);
	}
	
	// add entrypoint calls
	int conditionCounter = 0;
	JNopStmt startStmt = new JNopStmt();
	JNopStmt endStmt = new JNopStmt();
	Value intCounter = generator.generateLocal(IntType.v());
	body.getUnits().add(startStmt);
	for (Entry<String, Set<String>> entry : classMap.entrySet()){
		Local classLocal = localVarsForClasses.get(entry.getKey());
		for (String method : entry.getValue()){
			SootMethodAndClass methodAndClass =
					SootMethodRepresentationParser.v().parseSootMethodString(method);
			SootMethod currentMethod = findMethod(Scene.v().getSootClass(methodAndClass.getClassName()),
					methodAndClass.getSubSignature());
			if (currentMethod == null) {
				logger.warn("Entry point not found: {}", method);
				continue;
			}
			
			JEqExpr cond = new JEqExpr(intCounter, IntConstant.v(conditionCounter));
			conditionCounter++;
			JNopStmt thenStmt = new JNopStmt();
			JIfStmt ifStmt = new JIfStmt(cond, thenStmt);
			body.getUnits().add(ifStmt);
			buildMethodCall(currentMethod, body, classLocal, generator);
			body.getUnits().add(thenStmt);
		}
	}
	body.getUnits().add(endStmt);
	JGotoStmt gotoStart = new JGotoStmt(startStmt);
	body.getUnits().add(gotoStart);
	
	body.getUnits().add(Jimple.v().newReturnVoidStmt());
	NopEliminator.v().transform(body);
	eliminateSelfLoops(body);
	return mainMethod;
}