Exemplo n.º 1
0
  /**
   * Utility method used in the construction of {@link UnitGraph}s, to be called only after the
   * unitToPreds and unitToSuccs maps have been built.
   *
   * <p><code>UnitGraph</code> provides an implementation of <code>buildHeadsAndTails()</code> which
   * defines the graph's set of heads to include the first {@link Unit} in the graph's body,
   * together with any other <tt>Unit</tt> which has no predecessors. It defines the graph's set of
   * tails to include all <tt>Unit</tt>s with no successors. Subclasses of <code>UnitGraph</code>
   * may override this method to change the criteria for classifying a node as a head or tail.
   */
  protected void buildHeadsAndTails() {
    List tailList = new ArrayList();
    List headList = new ArrayList();

    for (Iterator unitIt = unitChain.iterator(); unitIt.hasNext(); ) {
      Unit s = (Unit) unitIt.next();
      List succs = (List) unitToSuccs.get(s);
      if (succs.size() == 0) {
        tailList.add(s);
      }
      List preds = (List) unitToPreds.get(s);
      if (preds.size() == 0) {
        headList.add(s);
      }
    }

    // Add the first Unit, even if it is the target of
    // a branch.
    Unit entryPoint = (Unit) unitChain.getFirst();
    if (!headList.contains(entryPoint)) {
      headList.add(entryPoint);
    }

    tails = Collections.unmodifiableList(tailList);
    heads = Collections.unmodifiableList(headList);
  }
Exemplo n.º 2
0
  protected void testPegChain(Chain chain) {
    System.out.println("******** chain********");
    Iterator it = chain.iterator();
    while (it.hasNext()) {
      /*Object o = it.next();
      System.out.println(o);
      if (!(o instanceof JPegStmt))  System.out.println("not instanceof JPegStmt: "+o);
      JPegStmt s = (JPegStmt)o;
      */
      JPegStmt stmt = (JPegStmt) it.next();
      System.out.println(stmt.toString());
      /*if (stmt.getName().equals("start")){

      System.out.println("find start method in : " + stmt.toString() );
      List list =(List)startToThread.get(stmt);
      Iterator chainIt = list.iterator();
      while (chainIt.hasNext()){
      Chain chain = (Chain)chainIt.next();
      Iterator subit = chain.iterator();
      while (subit.hasNext()){
      System.out.println("**" + ((JPegStmt)subit.next()).toString());
      }
      }
      System.out.println("$$$$$$returing to main chain");
      }
      */
    }
  }
Exemplo n.º 3
0
 /** Returns index of local in body, or negative value if not found. */
 public static int getIndexOfLocal(Local l, Body b) {
   int i = 0;
   Chain locals = b.getLocals();
   for (Iterator itLoc = locals.iterator(); itLoc.hasNext(); ) {
     if (l == (Local) itLoc.next()) return i;
     ++i;
   }
   return Integer.MIN_VALUE;
 }
  /**
   * Make sure that all invoke special targets are cloned into the class from ancestors. This might
   * mean that we have to clone hidden methods, and change their names. So clone them in, and update
   * the clone to original map, and update the invoke special Also, this will update invoke specials
   * that target methods cloned in previous call to above cloneReachableNonHiddenAncestorMethods()
   */
  private void cloneHiddenAncestorMethodsAndFixInvokeSpecial() {
    Set<SootClass> parents = SootUtils.getParents(clazz);

    boolean debug = false; // (clazz.getName().contains("ResultDisplayer"));

    boolean cloneAdded = false;
    do {
      cloneAdded = false;
      for (SootMethod method : clazz.getMethods()) {

        if (method.isAbstract() || method.isPhantom() || !method.isConcrete()) continue;

        if (debug) System.out.println(method);

        Body body = null;
        try {
          body = method.retrieveActiveBody();
        } catch (Exception ex) {
          logger.info("Exception retrieving method body {}", ex);
          continue;
        }

        StmtBody stmtBody = (StmtBody) body;

        Chain units = stmtBody.getUnits();
        Iterator stmtIt = units.iterator();

        while (stmtIt.hasNext()) {
          Stmt stmt = (Stmt) stmtIt.next();

          if (stmt.containsInvokeExpr() && stmt.getInvokeExpr() instanceof SpecialInvokeExpr) {
            SpecialInvokeExpr si = (SpecialInvokeExpr) stmt.getInvokeExpr();

            SootMethod target = resolveSpecialInvokeTarget(si); // si.getMethod();

            if (debug) System.out.printf("\t%s %s", si, target);

            if (clonedToOriginal.values().contains(target)) {
              // found target of invoke special, and it has been cloned, so change the invoke
              // special
              SootMethod cloneOfTarget = clonedToOriginal.inverse().get(target);
              si.setMethodRef(cloneOfTarget.makeRef());
              if (debug) System.out.println("\tChange ref " + cloneOfTarget);
            } else if (parents.contains(target.getDeclaringClass())) {
              // target has not been cloned, but should be cloned, so clone it and change ref of
              // invoke
              String name = target.getName() + CLONED_METHOD_SUFFIX + (cloned_method_id++);
              SootMethod clonedMethod = cloneMethod(target, name);
              si.setMethodRef(clonedMethod.makeRef());
              cloneAdded = true;
              if (debug) System.out.println("\tClone and Change ref " + clonedMethod);
            }
          }
        }
      }
    } while (cloneAdded);
  }
