soot.jimple.NewExpr Java Examples

The following examples show how to use soot.jimple.NewExpr. 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: TypeStateMachineWeightFunctions.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
protected Collection<WeightedForwardQuery<TransitionFunction>> generateAtAllocationSiteOf(SootMethod m, Unit unit,
        Class allocationSuperType) {
    if (unit instanceof AssignStmt) {
        AssignStmt assignStmt = (AssignStmt) unit;
        if (assignStmt.getRightOp() instanceof NewExpr) {
            NewExpr newExpr = (NewExpr) assignStmt.getRightOp();
            Value leftOp = assignStmt.getLeftOp();
            soot.Type type = newExpr.getType();
            if (Scene.v().getOrMakeFastHierarchy().canStoreType(type,
                    Scene.v().getType(allocationSuperType.getName()))) {
                return Collections.singleton(new WeightedForwardQuery<>(new Statement((Stmt) unit, m),
                        new AllocVal(leftOp, m, assignStmt.getRightOp(), new Statement((Stmt) unit, m)),
                        initialTransition()));
            }
        }
    }
    return Collections.emptySet();
}
 
Example #2
Source File: AbstractBoomerangTest.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
public Optional<? extends Query> test(Stmt unit) {
    if (unit instanceof AssignStmt) {
        AssignStmt as = (AssignStmt) unit;
        if (as.getLeftOp() instanceof Local && as.getRightOp() instanceof NewExpr) {
            NewExpr expr = ((NewExpr) as.getRightOp());
            if (allocatesObjectOfInterest(expr)) {
                Local local = (Local) as.getLeftOp();
                Statement statement = new Statement(unit, staticIcfg.getMethodOf(unit));
                ForwardQuery forwardQuery = new ForwardQuery(statement,
                        new AllocVal(local, staticIcfg.getMethodOf(unit), as.getRightOp(), statement));
                return Optional.<Query> of(forwardQuery);
            }
        }
    }
    return Optional.empty();
}
 
Example #3
Source File: BackwardBoomerangResults.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Set<Type> possibleTypes() {
    computeAllocations();
    Set<Type> res = Sets.newHashSet();
    for (ForwardQuery q : allocationSites.keySet()) {
        Val fact = q.asNode().fact();
        if (fact.isNewExpr()) {
            AllocVal alloc = (AllocVal) fact;
            NewExpr expr = (NewExpr) alloc.allocationValue();
            res.add(expr.getType());
        } else {
            res.add(fact.value().getType());
        }
    }
    return res;
}
 
Example #4
Source File: DavaBody.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
private void javafy_new_expr(ValueBox vb) {
	NewExpr ne = (NewExpr) vb.getValue();

	String className = ne.getBaseType().getSootClass().toString();
	String packageName = ne.getBaseType().getSootClass().getJavaPackageName();
	
	String classPackageName = packageName;
	
	if (className.lastIndexOf('.') > 0) {// 0 doesnt make sense
		classPackageName = className.substring(0, className.lastIndexOf('.'));
	}
	if(!packageName.equals(classPackageName))
		throw new DecompilationException("Unable to retrieve package name for identifier. Please report to developer.");
	
	addToImportList(className);
}
 
Example #5
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 #6
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 #7
Source File: NewInstanceInstruction.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
public void jimplify (DexBody body) {
      Instruction21c i = (Instruction21c)instruction;
      int dest = i.getRegisterA();
      String className = dottedClassName(((TypeReference)(i.getReference())).toString());
      RefType type = RefType.v(className);
      NewExpr n = Jimple.v().newNewExpr(type);
      assign = Jimple.v().newAssignStmt(body.getRegisterLocal(dest), n);
      setUnit(assign);
      addTags(assign);
      body.add(assign);

if (IDalvikTyper.ENABLE_DVKTYPER) {
	Debug.printDbg(IDalvikTyper.DEBUG, "constraint: "+ assign);
        int op = (int)instruction.getOpcode().value;
        //DalvikTyper.v().captureAssign((JAssignStmt)assign, op); // TODO: ref. type may be null!
        DalvikTyper.v().setType(assign.getLeftOpBox(), type, false);
      }
  }
 
