コード例 #1
0
  public static boolean maybeSameLocation(Value v1, Value v2) {
    if (!(v1 instanceof InstanceFieldRef && v2 instanceof InstanceFieldRef)
        && !(v1 instanceof ArrayRef && v2 instanceof ArrayRef)) {
      return v1.equivTo(v2);
    }
    if (v1 instanceof InstanceFieldRef && v2 instanceof InstanceFieldRef) {
      InstanceFieldRef ifr1 = (InstanceFieldRef) v1;
      InstanceFieldRef ifr2 = (InstanceFieldRef) v2;
      if (!ifr1.getField().getName().equals(ifr2.getField().getName())) return false;

      Local base1 = (Local) ifr1.getBase();
      Local base2 = (Local) ifr2.getBase();
      PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
      PointsToSet pts1 = pta.reachingObjects(base1);
      PointsToSet pts2 = pta.reachingObjects(base2);
      return pts1.hasNonEmptyIntersection(pts2);
    } else { // v1 instanceof ArrayRef && v2 instanceof ArrayRef
      ArrayRef ar1 = (ArrayRef) v1;
      ArrayRef ar2 = (ArrayRef) v2;

      Local base1 = (Local) ar1.getBase();
      Local base2 = (Local) ar2.getBase();
      PointsToAnalysis pta = Scene.v().getPointsToAnalysis();
      PointsToSet pts1 = pta.reachingObjects(base1);
      PointsToSet pts2 = pta.reachingObjects(base2);
      return pts1.hasNonEmptyIntersection(pts2);
    }
  }
コード例 #2
0
  protected void internalTransform(String pn, Map map) {
    SymbiosisTransformer.tlo = new ThreadLocalObjectsAnalysis(new SynchObliviousMhpAnalysis());
    SymbiosisTransformer.ftea = new XFieldThreadEscapeAnalysis();
    SymbiosisTransformer.pecg = new PegCallGraph(Scene.v().getCallGraph());

    Iterator<SootClass> classIt = Scene.v().getApplicationClasses().iterator();
    while (classIt.hasNext()) {
      SootClass sc = classIt.next();

      Iterator<SootMethod> methodIt = sc.getMethods().iterator();

      while (methodIt.hasNext()) {
        SootMethod sm = methodIt.next();

        if (sm.isAbstract() || sm.isNative()) continue;

        try {
          Body body = sm.retrieveActiveBody();
          SymbFindSVPass.v().internalTransform(body, pn, map);
        } catch (Exception e) {
          System.err.println("[SymbiosisTransformer] SymbScenePass: " + e.getMessage());
          e.printStackTrace();
          continue;
        }
      }
    }
  }