Exemplo n.º 5
0
  /**
   * Utility method for <tt>UnitGraph</tt> constructors. It computes the edges corresponding to
   * unexceptional control flow.
   *
   * @param unitToSuccs A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is
   *     an ``out parameter''; callers must pass an empty {@link Map}.
   *     <tt>buildUnexceptionalEdges</tt> will add a mapping for every <tt>Unit</tt> in the body to
   *     a list of its unexceptional successors.
   * @param unitToPreds A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is
   *     an ``out parameter''; callers must pass an empty {@link Map}.
   *     <tt>buildUnexceptionalEdges</tt> will add a mapping for every <tt>Unit</tt> in the body to
   *     a list of its unexceptional predecessors.
   */
  protected void buildUnexceptionalEdges(Map unitToSuccs, Map unitToPreds) {

    // Initialize the predecessor sets to empty
    for (Iterator unitIt = unitChain.iterator(); unitIt.hasNext(); ) {
      unitToPreds.put(unitIt.next(), new ArrayList());
    }

    Iterator unitIt = unitChain.iterator();
    Unit currentUnit, nextUnit;

    nextUnit = unitIt.hasNext() ? (Unit) unitIt.next() : null;

    while (nextUnit != null) {
      currentUnit = nextUnit;
      nextUnit = unitIt.hasNext() ? (Unit) unitIt.next() : null;

      List successors = new ArrayList();

      if (currentUnit.fallsThrough()) {
        // Add the next unit as the successor
        if (nextUnit != null) {
          successors.add(nextUnit);
          ((List) unitToPreds.get(nextUnit)).add(currentUnit);
        }
      }

      if (currentUnit.branches()) {
        for (Iterator targetIt = currentUnit.getUnitBoxes().iterator(); targetIt.hasNext(); ) {
          Unit target = ((UnitBox) targetIt.next()).getUnit();
          // Arbitrary bytecode can branch to the same
          // target it falls through to, so we screen for duplicates:
          if (!successors.contains(target)) {
            successors.add(target);
            ((List) unitToPreds.get(target)).add(currentUnit);
          }
        }
      }

      // Store away successors
      unitToSuccs.put(currentUnit, successors);
    }
  }
Exemplo n.º 6
0
 public String toString() {
   Iterator it = unitChain.iterator();
   StringBuffer buf = new StringBuffer();
   while (it.hasNext()) {
     Unit u = (Unit) it.next();
     buf.append("// preds: " + getPredsOf(u) + "\n");
     buf.append(u.toString() + '\n');
     buf.append("// succs " + getSuccsOf(u) + "\n");
   }
   return buf.toString();
 }