Example #8
Source File: LocalMustNotAliasAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * If the given local at the given statement was initialized with a single, concrete new-expression
 * then the type of this expression is returned. Otherwise this method returns null.
 */
public RefType concreteType(Local l, Stmt s) {
	HashMap<Local,Set<NewExpr>> flowBefore = getFlowBefore(s);

	Set<NewExpr> set = flowBefore.get(l);
	if(set.size()!=1) return null;
	else {
		NewExpr singleNewExpr = set.iterator().next();
		if(singleNewExpr==UNKNOWN) return null;
		return (RefType) singleNewExpr.getType();
	}
}
 
Example #9
Source File: PointsToGraph.java    From vasco with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Stores a constant into a field of objects pointed-to by a root variable.
 */
public void setFieldConstant(Local lhs, SootField field, Constant rhs) {
	// Find out the alloc site of the constant
	NewExpr newExpr = constantNewExpr(rhs);
	// If null, do nothing, as we handle only weak updates,
	// otherwise, add the edge
	if (newExpr != null) {
		setFieldNew(lhs, field, newExpr);
	}
}
 
Example #10
Source File: PointsToGraph.java    From vasco with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a new node for a constant.
 */
private NewExpr constantNewExpr(Constant constant) {
	if (constant instanceof StringConstant) {
		return STRING_SITE;
	} else if (constant instanceof ClassConstant) {
		return CLASS_SITE;
	} else if (constant instanceof NullConstant) {
		return null;
	} else {
		throw new RuntimeException(constant.toString());
	}
}
 
Example #11
Source File: PointsToGraph.java    From vasco with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Assigns a constant to a root variable.
 */
public void assignConstant(Local lhs, Constant rhs) {
	// Get the allocation site of this constant
	NewExpr newExpr = constantNewExpr(rhs);
	// If it was a null constant, assign null, otherwise assign alloc site
	if (newExpr == null) {
		assign(lhs, null);
	} else {
		assignNew(lhs, newExpr);
	}
}
 
Example #12
Source File: AbstractBoomerangTest.java    From SPDS with Eclipse Public License 2.0 5 votes vote down vote up
private boolean allocatesObjectOfInterest(NewExpr rightOp) {
    SootClass interfaceType = Scene.v().getSootClass("test.core.selfrunning.AllocatedObject");
    if (!interfaceType.isInterface())
        return false;
    RefType allocatedType = rightOp.getBaseType();
    return Scene.v().getActiveHierarchy().getImplementersOf(interfaceType).contains(allocatedType.getSootClass());
}
 
Example #13
Source File: UnitThrowAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public void caseNewExpr(NewExpr expr) {
    result = result.add(mgr.INITIALIZATION_ERRORS);
    for (Iterator i = expr.getUseBoxes().iterator(); i.hasNext(); ) {
	ValueBox box = (ValueBox) i.next();
	result = result.add(mightThrow(box.getValue()));
    }
}
 
Example #14
Source File: LocalMustNotAliasAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return true if values of l1 (at s1) and l2 (at s2) are known
 * to point to different objects
 */
public boolean notMayAlias(Local l1, Stmt s1, Local l2, Stmt s2) {
	Set<NewExpr> l1n = getFlowBefore(s1).get(l1);
	Set<NewExpr> l2n = getFlowBefore(s2).get(l2);

    if (l1n.contains(UNKNOWN) || l2n.contains(UNKNOWN))
        return false;

    Set<NewExpr> n = new HashSet<NewExpr>(); n.addAll(l1n); n.retainAll(l2n);
    return n.isEmpty();
}
 