コード例 #3
0
ファイル: Mocker.java プロジェクト: serval-snt-uni-lu/DroidRA
  public static SootClass mockSootClass(String clsName) {
    SootClass sc = null;

    if (Scene.v().containsClass(clsName)) {
      sc = Scene.v().getSootClass(clsName);

      if (sc.isPhantom()) {
        // sc.setPhantom(false);
        sc.setApplicationClass();
        sc.setInScene(true);

        try {
          for (Field field : sc.getClass().getFields()) {
            if (field.getName().equals("isPhantom")) {
              field.setAccessible(true);
              field.setBoolean(sc, false);
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    } else {
      sc = new SootClass(clsName);
      sc.setSuperclass(Scene.v().getSootClass("java.lang.Object"));

      sc.setPhantom(false);
      sc.setApplicationClass();
      sc.setInScene(true);
    }

    mockConstructor(sc);

    return sc;
  }
コード例 #4
0
ファイル: Util.java プロジェクト: pabloloyola/soot
  public static Collection<Type> getP2Nodes(Value v) {
    PointsToSet p2sTypes;
    if (v instanceof Local) p2sTypes = Scene.v().getPointsToAnalysis().reachingObjects((Local) v);
    else p2sTypes = Scene.v().getPointsToAnalysis().reachingObjects(((FieldRef) v).getField());

    return (Collection<Type>) p2sTypes.possibleTypes();
  }
コード例 #5
0
 private void loadClasses() {
   Date start = new Date();
   if (entryClass != null) {
     SootUtils.loadClassesForEntry(entryClass);
   } else {
     for (JavaCriticalSection cs : results) {
       String clsname = cs.getClassName();
       String regex = "\\$\\d";
       Pattern pattern = Pattern.compile(regex);
       Matcher matcher = pattern.matcher(clsname);
       if (matcher.find()) {
         System.out.println("can't find the class created randomly by compiler");
         continue;
       }
       SootClass cls = Scene.v().loadClassAndSupport(clsname);
       if (setMainClass == true
           && cls.declaresMethod(
               Scene.v().getSubSigNumberer().findOrAdd("void main(java.lang.String[])"))) {
         Scene.v().setMainClass(cls);
         setMainClass = false;
       }
     }
     Scene.v().loadNecessaryClasses();
   }
   Date end = new Date();
   System.out.println(
       "load " + Scene.v().getClasses().size() + " classes in " + getTimeConsumed(start, end));
 }
コード例 #6
0
  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();
  }
コード例 #7
0
  /**
   * Instruments the runtime version of the program.
   *
   * @param mainclass
   */
  public static void transformRuntimeVersion(String mainclass) {
    PackManager.v().getPack("jtp").add(new Transform("jtp.intrumenter", SymbBodyPass.v()));
    setOptions(mainclass, false);

    Scene.v()
        .setSootClassPath(
            System.getProperty("sun.boot.class.path")
                + File.pathSeparator
                + System.getProperty("java.class.path"));

    Scene.v().loadClassAndSupport(runtimeClass);

    try {

      // ** instrument runtime version
      String outpath = getOutputDir();
      String[] args1 = getArgs(mainclass, outpath);

      soot.Main.main(args1);
      System.err.println("***** Runtime version generated *****\n");

      // reset soot parameters
      soot.G.reset();
      bbIdCounter = 0;

    } catch (Exception e) {
      System.err.println(">> Exception: " + e.getMessage());
      e.printStackTrace();
    }
  }
コード例 #8
0
ファイル: Code.java プロジェクト: peterthiemann/gradual-java
 private static SootClass makeFreshClass(String name) {
   // reset the testClass
   if (Scene.v().containsClass(name)) {
     Scene.v().removeClass(Scene.v().getSootClass(name));
   }
   SootClass result = new SootClass(name);
   Scene.v().addClass(result);
   return result;
 }
コード例 #9
0
ファイル: AssignPlusExpr.java プロジェクト: JansenLi/soot
  /**
   * @ast method
   * @aspect Expressions
   * @declaredat
   *     /Users/eric/Documents/workspaces/clara-soot/JastAddExtensions/JimpleBackend/Expressions.jrag:84
   */
  public soot.Value eval(Body b) {
    TypeDecl dest = getDest().type();
    TypeDecl source = getSource().type();
    if (dest.isString()) {

      Value lvalue = getDest().eval(b);

      Value v = asImmediate(b, lvalue);

      // new StringBuffer(left)
      Local local =
          b.newTemp(b.newNewExpr(lookupType("java.lang", "StringBuffer").sootRef(), this));
      b.setLine(this);
      b.add(
          b.newInvokeStmt(
              b.newSpecialInvokeExpr(
                  local,
                  Scene.v()
                      .getMethod("<java.lang.StringBuffer: void <init>(java.lang.String)>")
                      .makeRef(),
                  v,
                  this),
              this));

      // append right
      Local rightResult =
          b.newTemp(
              b.newVirtualInvokeExpr(
                  local,
                  lookupType("java.lang", "StringBuffer")
                      .methodWithArgs("append", new TypeDecl[] {source.stringPromotion()})
                      .sootRef(),
                  asImmediate(b, getSource().eval(b)),
                  this));

      // toString
      Local result =
          b.newTemp(
              b.newVirtualInvokeExpr(
                  rightResult,
                  Scene.v()
                      .getMethod("<java.lang.StringBuffer: java.lang.String toString()>")
                      .makeRef(),
                  this));

      Value v2 = lvalue instanceof Local ? lvalue : (Value) lvalue.clone();
      getDest().emitStore(b, v2, result, this);
      return result;
    } else {
      return super.eval(b);
    }
  }
コード例 #10
0
  private static void setOptions(String mainclass, boolean isJPF) {
    PhaseOptions.v().setPhaseOption("jb", "enabled:true");
    PhaseOptions.v().setPhaseOption("tag.ln", "on");
    Options.v().set_keep_line_number(true);
    Options.v().setPhaseOption("jb", "use-original-names:true");
    Options.v().set_app(true);
    Options.v().set_whole_program(true);

    if (isJPF) {
      // Enable Spark
      HashMap<String, String> opt = new HashMap<String, String>();
      // opt.put("verbose","true");
      opt.put("propagator", "worklist");
      opt.put("simple-edges-bidirectional", "false");
      opt.put("on-fly-cg", "true");
      opt.put("set-impl", "double");
      opt.put("double-set-old", "hybrid");
      opt.put("double-set-new", "hybrid");
      opt.put("pre_jimplify", "true");
      SparkTransformer.v().transform("", opt);
      PhaseOptions.v().setPhaseOption("cg.spark", "enabled:true");

      Scene.v()
          .setSootClassPath(
              System.getProperty("sun.boot.class.path")
                  + File.pathSeparator
                  + System.getProperty("java.class.path"));
    }

    List excludes = new ArrayList();
    excludes.add("org.eclipse.");
    excludes.add("javax.");
    excludes.add("java.");
    excludes.add("pt.tecnico.");
    Options.v().set_exclude(excludes);

    List includes = new ArrayList();
    includes.add("org.apache.commons.pool."); // pool107
    includes.add("org.apache.log4j."); // log4j_3
    includes.add("org.apache.commons.lang."); // lang
    Options.v().set_include(includes);

    SootClass appclass = Scene.v().loadClassAndSupport(mainclass);

    try {
      Scene.v().setMainClass(appclass);
      Scene.v().getMainClass();
    } catch (Exception e) {
      System.out.println(">> Exception [No main class]: " + e.getMessage());
    }
  }
コード例 #11
0
ファイル: Util.java プロジェクト: pabloloyola/soot
  /** For instance invokes */
  public static ArrayList<SootMethod> resolveAppCall(Type tgtType, SootMethodRef methodRef) {
    final NumberedString mSubsignature = methodRef.getSubSignature();
    if (tgtType instanceof RefType) {
      // find first class upwards in hierarchy, starting from cls, that implements method (i.e.,
      // *concrete* method)
      SootClass cls = ((RefType) tgtType).getSootClass();
      while (!cls.declaresMethod(mSubsignature))
        cls =
            cls
                .getSuperclass(); // if method not in this class, it HAS to be in a superclass, so a
                                  // superclass must exist

      if (!cls.hasTag(ClassTag.TAG_NAME)) return null; // not an app method

      // finally, store resolved app method
      SootMethod m = cls.getMethod(mSubsignature);
      assert m.hasTag(MethodTag.TAG_NAME);

      ArrayList<SootMethod> methods = new ArrayList<SootMethod>();
      methods.add(m); // just one element, directly resolved
      return methods;
    }

    if (tgtType instanceof AnySubType) {
      // return set of all app subtypes that implement referenced method
      SootClass baseCls = ((AnySubType) tgtType).getBase().getSootClass();
      List subClasses =
          baseCls.isInterface()
              ? Scene.v().getActiveHierarchy().getImplementersOf(baseCls)
              : Scene.v().getActiveHierarchy().getSubclassesOf(baseCls);
      ArrayList<SootMethod> methods = new ArrayList<SootMethod>();
      for (Object oSubCls : subClasses) {
        SootClass subCls = (SootClass) oSubCls;
        if (subCls.hasTag(ClassTag.TAG_NAME)) {
          try {
            SootMethod m = subCls.getMethod(mSubsignature);
            assert m.hasTag(MethodTag.TAG_NAME);
            if (!m.isAbstract()) methods.add(m);
          } catch (RuntimeException e) {
          }
        }
      }

      return methods;
    }

    assert tgtType instanceof ArrayType; // only other case observed so far
    return new ArrayList(); // no array class/method is in app
  }
コード例 #12
0
  protected void readNonRefField(OpenCLField field) {
    SootField soot_field = field.getSootField();
    String function_name = "read" + getTypeString(soot_field);

    BytecodeLanguage bcl = m_bcl.top();
    bcl.pushMethod(m_currMem.top(), function_name, soot_field.getType());
    Local data = bcl.invokeMethodRet(m_currMem.top());

    SootClass soot_class = Scene.v().getSootClass(soot_field.getDeclaringClass().getName());
    if (soot_class.isApplicationClass()) {
      if (field.isInstance()) {
        bcl.setInstanceField(soot_field, m_objSerializing.top(), data);
      } else {
        bcl.setStaticField(soot_field, data);
      }
    } else {
      SootClass obj = Scene.v().getSootClass("java.lang.Object");
      SootClass string = Scene.v().getSootClass("java.lang.String");
      String static_str;
      SootClass first_param_type;
      Value first_param;
      if (field.isInstance()) {
        static_str = "";
        first_param_type = obj;
        first_param = m_objSerializing.top();
      } else {
        static_str = "Static";
        first_param_type = Scene.v().getSootClass("java.lang.Class");
        first_param = ClassConstant.v(soot_class.getName());
      }
      String private_field_fun_name = "write" + static_str + getTypeString(soot_field);
      Local private_fields = bcl.newInstance("org.trifort.rootbeer.runtime.PrivateFields");
      bcl.pushMethod(
          private_fields,
          private_field_fun_name,
          VoidType.v(),
          first_param_type.getType(),
          string.getType(),
          string.getType(),
          soot_field.getType());
      bcl.invokeMethodNoRet(
          private_fields,
          first_param,
          StringConstant.v(soot_field.getName()),
          StringConstant.v(soot_field.getDeclaringClass().getName()),
          data);
    }
  }
コード例 #13
0
 public Map<Unit, Set<TaintFact>> initialSeeds() {
   if (DEBUG) System.out.println("initial seeds");
   return DefaultSeeds.make(
       Collections.singleton(
           Scene.v().getEntryPoints().get(0).getActiveBody().getUnits().getFirst()),
       zeroValue());
 }
コード例 #14
0
  /**
   * Instruments the Java Path Finder version of the program.
   *
   * @param mainclass
   */
  public static void transformJPFVersion(String mainclass) {
    sharedVars = new HashSet<String>();

    PackManager.v().getPack("wjtp").add(new Transform("wjtp.transformer", new SymbScenePass()));
    PackManager.v().getPack("jtp").add(new Transform("jtp.transformer", new SymbBodyPass()));
    setOptions(mainclass, true);
    Scene.v().loadClassAndSupport(jpfClass);

    try {

      // ** instrument JPF version
      JPF_MODE = true;
      String outpath = getOutputDir();
      sharedAccLogPath = outpath + mainclass + ".accesses";
      String[] args1 = getArgs(mainclass, outpath);

      soot.Main.main(args1);
      System.err.println("***** JPF version generated *****");
      saveSharedAccessesLog();

    } catch (Exception e) {
      System.err.println(">> Exception: " + e.getMessage());
      e.printStackTrace();
    }
  }
コード例 #15
0
 private void run(String cls, boolean app_class) {
   SootClass soot_class = Scene.v().getSootClass(cls);
   List<SootMethod> methods = soot_class.getMethods();
   for (SootMethod method : methods) {
     visit(method);
   }
 }
コード例 #16
0
public class TopologicalOrderer {
  CallGraph cg;
  List<SootMethod> order = new ArrayList<SootMethod>();
  NumberedSet visited = new NumberedSet(Scene.v().getMethodNumberer());

  public TopologicalOrderer(CallGraph cg) {
    this.cg = cg;
  }

  public void go() {
    Iterator methods = cg.sourceMethods();
    while (methods.hasNext()) {
      SootMethod m = (SootMethod) methods.next();
      dfsVisit(m);
    }
  }

  private void dfsVisit(SootMethod m) {
    if (visited.contains(m)) return;
    visited.add(m);
    Iterator targets = new Targets(cg.edgesOutOf(m));
    while (targets.hasNext()) {
      SootMethod target = (SootMethod) targets.next();
      dfsVisit(target);
    }
    order.add(m);
  }

  public List<SootMethod> order() {
    return order;
  }
}
コード例 #17
0
  public void dumpTextGraph(String fileName) {
    // TODO Auto-generated method stub
    PrintStream printStream = null;
    try {
      printStream = new PrintStream(fileName);
    } catch (Exception ex) {
      logger.warn("Cannot dump TextGraph {} ", fileName);
      return;
    }

    callgraphSet.clear();

    for (SootMethod entry : Scene.v().getEntryPoints()) {
      /*
        printStream.printf("Entry %s \n", entry.toString());
        Iterator<Edge> iterator = callGraph.edgesOutOf(entry);
        while (iterator.hasNext()) {
        totalIndegree++;
        Edge edge = iterator.next();
        printStream.printf("%d: %s \n", totalIndegree, edge.tgt().toString());
        }
        printStream.printf("\n");
      */
      dumpTextGraph(entry, printStream, 0);
    }

    printStream.close();
  }
コード例 #18
0
ファイル: Clazzes.java プロジェクト: ashleyj/aura
 SootClass getSootClass(Clazz clazz) {
   if (!sootInitialized) {
     initializeSoot(this);
     sootInitialized = true;
   }
   return Scene.v().loadClassAndSupport(clazz.getClassName());
 }
コード例 #19
0
ファイル: OnFlyCallGraph.java プロジェクト: safdariqbal/soot
 public OnFlyCallGraph(PAG pag) {
   this.pag = pag;
   CGOptions options = new CGOptions(PhaseOptions.v().getPhaseOptions("cg"));
   if (options.all_reachable()) {
     List entryPoints = new ArrayList();
     entryPoints.addAll(EntryPoints.v().all());
     entryPoints.addAll(EntryPoints.v().methodsOfApplicationClasses());
     Scene.v().setEntryPoints(entryPoints);
   }
   callGraph = new CallGraph();
   Scene.v().setCallGraph(callGraph);
   ContextManager cm = CallGraphBuilder.makeContextManager(callGraph);
   reachableMethods = Scene.v().getReachableMethods();
   ofcgb = new OnFlyCallGraphBuilder(cm, reachableMethods);
   reachablesReader = reachableMethods.listener();
   callEdges = cm.callGraph().listener();
 }
コード例 #20
0
ファイル: Clazzes.java プロジェクト: ashleyj/aura
  private static void initializeSoot(Clazzes clazzes) {
    soot.G.reset();
    Options.v().set_output_format(Options.output_format_jimple);
    Options.v().set_include_all(true);
    Options.v().set_print_tags_in_output(true);
    Options.v().set_allow_phantom_refs(true);
    Options.v().set_keep_line_number(true);
    Options.v().set_soot_classpath(getSootClasspath(clazzes));

    /*
     * Enable the use-original-names phase to merge local variables and
     * verbose logging for debugging purposes only.
     */
    // Options.v().set_verbose(true);
    // Options.v().setPhaseOption("jb", "use-original-names:true");
    /*
     * Disable the jb.dae phase (DeadAssignmentEliminator) since it removes
     * LDC instructions which would have thrown a NoClassDefFoundError.
     * TODO: Report this to soot as a bug?
     */
    Options.v().setPhaseOption("jb.dae", "enabled:false");
    /*
     * Disable the jb.uce phase (UnreachableCodeEliminator) since it seems
     * to remove try-catch blocks which catches a non-existing Throwable
     * class. This should generate a NoClassDefFoundError at runtime but
     * with the UCE in place no exception is thrown.
     */
    Options.v().setPhaseOption("jb.uce", "enabled:false");

    /*
     * Enable jap.npc (NullPointerChecker) and jap.abc (ArrayBoundsChecker)
     * phases in the annotation pack. The annotation pack is enabled by
     * default but all its phases are disabled by default.
     */
    Options.v().setPhaseOption("jap.npc", "enabled:true");
    Options.v().setPhaseOption("jap.abc", "enabled:true");

    /*
     * Enable the jop (Jimple optimization) pack but disable all phases for
     * now.
     */
    Options.v().setPhaseOption("jop", "enabled:true");
    Options.v().setPhaseOption("jop.cse", "enabled:false");
    Options.v().setPhaseOption("jop.bcm", "enabled:false");
    Options.v().setPhaseOption("jop.lcm", "enabled:false");
    Options.v().setPhaseOption("jop.cp", "enabled:false");
    Options.v().setPhaseOption("jop.cpf", "enabled:false");
    Options.v().setPhaseOption("jop.cbf", "enabled:false");
    Options.v().setPhaseOption("jop.dae", "enabled:false");
    Options.v().setPhaseOption("jop.nce", "enabled:false");
    Options.v().setPhaseOption("jop.uce1", "enabled:false");
    Options.v().setPhaseOption("jop.ubf1", "enabled:false");
    Options.v().setPhaseOption("jop.uce2", "enabled:false");
    Options.v().setPhaseOption("jop.ubf2", "enabled:false");
    Options.v().setPhaseOption("jop.ule", "enabled:false");

    Scene.v().loadNecessaryClasses();
  }
コード例 #21
0
  public static void main(String args[]) {
    // Set classPath
    String exemplePath = "/Users/gamyot/Documents/workspace/Soot_Exemples/src/";
    String objectPath = "/System/Library/Frameworks/JavaVM.framework/Classes/classes.jar";
    String tracePath = "/Users/gamyot/Documents/workspace/SootInstrumenter/src/";

    Scene.v().setSootClassPath(".:" + objectPath + ":" + exemplePath + ":" + tracePath);

    Scene.v().loadClassAndSupport("java.lang.Object");
    Scene.v().loadClassAndSupport("java.lang.System");

    // Set up the class we’re working with
    SootClass c = Scene.v().loadClassAndSupport("MyExemples.ExempleBasic");
    c.setApplicationClass();

    // Get methods
    Iterator<SootMethod> methodIterator = c.methodIterator();
    while (methodIterator.hasNext()) methodList.add(methodIterator.next());
    // Iterate through the method list
    for (SootMethod m : methodList) {
      Body body = m.retrieveActiveBody();
      PatchingChain<Unit> unitList = body.getUnits();
      // get the all the "if statements" Units
      List<Unit> ifStmtList = searchIfStmts(body);

      // for each "if statement" unit, instrument and add the instrumentation code right after
      for (Unit ifStmtUnit : ifStmtList) {
        // Chain<Unit> instrumentedChain = generateInstrumentationUnits(ifStmtUnit, body);
        // unitList.insertAfter(instrumentedChain, ifStmtUnit);
        Chain<Unit> testChain = generateInstrumentationUnits(ifStmtUnit, body);
        unitList.insertAfter(testChain, ifStmtUnit);
      }
      // Output all the units for this method on terminal
      String methodName = m.getName();
      System.out.println(
          "____Method: \"" + methodName + "\"__________________________________________________");
      LoadAndGenerate.printAllUnits(body);
    }

    try {
      LoadAndGenerate.outputClassToBinary(c);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #22
0
  /**
   * For a concrete method (declared in an application class), find statements containing an invoke
   * expression for which the method is one of the method in 'allEventInformation' (i.e.,
   * getLine1Number(), ...).
   *
   * @param cfg
   */
  private void doAccessControlChecks(BiDiInterproceduralCFG<Unit, SootMethod> cfg) {
    for (SootClass sc : Scene.v().getApplicationClasses()) {
      for (SootMethod sm : sc.getMethods()) {
        if (sm.isConcrete()) {
          Body body = sm.retrieveActiveBody();
          // only instrument application methods (i.e., not methods declared in PEP helper classes
          // or in a Java library classes or in an Android classes, ...)
          if (isInstrumentationNecessary(sm)) {

            // important to use snapshotIterator here
            Iterator<Unit> i = body.getUnits().snapshotIterator();
            log.debug("method: " + sm);
            while (i.hasNext()) {
              Stmt s = (Stmt) i.next();

              if (s.containsInvokeExpr()) {
                InvokeExpr invExpr = s.getInvokeExpr();
                String methodSignature = invExpr.getMethod().getSignature();

                if (allEventInformation.containsKey(methodSignature)) {
                  log.debug("statement " + s + " matches " + methodSignature + ".");
                  ResultSinkInfo sink = null;

                  outer:
                  for (ResultSinkInfo key : results.getResults().keySet()) {

                    // iterate over all the arguments of the invoke expression
                    // and check if an argument is a tainted sink. If one is
                    // set variable 'sink' to the ResultSinkInfo key.
                    for (Value v : invExpr.getArgs()) {
                      Value pathValue = key.getAccessPath().getPlainValue();
                      if (v == pathValue) {
                        sink = key;
                        log.debug("found a sink: " + pathValue);
                        break outer;
                      }
                    }
                  }

                  if (sink != null) {
                    log.debug("instrument with data flow information )" + s + ")");
                    instrumentSourceToSinkConnections(cfg, sink, s instanceof AssignStmt);
                    instrumentWithNoDataFlowInformation(
                        methodSignature, s, invExpr, body, s instanceof AssignStmt);
                  } else {
                    log.debug("instrument without data flow information (" + s + ")");
                    instrumentWithNoDataFlowInformation(
                        methodSignature, s, invExpr, body, s instanceof AssignStmt);
                  }
                }
              } // if stmt containts invoke expression
            } // loop on statements
          }
        }
      }
    }
  }
コード例 #23
0
  public void getAllInvolvedMethods() {

    ReachableMethods rm =
        CallGraphHelper.getReachableMethod(Scene.v().getCallGraph(), syncsEnclosingMethods);
    for (Iterator<?> it = rm.listener(); it.hasNext(); ) {
      SootMethod m = (SootMethod) it.next();
      allInvolvedMethod.add(m);
    }
  }
コード例 #24
0
ファイル: ThrowableSet.java プロジェクト: safdariqbal/soot
  /**
   * Indicates whether this ThrowableSet includes some exception that might be caught by a handler
   * argument of the type <code>catcher</code>.
   *
   * @param catcher type of the handler parameter to be tested.
   * @return <code>true</code> if this set contains an exception type that might be caught by <code>
   *     catcher</code>, false if it does not.
   */
  public boolean catchableAs(RefType catcher) {
    if (INSTRUMENTING) {
      Manager.v().catchableAsQueries++;
    }

    FastHierarchy h = Scene.v().getOrMakeFastHierarchy();

    if (exceptionsExcluded.size() > 0) {
      if (INSTRUMENTING) {
        Manager.v().catchableAsFromSearch++;
      }
      for (Iterator i = exceptionsExcluded.iterator(); i.hasNext(); ) {
        AnySubType exclusion = (AnySubType) i.next();
        if (h.canStoreType(catcher, exclusion.getBase())) {
          return false;
        }
      }
    }

    if (exceptionsIncluded.contains(catcher)) {
      if (INSTRUMENTING) {
        if (exceptionsExcluded.size() == 0) {
          Manager.v().catchableAsFromMap++;
        } else {
          Manager.v().catchableAsFromSearch++;
        }
      }
      return true;
    } else {
      if (INSTRUMENTING) {
        if (exceptionsExcluded.size() == 0) {
          Manager.v().catchableAsFromSearch++;
        }
      }
      for (Iterator i = exceptionsIncluded.iterator(); i.hasNext(); ) {
        RefLikeType thrownType = (RefLikeType) i.next();
        if (thrownType instanceof RefType) {
          if (thrownType == catcher) {
            // assertion failure.
            throw new IllegalStateException(
                "ThrowableSet.catchableAs(RefType): exceptions.contains() failed to match contained RefType "
                    + catcher);
          } else if (h.canStoreType(thrownType, catcher)) {
            return true;
          }
        } else {
          RefType thrownBase = ((AnySubType) thrownType).getBase();
          // At runtime, thrownType might be instantiated by any
          // of thrownBase's subtypes, so:
          if (h.canStoreType(thrownBase, catcher) || h.canStoreType(catcher, thrownBase)) {
            return true;
          }
        }
      }
      return false;
    }
  }
コード例 #25
0
  @Override
  protected void runInternal() {
    // don't print crap to screen!
    G.v().out = new PrintStream(NullOutputStream.NULL_OUTPUT_STREAM);
    Scene.v().loadDynamicClasses();

    setSparkPointsToAnalysis();

    // other passes can print crap now
    G.v().out = System.out;

    ptsProvider = (PAG) Scene.v().getPointsToAnalysis();

    typeManager = ptsProvider.getTypeManager();

    // cache the call graph
    callGraph = Scene.v().getCallGraph();

    createNewToAllocMap();

    /*
    for (SootMethod method : getReachableMethods()) {
        Set<MethodOrMethodContext> mcs = getMethodContexts(method);
        if (mcs.size() > 30)
            System.out.println(method + " " + mcs.size());
    }
     */

    // dumpReachablesAndAllocNodes();
    // dumpCallGraphReachablesCSV();
    // dumpOutdegreesCSV();

    if (Config.v().dumpPta) {
      dumpPTA(Project.v().getOutputDir() + File.separator + "pta.txt");
    }

    if (Config.v().dumpCallGraph) {
      // dumpCallGraph(Project.v().getOutputDir() + File.separator + "callgraph.dot");
      String fileName = String.format("callgraph%d.txt", runCount++);
      dumpTextGraph(Project.v().getOutputDir() + File.separator + fileName);
    }

    // System.out.println(SparkEvaluator.v().toString());
  }
コード例 #26
0
  public static SootClass createSootClass(String clsName) {
    SootClass sc = new SootClass(clsName);
    sc.setSuperclass(Scene.v().getSootClass("java.lang.Object"));

    sc.setApplicationClass();
    sc.setPhantom(false);
    sc.setInScene(true);

    return sc;
  }
コード例 #27
0
 @Override
 protected void internalTransform(String string, Map map) {
   CallGraph call_graph = Scene.v().getCallGraph();
   Iterator<MethodOrMethodContext> src_methods = call_graph.sourceMethods();
   while (src_methods.hasNext()) {
     MethodOrMethodContext momc = src_methods.next();
     SootMethod soot_method = momc.method();
     String signature = soot_method.getSignature();
     System.out.println(signature);
   }
 }
コード例 #28
0
ファイル: KernelMain.java プロジェクト: Elblonko/kepler
    /**
     * Transform the Scene according to the information specified in the model for this transform.
     *
     * @param phaseName The phase this transform is operating under.
     * @param options The options to apply.
     */
    protected void internalTransform(String phaseName, Map options) {
      // For some reason, soot 2.0.1 gives java.lang.Object as
      // its own superclass!
      PtolemyUtilities.objectClass.setSuperclass(null);

      for (Iterator classes = Scene.v().getApplicationClasses().snapshotIterator();
          classes.hasNext(); ) {
        SootClass theClass = (SootClass) classes.next();
        theClass.setLibraryClass();
      }
    }
コード例 #29
0
 public CallGraph buildCallGraph(Collection<JavaCriticalSection> validSyncs)
     throws NoMatchingSootMethodException {
   CallGraphBuilder cgb = new CallGraphBuilder(DumbPointerAnalysis.v());
   cgb.build();
   CallGraph cg = Scene.v().getCallGraph();
   for (JavaCriticalSection cs : results) {
     String clsname = cs.getClassName();
     String regex = "\\$\\d";
     Pattern pattern = Pattern.compile(regex);
     Matcher matcher = pattern.matcher(clsname);
     if (matcher.find()) {
       continue;
     }
     validSyncs.add(cs);
     cs.bindToSoot();
     syncsEnclosingMethods.add(cs.getSootMethod());
   }
   Scene.v().setCallGraph(cg);
   return cg;
 }
コード例 #30
0
  public ReverseClassHierarchy(Map<String, OpenCLClass> classes) {
    m_Hierarchy = new ArrayList<TreeNode>();
    m_Classes = classes;

    addClass("java.lang.String");

    Set<String> key_set = classes.keySet();
    Set<String> visited = new HashSet<String>();
    for (String key : key_set) {
      OpenCLClass ocl_class = classes.get(key);
      SootClass soot_class = Scene.v().getSootClass(ocl_class.getJavaName());
      if (soot_class.hasSuperclass() == false) continue;
      SootClass parent = soot_class.getSuperclass();
      if (parent.getName().equals("java.lang.Object")) {
        TreeNode tree = new TreeNode(soot_class, ocl_class);
        m_Hierarchy.add(tree);
        visited.add(key);
      }
    }

    boolean modified;
    do {
      modified = false;

      key_set = classes.keySet();
      for (String key : key_set) {
        if (visited.contains(key)) continue;
        OpenCLClass ocl_class = classes.get(key);
        SootClass soot_class = Scene.v().getSootClass(ocl_class.getJavaName());
        if (soot_class.hasSuperclass() == false) continue;
        SootClass parent = soot_class.getSuperclass();
        TreeNode node = getNode(parent);
        if (node == null) continue;
        node.addChild(soot_class, ocl_class);
        modified = true;
        visited.add(key);
      }

    } while (modified);
  }