Exemplo n.º 7
0
  /**
   * Utility method that produces a new map from the {@link Unit}s of this graph's body to the union
   * of the values stored in the two argument {@link Map}s, used to combine the maps of exceptional
   * and unexceptional predecessors and successors into maps of all predecessors and successors. The
   * values stored in both argument maps must be {@link List}s of {@link Unit}s, which are assumed
   * not to contain any duplicate <tt>Unit</tt>s.
   *
   * @param mapA The first map to be combined.
   * @param mapB The second map to be combined.
   */
  protected Map combineMapValues(Map mapA, Map mapB) {
    // The duplicate screen
    Map result = new HashMap(mapA.size() * 2 + 1, 0.7f);
    for (Iterator chainIt = unitChain.iterator(); chainIt.hasNext(); ) {
      Unit unit = (Unit) chainIt.next();
      List listA = (List) mapA.get(unit);
      if (listA == null) {
        listA = Collections.EMPTY_LIST;
      }
      List listB = (List) mapB.get(unit);
      if (listB == null) {
        listB = Collections.EMPTY_LIST;
      }

      int resultSize = listA.size() + listB.size();
      if (resultSize == 0) {
        result.put(unit, Collections.EMPTY_LIST);
      } else {
        List resultList = new ArrayList(resultSize);
        Iterator listIt = null;
        // As a minor optimization of the duplicate screening,
        // copy the longer list first.
        if (listA.size() >= listB.size()) {
          resultList.addAll(listA);
          listIt = listB.iterator();
        } else {
          resultList.addAll(listB);
          listIt = listA.iterator();
        }
        while (listIt.hasNext()) {
          Object element = listIt.next();
          // It is possible for there to be both an exceptional
          // and an unexceptional edge connecting two Units
          // (though probably not in a class generated by
          // javac), so we need to screen for duplicates. On the
          // other hand, we expect most of these lists to have
          // only one or two elements, so it doesn't seem worth
          // the cost to build a Set to do the screening.
          if (!resultList.contains(element)) {
            resultList.add(element);
          }
        }
        result.put(unit, Collections.unmodifiableList(resultList));
      }
    }
    return result;
  }
Exemplo n.º 8
0
  protected void internalTransform(Body body, String phaseName, Map options) {
    if (Options.v().verbose())
      G.v().out.println("[" + body.getMethod().getName() + "] Tightening trap boundaries...");

    Chain trapChain = body.getTraps();
    Chain unitChain = body.getUnits();
    if (trapChain.size() > 0) {
      ExceptionalUnitGraph graph = new ExceptionalUnitGraph(body);

      for (Iterator trapIt = trapChain.iterator(); trapIt.hasNext(); ) {
        Trap trap = (Trap) trapIt.next();
        Unit firstTrappedUnit = trap.getBeginUnit();
        Unit firstTrappedThrower = null;
        Unit firstUntrappedUnit = trap.getEndUnit();
        Unit lastTrappedUnit = (Unit) unitChain.getPredOf(firstUntrappedUnit);
        Unit lastTrappedThrower = null;
        for (Unit u = firstTrappedUnit;
            u != null && u != firstUntrappedUnit;
            u = (Unit) unitChain.getSuccOf(u)) {
          if (mightThrowTo(graph, u, trap)) {
            firstTrappedThrower = u;
            break;
          }
        }
        if (firstTrappedThrower != null) {
          for (Unit u = lastTrappedUnit; u != null; u = (Unit) unitChain.getPredOf(u)) {
            if (mightThrowTo(graph, u, trap)) {
              lastTrappedThrower = u;
              break;
            }
          }
        }
        if (firstTrappedThrower != null && firstTrappedUnit != firstTrappedThrower) {
          trap.setBeginUnit(firstTrappedThrower);
        }
        if (lastTrappedThrower == null) {
          lastTrappedThrower = firstTrappedUnit;
        }
        if (lastTrappedUnit != lastTrappedThrower) {
          trap.setEndUnit((Unit) unitChain.getSuccOf(lastTrappedThrower));
        }
      }
    }
  }
Exemplo n.º 9
0
  private void buildHeadsAndTails() {

    List tailList = new ArrayList();
    List headList = new ArrayList();

    // Build the sets
    {
      Iterator unitIt = mainPegChain.iterator();

      while (unitIt.hasNext()) {
        JPegStmt s = (JPegStmt) unitIt.next();

        List succs = unitToSuccs.get(s);
        if (succs.size() == 0) tailList.add(s);
        if (!unitToPreds.containsKey(s)) {
          System.err.println("unitToPreds does not contain key: " + s);
          System.exit(1);
        }
        List preds = unitToPreds.get(s);
        if (preds.size() == 0) headList.add(s);
        // System.out.println("head is:");
      }
    }
    tails = (List) tailList;
    heads = (List) headList;
    //	tails = Collections.unmodifiableList(tailList);
    // heads = Collections.unmodifiableList(headList);

    Iterator tmpIt = heads.iterator();

    while (tmpIt.hasNext()) {
      Object temp = tmpIt.next();
      // System.out.println(temp);
    }

    buildPredecessor(mainPegChain);
  }