Example #15
Source File: LocalMustNotAliasAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns true if this analysis has any information about local l
 * at statement s (i.e. it is not {@link #UNKNOWN}).
 * In particular, it is safe to pass in locals/statements that are not
 * even part of the right method. In those cases <code>false</code>
 * will be returned.
 * Permits s to be <code>null</code>, in which case <code>false</code> will be returned.
 */
public boolean hasInfoOn(Local l, Stmt s) {
	HashMap<Local,Set<NewExpr>> flowBefore = getFlowBefore(s);
	if(flowBefore==null) {
		return false;
	} else {
		Set<NewExpr> info = flowBefore.get(l);
		return info!=null && !info.contains(UNKNOWN);
	}
}
 
Example #16
Source File: LocalMustNotAliasAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
protected HashMap<Local,Set<NewExpr>> entryInitialFlow()
{
	HashMap<Local,Set<NewExpr>> m = new HashMap<Local,Set<NewExpr>>();
    for (Local l : (Collection<Local>) locals) {
        HashSet<NewExpr> s = new HashSet<NewExpr>();
        s.add(UNKNOWN);
        m.put(l, s);
    }
    return m;
}
 
Example #17
Source File: LocalMustNotAliasAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
protected HashMap<Local,Set<NewExpr>> newInitialFlow()
{
	HashMap<Local,Set<NewExpr>> m = new HashMap<Local,Set<NewExpr>>();
    for (Local l : (Collection<Local>) locals) {
    	HashSet<NewExpr> s = new HashSet<NewExpr>(); 
        m.put(l, s);
    }
    return m;
}
 
Example #18
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 #19
Source File: LocalMustNotAliasAnalysis.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
protected void merge(HashMap<Local,Set<NewExpr>> in1, HashMap<Local,Set<NewExpr>> in2, HashMap<Local,Set<NewExpr>> o)
{

    for (Local l : locals) {
        Set<NewExpr> l1 = in1.get(l), l2 = in2.get(l);
        Set<NewExpr> out = o.get(l);
        out.clear();
        if (l1.contains(UNKNOWN) || l2.contains(UNKNOWN)) {
            out.add(UNKNOWN);
        } else {
            out.addAll(l1); out.addAll(l2);
        }
    }
}
 
Example #20
Source File: ValueTemplatePrinter.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
public void caseNewExpr(NewExpr v) {
	String oldName = varName;
	
	suggestVariableName("type");
	String typeName = varName;
	ttp.setVariableName(varName);
	v.getType().apply(ttp);
	
	p.println("Value "+oldName+" = Jimple.v().newNewExpr("+typeName+");");
	varName = oldName;

}
 
Example #21
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 #22
Source File: JimpleExprVisitorImpl.java    From FuzzDroid with Apache License 2.0 4 votes vote down vote up
@Override
public void caseNewExpr(NewExpr v) {
	throw new RuntimeException("todo");
	
}
 
Example #23
Source File: ExprTranslator.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public void caseNewExpr(NewExpr expr) {
	st.addStatement(new Nop());
}
 
Example #24
Source File: PolicyEnforcementPoint.java    From DroidForce with GNU Lesser General Public License v2.1 4 votes vote down vote up
private List<Unit> instrumentIntentAddings(BiDiInterproceduralCFG<Unit, SootMethod> cfg,
		Unit unit, InvokeExpr sinkExpr, Set<ResultSourceInfo> sourceInfo){
	if(isMethodInterComponentSink(sinkExpr.getMethod())){
		SootMethod method = cfg.getMethodOf(unit);
		Body body = null;
		if(method.hasActiveBody())
			body = method.retrieveActiveBody();
		else
			throw new RuntimeException("No body found!");
		
		Set<String> sourceCategories = getDataIdList(sourceInfo);
		
		final String hashSetType = "java.util.HashSet";
		List<Unit> generated = new ArrayList<Unit>();
		
		//HashSet initialization
		Local hashSetLocal = generateFreshLocal(body, RefType.v(hashSetType));
		NewExpr newExpr = Jimple.v().newNewExpr(RefType.v(hashSetType));
		AssignStmt assignStmt = Jimple.v().newAssignStmt(hashSetLocal, newExpr);
		generated.add(assignStmt);
		
		//constructor call
		SpecialInvokeExpr constructorCall = Jimple.v().newSpecialInvokeExpr(hashSetLocal, Scene.v().getMethod("<java.util.HashSet: void <init>()>").makeRef());
		InvokeStmt constructorCallStmt = Jimple.v().newInvokeStmt(constructorCall);
		generated.add(constructorCallStmt);
		
		//add categories to HashSet
		for(String cat : sourceCategories){
			InterfaceInvokeExpr addCall = Jimple.v().newInterfaceInvokeExpr(hashSetLocal, Scene.v().getMethod("<java.util.Set: boolean add(java.lang.Object)>").makeRef(), StringConstant.v(cat));
			InvokeStmt addCallStmt = Jimple.v().newInvokeStmt(addCall);
			generated.add(addCallStmt);
		}
		
		//get Intent
		Value intent = sinkExpr.getArg(0);
		List<Object> args = new ArrayList<Object>();
		args.add(RefType.v("android.content.Intent"));
		args.add(intent);
		args.add(RefType.v(hashSetType));
		args.add(hashSetLocal);
		StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
				Settings.INSTRUMENTATION_HELPER_JAVA,
				"addTaintInformationToIntent",
				args);
		InvokeStmt invStmt = Jimple.v().newInvokeStmt(sie);
		generated.add(invStmt);
		
		return generated;
	}
	return Collections.emptyList();
}
 
Example #25
Source File: SootMethodRefImpl.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
    * Creates a method body that throws an "unresolved compilation error"
    * message
    * @param declaringClass The class that was supposed to contain the method
    * @return The created SootMethod
    */
private SootMethod createUnresolvedErrorMethod(SootClass declaringClass) {
	SootMethod m = new SootMethod(name, parameterTypes, returnType, isStatic()?Modifier.STATIC:0);
	int modifiers = Modifier.PUBLIC; //  we don't know who will be calling us
	if (isStatic())
		modifiers |= Modifier.STATIC;
	m.setModifiers(modifiers);
	JimpleBody body = Jimple.v().newBody(m);
	m.setActiveBody(body);

	final LocalGenerator lg = new LocalGenerator(body);
	
	// For producing valid Jimple code, we need to access all parameters.
	// Otherwise, methods like "getThisLocal()" will fail.
	if (!isStatic) {
		RefType thisType = RefType.v(declaringClass);
		Local lThis = lg.generateLocal(thisType);
		body.getUnits().add(Jimple.v().newIdentityStmt(lThis, Jimple.v().newThisRef(thisType)));
	}
	for (int i = 0; i < m.getParameterCount(); i++) {
		Type paramType = m.getParameterType(i);
		Local lParam = lg.generateLocal(paramType);
		body.getUnits().add(Jimple.v().newIdentityStmt(lParam, Jimple.v().newParameterRef(paramType, i)));
	}
	
	//exc = new Error
	RefType runtimeExceptionType = RefType.v("java.lang.Error");
	NewExpr newExpr = Jimple.v().newNewExpr(runtimeExceptionType);
	Local exceptionLocal = lg.generateLocal(runtimeExceptionType);
	AssignStmt assignStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr);
	body.getUnits().add(assignStmt);
	
	//exc.<init>(message)
	SootMethodRef cref = Scene.v().makeConstructorRef(runtimeExceptionType.getSootClass(),
			Collections.<Type>singletonList(RefType.v("java.lang.String")));
	SpecialInvokeExpr constructorInvokeExpr = Jimple.v().newSpecialInvokeExpr(exceptionLocal, cref,
			StringConstant.v("Unresolved compilation error: Method "+getSignature()+" does not exist!"));
	InvokeStmt initStmt = Jimple.v().newInvokeStmt(constructorInvokeExpr);
	body.getUnits().insertAfter(initStmt, assignStmt);
	
	//throw exc
	body.getUnits().insertAfter(Jimple.v().newThrowStmt(exceptionLocal), initStmt);

	declaringClass.addMethod(m);
	return m;
}
 
