Exemplo n.º 1
0
  /** Prints the given <code>JimpleBody</code> to the specified <code>PrintWriter</code>. */
  private void printLocalsInBody(Body body, UnitPrinter up) {
    // Print out local variables
    {
      Map typeToLocals = new DeterministicHashMap(body.getLocalCount() * 2 + 1, 0.7f);

      // Collect locals
      {
        Iterator localIt = body.getLocals().iterator();

        while (localIt.hasNext()) {
          Local local = (Local) localIt.next();

          List localList;

          Type t = local.getType();

          if (typeToLocals.containsKey(t)) localList = (List) typeToLocals.get(t);
          else {
            localList = new ArrayList();
            typeToLocals.put(t, localList);
          }

          localList.add(local);
        }
      }

      // Print locals
      {
        Iterator typeIt = typeToLocals.keySet().iterator();

        while (typeIt.hasNext()) {
          Type type = (Type) typeIt.next();

          List localList = (List) typeToLocals.get(type);
          Object[] locals = localList.toArray();
          up.type(type);
          up.literal(" ");

          for (int k = 0; k < locals.length; k++) {
            if (k != 0) up.literal(", ");

            up.local((Local) locals[k]);
          }

          up.literal(";");
          up.newline();
        }
      }

      if (!typeToLocals.isEmpty()) {
        up.newline();
      }
    }
  }
Exemplo n.º 2
0
  /**
   * Prints out the method corresponding to b Body, (declaration and body), in the textual format
   * corresponding to the IR used to encode b body.
   *
   * @param out a PrintWriter instance to print to.
   */
  public void printTo(Body b, PrintWriter out) {
    b.validate();

    boolean isPrecise = !useAbbreviations();

    String decl = b.getMethod().getDeclaration();

    out.println("    " + decl);
    // incJimpleLnNum();

    // only print tags if not printing attributes in a file
    if (!addJimpleLn()) {
      /*for( Iterator tIt = b.getMethod().getTags().iterator(); tIt.hasNext(); ) {    final Tag t = (Tag) tIt.next();
          out.println(t);
          incJimpleLnNum();

      }*/
    }

    if (addJimpleLn()) {
      setJimpleLnNum(addJimpleLnTags(getJimpleLnNum(), b.getMethod()));
      // G.v().out.println("added jimple ln tag for method: "+b.getMethod().toString()+"
      // "+b.getMethod().getDeclaringClass().getName());
    }

    out.println("    {");
    incJimpleLnNum();

    UnitGraph unitGraph = new soot.toolkits.graph.BriefUnitGraph(b);

    LabeledUnitPrinter up;
    if (isPrecise) up = new NormalUnitPrinter(b);
    else up = new BriefUnitPrinter(b);

    if (addJimpleLn()) {
      up.setPositionTagger(new AttributesUnitPrinter(getJimpleLnNum()));
    }

    printLocalsInBody(b, up);

    printStatementsInBody(b, out, up, unitGraph);

    out.println("    }");
    incJimpleLnNum();
  }
Exemplo n.º 3
0
  protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
    initialize(options);
    SootMethod meth = b.getMethod();

    if ((methodsToPrint == null)
        || (meth.getDeclaringClass().getName() == methodsToPrint.get(meth.getName()))) {
      Body body = ir.getBody((JimpleBody) b);
      print_cfg(body);
    }
  }
Exemplo n.º 4
0
  protected void print_cfg(Body body) {
    DirectedGraph<Unit> graph = graphtype.buildGraph(body);
    DotGraph canvas = graphtype.drawGraph(drawer, graph, body);

    String methodname = body.getMethod().getSubSignature();
    String filename = soot.SourceLocator.v().getOutputDir();
    if (filename.length() > 0) {
      filename = filename + java.io.File.separator;
    }
    filename =
        filename + methodname.replace(java.io.File.separatorChar, '.') + DotGraph.DOT_EXTENSION;

    G.v().out.println("Generate dot file in " + filename);
    canvas.plot(filename);
  }
  public FaintVariableAnalysis(Body body) {

    Chain<Local> locals = body.getLocals();

    allVariables = new CollectionFlowUniverse<Local>(locals);

    universalSet = new ArrayPackedSet(allVariables);

    for (Local l : locals) universalSet.add(l);

    useSetMap = new HashMap<Unit, BoundedFlowSet>();
    defSetMap = new HashMap<Unit, BoundedFlowSet>();

    UnitGraph graph = new BriefUnitGraph(body);
    for (Unit u : graph) {

      BoundedFlowSet defSet = new ArrayPackedSet(allVariables);
      BoundedFlowSet useSet = new ArrayPackedSet(allVariables);

      for (ValueBox v : u.getDefBoxes()) {
        // Only do this for locals. We're not going to even try to handle anything
        // other than locals.
        if (v.getValue() instanceof Local) {
          defSet.add(v.getValue());
        }
      }
      for (ValueBox v : u.getUseBoxes()) {
        // Only do this for locals. We're not going to even try to handle anything
        // other than locals.
        if (v.getValue() instanceof Local) {
          useSet.add(v.getValue());
        }
      }

      defSetMap.put(u, defSet);
      useSetMap.put(u, useSet);
    }
  }