Exemplo n.º 10
0
 public Iterator iterator() {
   return unitChain.iterator();
 }
Exemplo n.º 11
0
  /** Constructs a hierarchy from the current scene. */
  public Hierarchy() {
    this.sc = Scene.v();
    state = sc.getState();

    // Well, this used to be describable by 'Duh'.
    // Construct the subclasses hierarchy and the subinterfaces hierarchy.
    {
      Chain allClasses = sc.getClasses();

      classToSubclasses = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f);
      interfaceToSubinterfaces =
          new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f);

      classToDirSubclasses = new HashMap<SootClass, List>(allClasses.size() * 2 + 1, 0.7f);
      interfaceToDirSubinterfaces = new HashMap<SootClass, List>(allClasses.size() * 2 + 1, 0.7f);
      interfaceToDirImplementers = new HashMap<SootClass, List>(allClasses.size() * 2 + 1, 0.7f);

      Iterator classesIt = allClasses.iterator();
      while (classesIt.hasNext()) {
        SootClass c = (SootClass) classesIt.next();
        if (c.resolvingLevel() < SootClass.HIERARCHY) continue;

        if (c.isInterface()) {
          interfaceToDirSubinterfaces.put(c, new ArrayList());
          interfaceToDirImplementers.put(c, new ArrayList());
        } else classToDirSubclasses.put(c, new ArrayList());
      }

      classesIt = allClasses.iterator();
      while (classesIt.hasNext()) {
        SootClass c = (SootClass) classesIt.next();
        if (c.resolvingLevel() < SootClass.HIERARCHY) continue;

        if (c.hasSuperclass()) {
          if (c.isInterface()) {
            Iterator subIt = c.getInterfaces().iterator();

            while (subIt.hasNext()) {
              SootClass i = (SootClass) subIt.next();
              if (c.resolvingLevel() < SootClass.HIERARCHY) continue;
              List<SootClass> l = interfaceToDirSubinterfaces.get(i);
              l.add(c);
            }
          } else {
            List<SootClass> l = classToDirSubclasses.get(c.getSuperclass());
            l.add(c);

            Iterator subIt = c.getInterfaces().iterator();

            while (subIt.hasNext()) {
              SootClass i = (SootClass) subIt.next();
              if (c.resolvingLevel() < SootClass.HIERARCHY) continue;
              l = interfaceToDirImplementers.get(i);
              l.add(c);
            }
          }
        }
      }

      // Fill the directImplementers lists with subclasses.
      {
        classesIt = allClasses.iterator();
        while (classesIt.hasNext()) {
          SootClass c = (SootClass) classesIt.next();
          if (c.resolvingLevel() < SootClass.HIERARCHY) continue;
          if (c.isInterface()) {
            List<SootClass> imp = interfaceToDirImplementers.get(c);
            Set<SootClass> s = new ArraySet();

            Iterator<SootClass> impIt = imp.iterator();
            while (impIt.hasNext()) {
              SootClass c0 = impIt.next();
              if (c.resolvingLevel() < SootClass.HIERARCHY) continue;
              s.addAll(getSubclassesOfIncluding(c0));
            }

            imp.clear();
            imp.addAll(s);
          }
        }
      }

      classesIt = allClasses.iterator();
      while (classesIt.hasNext()) {
        SootClass c = (SootClass) classesIt.next();
        if (c.resolvingLevel() < SootClass.HIERARCHY) continue;

        if (c.isInterface()) {
          interfaceToDirSubinterfaces.put(
              c, Collections.unmodifiableList(interfaceToDirSubinterfaces.get(c)));
          interfaceToDirImplementers.put(
              c, Collections.unmodifiableList(interfaceToDirImplementers.get(c)));
        } else
          classToDirSubclasses.put(c, Collections.unmodifiableList(classToDirSubclasses.get(c)));
      }
    }
  }