Example #26
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 #27
Source File: AllocVal.java    From SPDS with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean isNewExpr() {
    return alloc instanceof NewExpr;
}
 
Example #28
Source File: ConstructorFolder.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/** This method change all new Obj/<init>(args) pairs to new Obj(args) idioms. */
protected void internalTransform(Body b, String phaseName, Map options)
{
    GrimpBody body = (GrimpBody)b;

    if(Options.v().verbose())
        G.v().out.println("[" + body.getMethod().getName() +
            "] Folding constructors...");

  Chain units = body.getUnits();
  List<Unit> stmtList = new ArrayList<Unit>();
  stmtList.addAll(units);

  Iterator<Unit> it = stmtList.iterator();
  
  LocalUses localUses = LocalUses.Factory.newLocalUses(b);

  /* fold in NewExpr's with specialinvoke's */
  while (it.hasNext())
    {
      Stmt s = (Stmt)it.next();
        
      if (!(s instanceof AssignStmt))
        continue;
        
      /* this should be generalized to ArrayRefs */
      Value lhs = ((AssignStmt)s).getLeftOp();
      if (!(lhs instanceof Local))
        continue;
        
      Value rhs = ((AssignStmt)s).getRightOp();
      if (!(rhs instanceof NewExpr))
        continue;

      /* TO BE IMPLEMENTED LATER: move any copy of the object reference
         for lhs down beyond the NewInvokeExpr, with the rationale
         being that you can't modify the object before the constructor
         call in any case.

         Also, do note that any new's (object creation) without
         corresponding constructors must be dead. */
       
      List lu = localUses.getUsesOf(s);
      Iterator luIter = lu.iterator();
      boolean MadeNewInvokeExpr = false;
       
      while (luIter.hasNext())
        {
          Unit use = ((UnitValueBoxPair)(luIter.next())).unit;
          if (!(use instanceof InvokeStmt))
            continue;
          InvokeStmt is = (InvokeStmt)use;
          if (!(is.getInvokeExpr() instanceof SpecialInvokeExpr) ||
              lhs != ((SpecialInvokeExpr)is.getInvokeExpr()).getBase())
            continue;
          
          SpecialInvokeExpr oldInvoke = 
            ((SpecialInvokeExpr)is.getInvokeExpr());
          LinkedList invokeArgs = new LinkedList();
          for (int i = 0; i < oldInvoke.getArgCount(); i++)
            invokeArgs.add(oldInvoke.getArg(i));
          
          AssignStmt constructStmt = Grimp.v().newAssignStmt
            ((AssignStmt)s);
          constructStmt.setRightOp
            (Grimp.v().newNewInvokeExpr
             (((NewExpr)rhs).getBaseType(), oldInvoke.getMethodRef(), invokeArgs));
          MadeNewInvokeExpr = true;
          
          use.redirectJumpsToThisTo(constructStmt);
          units.insertBefore(constructStmt, use);
          units.remove(use);
        }
      if (MadeNewInvokeExpr)
        {
          units.remove(s);
        }
    }
}
 