Exemplo n.º 6
0
  /**
   * Constructs a graph for the units found in the provided Body instance. Each node in the graph
   * corresponds to a unit. The edges are derived from the control flow.
   *
   * @param body The underlying body we want to make a graph for.
   * @param addExceptionEdges If true then the control flow edges associated with exceptions are
   *     added.
   * @param dontAddEdgeFromStmtBeforeAreaOfProtectionToCatchBlock This was added for Dava. If true,
   *     edges are not added from statement before area of protection to catch. If false, edges ARE
   *     added. For Dava, it should be true. For flow analyses, it should be false.
   * @param Hierarchy Using class hierarchy analysis to find the run method of started thread
   * @param PointsToAnalysis Using point to analysis (SPARK package) to improve the precision of
   *     results
   */
  public PegGraph(
      CallGraph callGraph,
      Hierarchy hierarchy,
      PAG pag,
      Set methodsNeedingInlining,
      Set allocNodes,
      List<List> inlineSites,
      Map<SootMethod, String> synchObj,
      Set multiRunAllocNodes,
      Map<AllocNode, String> allocNodeToObj,
      Body unitBody,
      String threadName,
      SootMethod sm,
      boolean addExceEdge,
      boolean dontAddEdgeFromStmtBeforeAreaOfProtectionToCatchBlock) {
    this.allocNodeToObj = allocNodeToObj;
    this.multiRunAllocNodes = multiRunAllocNodes;
    this.synchObj = synchObj;
    this.inlineSites = inlineSites;
    this.allocNodes = allocNodes;
    this.methodsNeedingInlining = methodsNeedingInlining;
    logFile = new File("log.txt");
    try {
      fileWriter = new FileWriter(logFile);
    } catch (IOException io) {
      System.err.println("Errors occur during create FileWriter !");
      //			throw io;
    }

    body = unitBody;
    synch = new HashSet<List>();
    exceHandlers = new HashSet<Unit>();
    needInlining = true;
    monitorObjs = new HashSet<Object>();
    startToBeginNodes = new HashMap();
    unitChain = body.getUnits();
    int size = unitChain.size();
    // initial unitToSuccs, unitToPreds, unitToPegMap, and startToThread
    unitToSuccs = new HashMap(size * 2 + 1, 0.7f);
    unitToPreds = new HashMap(size * 2 + 1, 0.7f);
    // unitToPegMap is the map of a chain to its corresponding (cfg node --> peg node ) map.
    unitToPegMap = new HashMap(size * 2 + 1, 0.7f);
    startToThread = new HashMap(size * 2 + 1, 0.7f);
    startToAllocNodes = new HashMap(size * 2 + 1, 0.7f);
    waitingNodes = new HashMap<String, FlowSet>(size * 2 + 1, 0.7f);
    joinStmtToThread = new HashMap<JPegStmt, Chain>();
    threadNo = new HashMap();
    threadNameToStart = new HashMap();
    this.allocNodeToObj = new HashMap<AllocNode, String>(size * 2 + 1, 0.7f);
    allocNodeToThread = new HashMap<AllocNode, PegChain>(size * 2 + 1, 0.7f);
    notifyAll = new HashMap<String, Set<JPegStmt>>(size * 2 + 1, 0.7f);

    methodsNeedingInlining = new HashSet();
    allNodes = new ArraySparseSet();
    canNotBeCompacted = new HashSet();
    threadAllocSites = new HashSet();
    specialJoin = new HashSet<JPegStmt>();
    //       if(Main.isVerbose)
    //   System.out.println("     Constructing PegGraph...");

    // if(Main.isProfilingOptimization)
    //   Main.graphTimer.start();
    // make a peg for debug
    /*
    mainPegChain = new HashChain();
    specialTreatment1();
    */
    // end make a peg

    UnitGraph mainUnitGraph = new CompleteUnitGraph(body);
    //	mainPegChain = new HashChain();
    mainPegChain =
        new PegChain(
            callGraph,
            hierarchy,
            pag,
            threadAllocSites,
            methodsNeedingInlining,
            allocNodes,
            inlineSites,
            synchObj,
            multiRunAllocNodes,
            allocNodeToObj,
            body,
            sm,
            threadName,
            true,
            this);

    // testPegChain();

    //		System.out.println("finish building chain");
    // testStartToThread();
    // buildSuccessor(mainUnitGraph, mainPegChain,addExceptionEdges);
    //	buildSuccessorForExtendingMethod(mainPegChain);
    // testSet(exceHandlers, "exceHandlers");
    buildSuccessor(mainPegChain);
    // System.out.println("finish building successors");
    // unmodifiableSuccs(mainPegChain);
    // testUnitToSucc );
    buildPredecessor(mainPegChain);
    // System.out.println("finish building predcessors");
    // unmodifiablePreds(mainPegChain);
    // testSynch();
    addMonitorStmt();
    addTag();
    //	System.out.println(this.toString());
    buildHeadsAndTails();

    // testIterator();
    // testWaitingNodes();

    //	System.out.println("finish building heads and tails");

    // testSet(canNotBeCompacted, "canNotBeCompacted");
    //	computeEdgeAndThreadNo();
    //	testExtendingPoints();
    //	testUnitToSucc();

    // testPegChain();
    /*	if (print) {
    PegToDotFile printer1 = new PegToDotFile(this, false, sm.getName());
    }
    */
    try {
      fileWriter.flush();
      fileWriter.close();
    } catch (IOException io) {
      System.err.println("Errors occur during close file  " + logFile.getName());
      //        throw io;
    }
    // System.out.println("==threadAllocaSits==\n"+threadAllocSites.toString());

  }