Exemplo n.º 12
0
  void doWeave(
      SootMethod method,
      LocalGeneratorEx lg,
      AdviceApplication adviceappl,
      Residue residue,
      WeavingContext wc) {
    AdviceInliner.v().addShadowMethod(method);
    ShadowPoints shadowpoints = adviceappl.shadowmatch.sp;
    AbstractAdviceDecl advicedecl = adviceappl.advice;

    Body b = method.getActiveBody();
    Chain units = b.getUnits().getNonPatchingChain();

    // end of shadow
    Stmt endshadow = shadowpoints.getEnd();

    NopStmt nop2 = Jimple.v().newNopStmt();
    GotoStmt goto1 = Jimple.v().newGotoStmt(nop2);
    if (advicedecl instanceof CflowSetup) {
      Tagger.tagStmt(goto1, InstructionKindTag.CFLOW_EXIT);
    } else if (advicedecl instanceof PerCflowSetup) {
      Tagger.tagStmt(goto1, InstructionKindTag.PERCFLOW_EXIT);
    } else if (advicedecl instanceof DeclareSoft) {
      Tagger.tagStmt(goto1, InstructionKindTag.EXCEPTION_SOFTENER);
    } else if (advicedecl instanceof DeclareMessage) {
      Tagger.tagStmt(goto1, InstructionKindTag.DECLARE_MESSAGE);
    } else {
      Tagger.tagStmt(goto1, InstructionKindTag.AFTER_THROWING_HANDLER);
    }
    Tagger.tagStmt(goto1, new InstructionSourceTag(advicedecl.sourceId));
    Tagger.tagStmt(goto1, new InstructionShadowTag(adviceappl.shadowmatch.shadowId));
    units.insertBefore(nop2, endshadow);
    units.insertBefore(goto1, nop2);

    // have ...
    //    goto1:      goto nop2;
    //    nop2:       nop;
    //    endshadow:  nop;

    RefType catchType = getCatchType();
    Local exception = lg.generateLocal(catchType, "exception");
    bindException(wc, advicedecl, exception);

    CaughtExceptionRef exceptRef = Jimple.v().newCaughtExceptionRef();
    IdentityStmt idStmt = Jimple.v().newIdentityStmt(exception, exceptRef);
    units.insertAfter(idStmt, goto1);

    ThrowStmt throwStmt = Jimple.v().newThrowStmt(exception);
    throwStmt.addTag(new ThrowCreatedByCompilerTag());

    if (advicedecl instanceof CflowSetup) {
      Tagger.tagStmt(throwStmt, InstructionKindTag.CFLOW_EXIT);
    } else if (advicedecl instanceof PerCflowSetup) {
      Tagger.tagStmt(throwStmt, InstructionKindTag.PERCFLOW_EXIT);
    } else if (advicedecl instanceof DeclareSoft) {
      Tagger.tagStmt(throwStmt, InstructionKindTag.EXCEPTION_SOFTENER);
    } else if (advicedecl instanceof DeclareMessage) {
      Tagger.tagStmt(throwStmt, InstructionKindTag.DECLARE_MESSAGE);
    } else {
      Tagger.tagStmt(throwStmt, InstructionKindTag.AFTER_THROWING_HANDLER);
    }
    Tagger.tagStmt(throwStmt, new InstructionSourceTag(advicedecl.sourceId));
    Tagger.tagStmt(throwStmt, new InstructionShadowTag(adviceappl.shadowmatch.shadowId));

    // store shadow/source tag for this residue in weaving context
    if (advicedecl instanceof CflowSetup) {
      wc.setKindTag(InstructionKindTag.CFLOW_TEST);
    }
    if (advicedecl instanceof PerCflowSetup) {
      wc.setKindTag(InstructionKindTag.CFLOW_TEST);
    }
    wc.setShadowTag(new InstructionShadowTag(adviceappl.shadowmatch.shadowId));
    wc.setSourceTag(new InstructionSourceTag(adviceappl.advice.sourceId));

    Stmt endresidue = residue.codeGen(method, lg, units, idStmt, throwStmt, true, wc);

    // have ...
    //    java.lang.Exception exception;
    //
    //    goto1:      goto nop2;
    //    idStmt:     exception := @caughtexception
    //    nop2:       nop;
    //    endshadow:  nop;

    units.insertAfter(throwStmt, endresidue);

    Chain invokestmts = advicedecl.makeAdviceExecutionStmts(adviceappl, lg, wc);

    for (Iterator stmtlist = invokestmts.iterator(); stmtlist.hasNext(); ) {
      Stmt nextstmt = (Stmt) stmtlist.next();
      units.insertBefore(nextstmt, throwStmt);
    }

    if (method.getName().equals("<clinit>"))
    // have to handle case of ExceptionInInitialzerError
    { //  if (exception instanceof java.lang.ExceptionInIntializerError)
      //     throw (exception);
      debug("Adding extra check in clinit");

      Local isInitError = lg.generateLocal(soot.BooleanType.v(), "isInitError");

      Stmt assignbool =
          Jimple.v()
              .newAssignStmt(
                  isInitError,
                  Jimple.v()
                      .newInstanceOfExpr(
                          exception, RefType.v("java.lang.ExceptionInInitializerError")));

      Stmt ifstmt =
          Jimple.v().newIfStmt(Jimple.v().newNeExpr(isInitError, IntConstant.v(0)), throwStmt);

      //	     ThrowStmt throwInitError = Jimple.v().newThrowStmt(exception);

      //	     units.insertAfter(throwInitError, idStmt);
      units.insertAfter(ifstmt, idStmt);
      units.insertAfter(assignbool, idStmt);
    }

    Stmt beginshadow = shadowpoints.getBegin();
    Stmt begincode = (Stmt) units.getSuccOf(beginshadow);

    // have ...
    //    java.lang.Exception exception;
    //    <AspectType> theAspect;
    //
    //    beginshadow:   nop
    //    begincode:     <some statement>
    //       ....        <stuff in between>
    //    goto1:         goto nop2;
    //    idStmt:        exception := @caughtexception;
    //    assignStmt:    theAspect = new AspectOf();
    //             .... invoke statements ....
    //    throwStmt:     throw exception;
    //    nop2:          nop;
    //    endshadow:     nop;

    Chain traps = b.getTraps();
    Trap t = traps.size() > 0 ? (Trap) traps.getFirst() : null;

    // assume no exception ranges overlap with this one; make sure
    // we go after any that would be enclosed within this one.
    while (t != null
        && (units.follows(t.getBeginUnit(), begincode)
            || (t.getBeginUnit() == begincode && units.follows(idStmt, t.getEndUnit()))))
      t = (Trap) traps.getSuccOf(t);

    Trap newt = Jimple.v().newTrap(catchType.getSootClass(), begincode, idStmt, idStmt);

    if (t == null) traps.addLast(newt);
    else traps.insertBefore(newt, t);

    //  added
    //     catch java.lang.Throwable
    //         from begincode upto idStmt handlewith idStmt

  } // method doWeave