Example #29
Source File: ExceptionalUnitGraph.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
/**
 * <p>
 * Utility method for checking if a {@link Unit} might have side effects. It
 * simply returns true for any unit which invokes a method directly or which
 * might invoke static initializers indirectly (by creating a new object or
 * by refering to a static field; see sections 2.17.4, 2.17.5, and 5.5 of
 * the Java Virtual Machine Specification).
 * </p>
 *
 * <code>mightHaveSideEffects()</code> is declared package-private so that
 * it is available to unit tests that are part of this package.
 *
 * @param u
 *            The unit whose potential for side effects is to be checked.
 *
 * @return whether or not <code>u</code> has the potential for side effects.
 */
static boolean mightHaveSideEffects(Unit u) {
	if (u instanceof Inst) {
		Inst i = (Inst) u;
		return (i.containsInvokeExpr() || (i instanceof StaticPutInst)
				|| (i instanceof StaticGetInst) || (i instanceof NewInst));
	} else if (u instanceof Stmt) {
		for (ValueBox vb : u.getUseBoxes()) {
			Value v = vb.getValue();
			if ((v instanceof StaticFieldRef) || (v instanceof InvokeExpr)
					|| (v instanceof NewExpr)) {
				return true;
			}
		}
	}
	return false;
}
 
Example #30
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(stmtBody);
   PatchingChain<Unit> units = stmtBody.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("<init>".equals(special.getMethodRef().name()))
	  {
	    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)
		      {			
			// We split the local.
			//G.v().out.println("split: [" + assign + "] and [" + stmt + "]");
			Local newlocal = Jimple.v().newLocal("tmp", null);
			stmtBody.getLocals().add(newlocal);
			
			special.setBase(newlocal);
			
			units.insertAfter(Jimple.v().newAssignStmt(assign.getLeftOp(), newlocal), assign);
			assign.setLeftOp(newlocal);
		      }
		  }
		break;
	      }
	  }
      }
  }
     }
 }