Exemplo n.º 7
0
  /** Prints the given <code>JimpleBody</code> to the specified <code>PrintWriter</code>. */
  private void printStatementsInBody(
      Body body, java.io.PrintWriter out, LabeledUnitPrinter up, UnitGraph unitGraph) {
    Chain units = body.getUnits();
    Iterator unitIt = units.iterator();
    Unit currentStmt = null, previousStmt;

    while (unitIt.hasNext()) {

      previousStmt = currentStmt;
      currentStmt = (Unit) unitIt.next();

      // Print appropriate header.
      {
        // Put an empty line if the previous node was a branch node, the current node is a join node
        //   or the previous statement does not have body statement as a successor, or if
        //   body statement has a label on it

        if (currentStmt != units.getFirst()) {
          if (unitGraph.getSuccsOf(previousStmt).size() != 1
              || unitGraph.getPredsOf(currentStmt).size() != 1
              || up.labels().containsKey(currentStmt)) {
            up.newline();
          } else {
            // Or if the previous node does not have body statement as a successor.

            List succs = unitGraph.getSuccsOf(previousStmt);

            if (succs.get(0) != currentStmt) {
              up.newline();
            }
          }
        }

        if (up.labels().containsKey(currentStmt)) {
          up.unitRef(currentStmt, true);
          up.literal(":");
          up.newline();
        }

        if (up.references().containsKey(currentStmt)) {
          up.unitRef(currentStmt, false);
        }
      }

      up.startUnit(currentStmt);
      currentStmt.toString(up);
      up.endUnit(currentStmt);

      up.literal(";");
      up.newline();

      // only print them if not generating attributes files
      // because they mess up line number
      // if (!addJimpleLn()) {
      if (Options.v().print_tags_in_output()) {
        Iterator tagIterator = currentStmt.getTags().iterator();
        while (tagIterator.hasNext()) {
          Tag t = (Tag) tagIterator.next();
          up.noIndent();
          up.literal("/*");
          up.literal(t.toString());
          up.literal("*/");
          up.newline();
        }
        /*Iterator udIt = currentStmt.getUseAndDefBoxes().iterator();
        while (udIt.hasNext()) {
            ValueBox temp = (ValueBox)udIt.next();
            Iterator vbtags = temp.getTags().iterator();
            while (vbtags.hasNext()) {
                Tag t = (Tag) vbtags.next();
                up.noIndent();
                up.literal("VB Tag: "+t.toString());
                up.newline();
            }
        }*/
      }
    }

    out.print(up.toString());
    if (addJimpleLn()) {
      setJimpleLnNum(up.getPositionTagger().getEndLn());
    }

    // Print out exceptions
    {
      Iterator trapIt = body.getTraps().iterator();

      if (trapIt.hasNext()) {
        out.println();
        incJimpleLnNum();
      }

      while (trapIt.hasNext()) {
        Trap trap = (Trap) trapIt.next();

        out.println(
            "        catch "
                + Scene.v().quotedNameOf(trap.getException().getName())
                + " from "
                + up.labels().get(trap.getBeginUnit())
                + " to "
                + up.labels().get(trap.getEndUnit())
                + " with "
                + up.labels().get(trap.getHandlerUnit())
                + ";");

        incJimpleLnNum();
      }
    }
  }