Exemplo n.º 13
0
  /*
  private void deleteExitToException(){
  Iterator it = iterator();
  while (it.hasNext()){
  JPegStmt stmt = (JPegStmt)it.next();
  Unit unit = stmt.getUnit();
  UnitGraph unitGraph = stmt.getUnitGraph();
  if (unit instanceof ExitMonitorStmt){
  Iterator succIt = unitGraph.getSuccsOf(unit).iterator();
  while(succIt.next
  && exceHandlers.contains(un) ){
  System.out.println("====find it! unit: "+unit+"\n un: "+un);
  continue;
  }
  }
  }
  */
  private void buildPredecessor(Chain pegChain) {
    // System.out.println("==building predcessor===");

    // initialize the pred sets to empty
    {
      JPegStmt s = null;
      Iterator unitIt = pegChain.iterator();
      while (unitIt.hasNext()) {

        s = (JPegStmt) unitIt.next();

        unitToPreds.put(s, new ArrayList());
      }
    }
    //	System.out.println("==finish init of unitToPred===");
    {
      Iterator unitIt = pegChain.iterator();

      while (unitIt.hasNext()) {

        Object s = unitIt.next();
        //		System.out.println("s is: "+s);

        // Modify preds set for each successor for this statement
        if (unitToSuccs.containsKey(s)) {
          List succList = unitToSuccs.get(s);
          Iterator succIt = succList.iterator();
          //		    System.out.println("unitToSuccs contains "+s);
          //		    System.out.println("succList is: "+succList);
          while (succIt.hasNext()) {

            // Object successor =  succIt.next();
            JPegStmt successor = (JPegStmt) succIt.next();
            //			System.out.println("successor is: "+successor);
            List<Object> predList = unitToPreds.get(successor);
            //			System.out.println("predList is: "+predList);
            if (predList != null && !predList.contains(s)) {
              try {
                predList.add(s);
                /*
                Tag tag1 = (Tag)((JPegStmt)s).getTags().get(0);
                System.out.println("add "+tag1+" "+s+" to predListof");
                Tag tag2 = (Tag)((JPegStmt)successor).getTags().get(0);
                System.out.println(tag2+" "+successor);
                */
              } catch (NullPointerException e) {
                System.out.println(s + "successor: " + successor);
                throw e;
              }
              // if (((JPegStmt)successor).getName().equals("start")){
              if (successor instanceof StartStmt) {
                List runMethodChainList = startToThread.get(successor);
                if (runMethodChainList == null) {
                  throw new RuntimeException("null runmehtodchain: \n" + successor.getUnit());
                }
                Iterator possibleMethodIt = runMethodChainList.iterator();
                while (possibleMethodIt.hasNext()) {

                  Chain subChain = (Chain) possibleMethodIt.next();

                  buildPredecessor(subChain);
                }
              }
            } else {
              System.err.println("predlist of " + s + " is null");
              //							System.exit(1);
            }
            //			unitToPreds.put(successor, predList);

          }

        } else {
          System.err.println("unitToSuccs does not contains key" + s);
          System.exit(1);
        }
      }
    }
  }
Exemplo n.º 14
0
  private void buildSuccessor(Chain pegChain) {

    // Add regular successors
    {
      HashMap unitToPeg = (HashMap) unitToPegMap.get(pegChain);
      Iterator pegIt = pegChain.iterator();
      JPegStmt currentNode, nextNode;
      currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
      // June 19 add for begin node
      if (currentNode != null) {
        // System.out.println("currentNode: "+currentNode);
        // if the unit is "begin" node
        nextNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;

        if (currentNode.getName().equals("begin")) {
          List<JPegStmt> successors = new ArrayList<JPegStmt>();
          successors.add(nextNode);
          unitToSuccs.put(currentNode, successors);

          currentNode = nextNode;
        }
        // end June 19 add for begin node

        while (currentNode != null) {
          //		    System.out.println("currentNode: "+currentNode);
          /* If unitToSuccs contains currentNode, it is the point to inline methods,
           * we need not compute its successors again
           */

          if (unitToSuccs.containsKey(currentNode) && !currentNode.getName().equals("wait")) {
            currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
            continue;
          }
          List<JPegStmt> successors = new ArrayList<JPegStmt>();
          Unit unit = currentNode.getUnit();

          UnitGraph unitGraph = currentNode.getUnitGraph();
          List unitSucc = unitGraph.getSuccsOf(unit);
          Iterator succIt = unitSucc.iterator();
          while (succIt.hasNext()) {
            Unit un = (Unit) succIt.next();

            // Don't build the edge from "monitor exit" to exception handler

            if (unit instanceof ExitMonitorStmt && exceHandlers.contains(un)) {
              // System.out.println("====find it! unit: "+unit+"\n un: "+un);
              continue;
            } else if (unitToPeg.containsKey(un)) {
              JPegStmt pp = (JPegStmt) (unitToPeg.get(un));
              if (pp != null && !successors.contains(pp)) successors.add(pp);
            }
          } // end while

          if (currentNode.getName().equals("wait")) {
            while (!(currentNode.getName().equals("notified-entry"))) {
              currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
            }
            unitToSuccs.put(currentNode, successors);
            // System.out.println("put key: "+currentNode+" into unitToSucc");
          } else {
            unitToSuccs.put(currentNode, successors);
          }
          if (currentNode.getName().equals("start")) {

            //						System.out.println("-----build succ for start----");

            if (startToThread.containsKey(currentNode)) {
              List runMethodChainList = startToThread.get(currentNode);
              Iterator possibleMethodIt = runMethodChainList.iterator();
              while (possibleMethodIt.hasNext()) {

                Chain subChain = (Chain) possibleMethodIt.next();
                if (subChain != null) {
                  // System.out.println("build succ for subChain");
                  // buildSuccessor(subGraph, subChain, addExceptionEdges);
                  buildSuccessor(subChain);
                } else System.out.println("*********subgraph is null!!!");
              }
            }
          }

          currentNode = pegIt.hasNext() ? (JPegStmt) pegIt.next() : null;
        } // while

        // June 19 add for begin node
      }
      // end June 19 add for begin node
    }
  }
Exemplo n.º 15
0
 public Iterator mainIterator() {
   return mainPegChain.iterator();
 }
Exemplo n.º 16
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();
      }
    }
  }