org.objectweb.asm.tree.analysis.Analyzer Java Examples

The following examples show how to use org.objectweb.asm.tree.analysis.Analyzer. 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: CheckMethodAdapter.java    From JByteMod-Beta with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 * 
 * @param access
 *          the method's access flags.
 * @param name
 *          the method's name.
 * @param desc
 *          the method's descriptor (see {@link Type Type}).
 * @param cmv
 *          the method visitor to which this adapter must delegate calls.
 * @param labels
 *          a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(final int access, final String name, final String desc, final MethodVisitor cmv, final Map<Label, Integer> labels) {
  this(new MethodNode(Opcodes.ASM5, access, name, desc, null, null) {
    @Override
    public void visitEnd() {
      Analyzer<BasicValue> a = new Analyzer<BasicValue>(new BasicVerifier());
      try {
        a.analyze("dummy", this);
      } catch (Exception e) {
        if (e instanceof IndexOutOfBoundsException && maxLocals == 0 && maxStack == 0) {
          throw new RuntimeException("Data flow checking option requires valid, non zero maxLocals and maxStack values.");
        }
        e.printStackTrace();
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        CheckClassAdapter.printAnalyzerResult(this, a, pw);
        pw.close();
        throw new RuntimeException(e.getMessage() + ' ' + sw.toString());
      }
      accept(cmv);
    }
  }, labels);
  this.access = access;
}
 
Example #2
Source File: MethodUtils.java    From JByteMod-Beta with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void removeDeadCode(ClassNode cn, MethodNode mn) {
  Analyzer analyzer = new Analyzer(new BasicInterpreter());
  try {
    analyzer.analyze(cn.name, mn);
  } catch (AnalyzerException e) {
    ErrorDisplay.error("Could not analyze the code: " + e.getMessage());
    return;
  }
  Frame[] frames = analyzer.getFrames();
  AbstractInsnNode[] insns = mn.instructions.toArray();
  for (int i = 0; i < frames.length; i++) {
    AbstractInsnNode insn = insns[i];
    if (frames[i] == null && insn.getType() != AbstractInsnNode.LABEL) {
      mn.instructions.remove(insn);
      insns[i] = null;
    }
  }
}
 
Example #3
Source File: CheckClassAdapter.java    From Concurnas with MIT License 5 votes vote down vote up
static void printAnalyzerResult(
    final MethodNode method, final Analyzer<BasicValue> analyzer, final PrintWriter printWriter) {
  Textifier textifier = new Textifier();
  TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(textifier);

  printWriter.println(method.name + method.desc);
  for (int i = 0; i < method.instructions.size(); ++i) {
    method.instructions.get(i).accept(traceMethodVisitor);

    StringBuilder stringBuilder = new StringBuilder();
    Frame<BasicValue> frame = analyzer.getFrames()[i];
    if (frame == null) {
      stringBuilder.append('?');
    } else {
      for (int j = 0; j < frame.getLocals(); ++j) {
        stringBuilder.append(getUnqualifiedName(frame.getLocal(j).toString())).append(' ');
      }
      stringBuilder.append(" : ");
      for (int j = 0; j < frame.getStackSize(); ++j) {
        stringBuilder.append(getUnqualifiedName(frame.getStack(j).toString())).append(' ');
      }
    }
    while (stringBuilder.length() < method.maxStack + method.maxLocals + 1) {
      stringBuilder.append(' ');
    }
    printWriter.print(Integer.toString(i + 100000).substring(1));
    printWriter.print(
        " " + stringBuilder + " : " + textifier.text.get(textifier.text.size() - 1));
  }
  for (TryCatchBlockNode tryCatchBlock : method.tryCatchBlocks) {
    tryCatchBlock.accept(traceMethodVisitor);
    printWriter.print(" " + textifier.text.get(textifier.text.size() - 1));
  }
  printWriter.println();
}
 
Example #4
Source File: AsmTestUtils.java    From grappa with Apache License 2.0 5 votes vote down vote up
public static void verifyMethodIntegrity(final String ownerInternalName, final MethodNode method) {
    try {
        new Analyzer(new SimpleVerifier()).analyze(ownerInternalName, method);
    } catch (AnalyzerException e) {
        throw new RuntimeException(
                "Integrity error in method '" + method.name + "' of type '" + ownerInternalName + "': ", e);
    }
}
 
Example #5
Source File: ContinuableMethodNode.java    From tascalate-javaflow with Apache License 2.0 5 votes vote down vote up
@Override
public void visitEnd() {
    if (instructions.size() == 0 || labels.size() == 0) {
        accept(mv);
        return;
    }

    this.stackRecorderVar = maxLocals;
    try {
        moveNew();

        analyzer = new Analyzer(new FastClassVerifier(classHierarchy)) {
            @Override
            protected Frame newFrame(int nLocals, int nStack) {
                return new MonitoringFrame(nLocals, nStack);
            }

            @Override
            protected Frame newFrame(Frame src) {
                return new MonitoringFrame(src);
            }
        };

        analyzer.analyze(className, this);
        accept(new ContinuableMethodVisitor(this));

    } catch (AnalyzerException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #6
Source File: ContinuableMethodNode.java    From tascalate-javaflow with Apache License 2.0 5 votes vote down vote up
@Override
public void visitEnd() {
    if (instructions.size() == 0 || labels.size() == 0) {
        accept(mv);
        return;
    }

    this.stackRecorderVar = maxLocals;
    try {
        moveNew();

        analyzer = new Analyzer(new FastClassVerifier(classHierarchy)) {
            @Override
            protected Frame newFrame(int nLocals, int nStack) {
                return new MonitoringFrame(nLocals, nStack);
            }

            @Override
            protected Frame newFrame(Frame src) {
                return new MonitoringFrame(src);
            }
        };

        analyzer.analyze(className, this);
        accept(new ContinuableMethodVisitor(this));

    } catch (AnalyzerException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #7
Source File: ContinuableMethodNode.java    From tascalate-javaflow with Apache License 2.0 5 votes vote down vote up
@Override
public void visitEnd() {

    checkCallSites();

    if (instructions.size() == 0 || labels.size() == 0) {
        accept(mv);
        return;
    }

    this.stackRecorderVar = maxLocals;
    try {
        moveNew();

        analyzer = new Analyzer(new FastClassVerifier(classHierarchy)) {
            @Override
            protected Frame newFrame(int nLocals, int nStack) {
                return new MonitoringFrame(nLocals, nStack);
            }

            @Override
            protected Frame newFrame(Frame src) {
                return new MonitoringFrame(src);
            }
        };

        analyzer.analyze(className, this);
        accept(new ContinuableMethodVisitor(this));

    } catch (AnalyzerException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #8
Source File: CheckClassAdapter.java    From JReFrameworker with MIT License 5 votes vote down vote up
static void printAnalyzerResult(
    final MethodNode method, final Analyzer<BasicValue> analyzer, final PrintWriter printWriter) {
  Textifier textifier = new Textifier();
  TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(textifier);

  printWriter.println(method.name + method.desc);
  for (int i = 0; i < method.instructions.size(); ++i) {
    method.instructions.get(i).accept(traceMethodVisitor);

    StringBuilder stringBuilder = new StringBuilder();
    Frame<BasicValue> frame = analyzer.getFrames()[i];
    if (frame == null) {
      stringBuilder.append('?');
    } else {
      for (int j = 0; j < frame.getLocals(); ++j) {
        stringBuilder.append(getUnqualifiedName(frame.getLocal(j).toString())).append(' ');
      }
      stringBuilder.append(" : ");
      for (int j = 0; j < frame.getStackSize(); ++j) {
        stringBuilder.append(getUnqualifiedName(frame.getStack(j).toString())).append(' ');
      }
    }
    while (stringBuilder.length() < method.maxStack + method.maxLocals + 1) {
      stringBuilder.append(' ');
    }
    printWriter.print(Integer.toString(i + 100000).substring(1));
    printWriter.print(
        " " + stringBuilder + " : " + textifier.text.get(textifier.text.size() - 1));
  }
  for (TryCatchBlockNode tryCatchBlock : method.tryCatchBlocks) {
    tryCatchBlock.accept(traceMethodVisitor);
    printWriter.print(" " + textifier.text.get(textifier.text.size() - 1));
  }
  printWriter.println();
}
 
Example #9
Source File: CheckClassAdapter.java    From JReFrameworker with MIT License 5 votes vote down vote up
/**
 * Checks the given class.
 *
 * @param classReader the class to be checked.
 * @param loader a <code>ClassLoader</code> which will be used to load referenced classes. May be
 *     {@literal null}.
 * @param printResults whether to print the results of the bytecode verification.
 * @param printWriter where the results (or the stack trace in case of error) must be printed.
 */
public static void verify(
    final ClassReader classReader,
    final ClassLoader loader,
    final boolean printResults,
    final PrintWriter printWriter) {
  ClassNode classNode = new ClassNode();
  classReader.accept(
      new CheckClassAdapter(Opcodes.ASM7, classNode, false) {}, ClassReader.SKIP_DEBUG);

  Type syperType = classNode.superName == null ? null : Type.getObjectType(classNode.superName);
  List<MethodNode> methods = classNode.methods;

  List<Type> interfaces = new ArrayList<Type>();
  for (String interfaceName : classNode.interfaces) {
    interfaces.add(Type.getObjectType(interfaceName));
  }

  for (MethodNode method : methods) {
    SimpleVerifier verifier =
        new SimpleVerifier(
            Type.getObjectType(classNode.name),
            syperType,
            interfaces,
            (classNode.access & Opcodes.ACC_INTERFACE) != 0);
    Analyzer<BasicValue> analyzer = new Analyzer<BasicValue>(verifier);
    if (loader != null) {
      verifier.setClassLoader(loader);
    }
    try {
      analyzer.analyze(classNode.name, method);
    } catch (AnalyzerException e) {
      e.printStackTrace(printWriter);
    }
    if (printResults) {
      printAnalyzerResult(method, analyzer, printWriter);
    }
  }
  printWriter.flush();
}
 
Example #10
Source File: CheckClassAdapter.java    From JReFrameworker with MIT License 5 votes vote down vote up
static void printAnalyzerResult(
    final MethodNode method, final Analyzer<BasicValue> analyzer, final PrintWriter printWriter) {
  Textifier textifier = new Textifier();
  TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(textifier);

  printWriter.println(method.name + method.desc);
  for (int i = 0; i < method.instructions.size(); ++i) {
    method.instructions.get(i).accept(traceMethodVisitor);

    StringBuilder stringBuilder = new StringBuilder();
    Frame<BasicValue> frame = analyzer.getFrames()[i];
    if (frame == null) {
      stringBuilder.append('?');
    } else {
      for (int j = 0; j < frame.getLocals(); ++j) {
        stringBuilder.append(getUnqualifiedName(frame.getLocal(j).toString())).append(' ');
      }
      stringBuilder.append(" : ");
      for (int j = 0; j < frame.getStackSize(); ++j) {
        stringBuilder.append(getUnqualifiedName(frame.getStack(j).toString())).append(' ');
      }
    }
    while (stringBuilder.length() < method.maxStack + method.maxLocals + 1) {
      stringBuilder.append(' ');
    }
    printWriter.print(Integer.toString(i + 100000).substring(1));
    printWriter.print(
        " " + stringBuilder + " : " + textifier.text.get(textifier.text.size() - 1));
  }
  for (TryCatchBlockNode tryCatchBlock : method.tryCatchBlocks) {
    tryCatchBlock.accept(traceMethodVisitor);
    printWriter.print(" " + textifier.text.get(textifier.text.size() - 1));
  }
  printWriter.println();
}
 
Example #11
Source File: CheckClassAdapter.java    From JReFrameworker with MIT License 5 votes vote down vote up
/**
 * Checks the given class.
 *
 * @param classReader the class to be checked.
 * @param loader a <code>ClassLoader</code> which will be used to load referenced classes. May be
 *     {@literal null}.
 * @param printResults whether to print the results of the bytecode verification.
 * @param printWriter where the results (or the stack trace in case of error) must be printed.
 */
public static void verify(
    final ClassReader classReader,
    final ClassLoader loader,
    final boolean printResults,
    final PrintWriter printWriter) {
  ClassNode classNode = new ClassNode();
  classReader.accept(
      new CheckClassAdapter(Opcodes.ASM7, classNode, false) {}, ClassReader.SKIP_DEBUG);

  Type syperType = classNode.superName == null ? null : Type.getObjectType(classNode.superName);
  List<MethodNode> methods = classNode.methods;

  List<Type> interfaces = new ArrayList<Type>();
  for (String interfaceName : classNode.interfaces) {
    interfaces.add(Type.getObjectType(interfaceName));
  }

  for (MethodNode method : methods) {
    SimpleVerifier verifier =
        new SimpleVerifier(
            Type.getObjectType(classNode.name),
            syperType,
            interfaces,
            (classNode.access & Opcodes.ACC_INTERFACE) != 0);
    Analyzer<BasicValue> analyzer = new Analyzer<BasicValue>(verifier);
    if (loader != null) {
      verifier.setClassLoader(loader);
    }
    try {
      analyzer.analyze(classNode.name, method);
    } catch (AnalyzerException e) {
      e.printStackTrace(printWriter);
    }
    if (printResults) {
      printAnalyzerResult(method, analyzer, printWriter);
    }
  }
  printWriter.flush();
}
 
Example #12
Source File: CheckClassAdapter.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
static void printAnalyzerResult(MethodNode method, Analyzer<BasicValue> a, final PrintWriter pw) {
  Frame<BasicValue>[] frames = a.getFrames();
  Textifier t = new Textifier();
  TraceMethodVisitor mv = new TraceMethodVisitor(t);

  pw.println(method.name + method.desc);
  for (int j = 0; j < method.instructions.size(); ++j) {
    method.instructions.get(j).accept(mv);

    StringBuilder sb = new StringBuilder();
    Frame<BasicValue> f = frames[j];
    if (f == null) {
      sb.append('?');
    } else {
      for (int k = 0; k < f.getLocals(); ++k) {
        sb.append(getShortName(f.getLocal(k).toString())).append(' ');
      }
      sb.append(" : ");
      for (int k = 0; k < f.getStackSize(); ++k) {
        sb.append(getShortName(f.getStack(k).toString())).append(' ');
      }
    }
    while (sb.length() < method.maxStack + method.maxLocals + 1) {
      sb.append(' ');
    }
    pw.print(Integer.toString(j + 100000).substring(1));
    pw.print(" " + sb + " : " + t.text.get(t.text.size() - 1));
  }
  for (int j = 0; j < method.tryCatchBlocks.size(); ++j) {
    method.tryCatchBlocks.get(j).accept(mv);
    pw.print(" " + t.text.get(t.text.size() - 1));
  }
  pw.println();
}
 
Example #13
Source File: CheckClassAdapter.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks a given class.
 * 
 * @param cr
 *          a <code>ClassReader</code> that contains bytecode for the
 *          analysis.
 * @param loader
 *          a <code>ClassLoader</code> which will be used to load referenced
 *          classes. This is useful if you are verifiying multiple
 *          interdependent classes.
 * @param dump
 *          true if bytecode should be printed out not only when errors are
 *          found.
 * @param pw
 *          write where results going to be printed
 */
public static void verify(final ClassReader cr, final ClassLoader loader, final boolean dump, final PrintWriter pw) {
  ClassNode cn = new ClassNode();
  cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

  Type syperType = cn.superName == null ? null : Type.getObjectType(cn.superName);
  List<MethodNode> methods = cn.methods;

  List<Type> interfaces = new ArrayList<Type>();
  for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
    interfaces.add(Type.getObjectType(i.next()));
  }

  for (int i = 0; i < methods.size(); ++i) {
    MethodNode method = methods.get(i);
    SimpleVerifier verifier = new SimpleVerifier(Type.getObjectType(cn.name), syperType, interfaces, (cn.access & Opcodes.ACC_INTERFACE) != 0);
    Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
    if (loader != null) {
      verifier.setClassLoader(loader);
    }
    try {
      a.analyze(cn.name, method);
      if (!dump) {
        continue;
      }
    } catch (Exception e) {
      e.printStackTrace(pw);
    }
    printAnalyzerResult(method, a, pw);
  }
  pw.flush();
}
 
Example #14
Source File: CheckClassAdapter.java    From Concurnas with MIT License 5 votes vote down vote up
/**
 * Checks the given class.
 *
 * @param classReader the class to be checked.
 * @param loader a <code>ClassLoader</code> which will be used to load referenced classes. May be
 *     {@literal null}.
 * @param printResults whether to print the results of the bytecode verification.
 * @param printWriter where the results (or the stack trace in case of error) must be printed.
 */
public static void verify(
    final ClassReader classReader,
    final ClassLoader loader,
    final boolean printResults,
    final PrintWriter printWriter) {
  ClassNode classNode = new ClassNode();
  classReader.accept(
      new CheckClassAdapter(Opcodes.ASM7, classNode, false) {}, ClassReader.SKIP_DEBUG);

  Type syperType = classNode.superName == null ? null : Type.getObjectType(classNode.superName);
  List<MethodNode> methods = classNode.methods;

  List<Type> interfaces = new ArrayList<>();
  for (String interfaceName : classNode.interfaces) {
    interfaces.add(Type.getObjectType(interfaceName));
  }

  for (MethodNode method : methods) {
    SimpleVerifier verifier =
        new SimpleVerifier(
            Type.getObjectType(classNode.name),
            syperType,
            interfaces,
            (classNode.access & Opcodes.ACC_INTERFACE) != 0);
    Analyzer<BasicValue> analyzer = new Analyzer<>(verifier);
    if (loader != null) {
      verifier.setClassLoader(loader);
    }
    try {
      analyzer.analyze(classNode.name, method);
    } catch (AnalyzerException e) {
      e.printStackTrace(printWriter);
    }
    if (printResults) {
      printAnalyzerResult(method, analyzer, printWriter);
    }
  }
  printWriter.flush();
}
 
Example #15
Source File: StringEncryptionTransformer.java    From deobfuscator with Apache License 2.0 4 votes vote down vote up
@Override 
  public boolean transform() throws Throwable {
  	DelegatingProvider provider = new DelegatingProvider();
      provider.register(new JVMMethodProvider());
      provider.register(new JVMComparisonProvider());
      provider.register(new MappedMethodProvider(classes));
      provider.register(new MappedFieldProvider());

      AtomicInteger count = new AtomicInteger();
      Set<MethodNode> decryptor = new HashSet<>();

      System.out.println("[Smoke] [StringEncryptionTransformer] Starting");

      for(ClassNode classNode : classes.values())
          for(MethodNode method : classNode.methods)
          {
          	InstructionModifier modifier = new InstructionModifier();
              Frame<SourceValue>[] frames;
              try 
              {
                  frames = new Analyzer<>(new SourceInterpreter()).analyze(classNode.name, method);
              }catch(AnalyzerException e) 
              {
                  oops("unexpected analyzer exception", e);
                  continue;
              }

              for(AbstractInsnNode ain : TransformerHelper.instructionIterator(method))
              	if(ain instanceof MethodInsnNode) 
              	{
                      MethodInsnNode m = (MethodInsnNode)ain;
                      String strCl = m.owner;
                      if(m.desc.equals("(Ljava/lang/String;I)Ljava/lang/String;")) 
                      {
                      	Frame<SourceValue> f = frames[method.instructions.indexOf(m)];
                      	if(f.getStack(f.getStackSize() - 2).insns.size() != 1
                      		|| f.getStack(f.getStackSize() - 1).insns.size() != 1)
                      		continue;
                      	AbstractInsnNode a1 = f.getStack(f.getStackSize() - 2).insns.iterator().next();
					AbstractInsnNode a2 = f.getStack(f.getStackSize() - 1).insns.iterator().next();
					if(a1.getOpcode() != Opcodes.LDC || !Utils.isInteger(a2))
						continue;
					Object obfString = ((LdcInsnNode)a1).cst;
					int number = Utils.getIntValue(a2);
  						Context context = new Context(provider);
  						if(classes.containsKey(strCl)) 
  						{
  							ClassNode innerClassNode = classes.get(strCl);
  							MethodNode decrypterNode = innerClassNode.methods.stream().filter(mn -> mn.name.equals(m.name) && mn.desc.equals(m.desc)).findFirst().orElse(null);
  							if(isSmokeMethod(decrypterNode))
  							{
      							String value = MethodExecutor.execute(classNode, decrypterNode, Arrays.asList(JavaValue.valueOf(obfString), new JavaInteger(number)), null, context);
      							modifier.remove(a2);
      							modifier.remove(a1);
      							modifier.replace(m, new LdcInsnNode(value));
                                  decryptor.add(decrypterNode);
                                  count.getAndIncrement();
  							}
  						}
                      }
              	}
              modifier.apply(method);
          }
      System.out.println("[Smoke] [StringEncryptionTransformer] Decrypted " + count + " encrypted strings");
      System.out.println("[Smoke] [StringEncryptionTransformer] Removed " + cleanup(decryptor) + " decryption methods");
      System.out.println("[Smoke] [StringEncryptionTransformer] Done");
return true;
  }
 
Example #16
Source File: Instrumenter.java    From coroutines with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void verifyClassIntegrity(ClassNode classNode) {
    // Do not COMPUTE_FRAMES. If you COMPUTE_FRAMES and you pop too many items off the stack or do other weird things that mess up the
    // stack map frames, it'll crash on classNode.accept(cw).
    ClassWriter cw = new SimpleClassWriter(ClassWriter.COMPUTE_MAXS/* | ClassWriter.COMPUTE_FRAMES*/, classRepo);
    classNode.accept(cw);
    
    byte[] classData = cw.toByteArray();

    ClassReader cr = new ClassReader(classData);
    classNode = new SimpleClassNode();
    cr.accept(classNode, 0);

    for (MethodNode methodNode : classNode.methods) {
        Analyzer<BasicValue> analyzer = new Analyzer<>(new SimpleVerifier(classRepo));
        try {
            analyzer.analyze(classNode.name, methodNode);
        } catch (AnalyzerException e) {
            // IF WE DID OUR INSTRUMENTATION RIGHT, WE SHOULD NEVER GET AN EXCEPTION HERE!!!!
            StringWriter writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            
            printWriter.append(methodNode.name + " encountered " + e);
            
            Printer printer = new Textifier();
            TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(printer);
            
            AbstractInsnNode insn = methodNode.instructions.getFirst();
            while (insn != null) {
                if (insn == e.node) {
                    printer.getText().add("----------------- BAD INSTRUCTION HERE -----------------\n");
                }
                insn.accept(traceMethodVisitor);
                insn = insn.getNext();
            }
            printer.print(printWriter);
            printWriter.flush(); // we need this or we'll get incomplete results
            
            throw new IllegalStateException(writer.toString(), e);
        }
    }
}
 
Example #17
Source File: SimpleVerifierTest.java    From coroutines with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testVertificationWithoutUsingClassLoader() throws Exception {

    // augment method to take in a single int argument
    methodNode.desc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);

    // augment method instructions
    VariableTable varTable = new VariableTable(classNode, methodNode);

    Class<?> iterableClass = Iterable.class;
    Constructor arrayListConstructor = ConstructorUtils.getAccessibleConstructor(ArrayList.class);
    Constructor linkedListConstructor = ConstructorUtils.getAccessibleConstructor(LinkedList.class);
    Constructor hashSetConstructor = ConstructorUtils.getAccessibleConstructor(HashSet.class);
    Method iteratorMethod = MethodUtils.getAccessibleMethod(iterableClass, "iterator");

    Type iterableType = Type.getType(iterableClass);

    VariableTable.Variable testArg = varTable.getArgument(1);
    VariableTable.Variable listVar = varTable.acquireExtra(iterableType);

    /**
     * Collection it;
     * switch(arg1) {
     *     case 0:
     *         it = new ArrayList()
     *         break;
     *     case 1:
     *         it = new LinkedList()
     *         break;
     *     case 2:
     *         it = new HashSet()
     *         break;
     *     default: throw new RuntimeException("must be 0 or 1");
     * }
     * list.iterator();
     */
    LabelNode invokePoint = new LabelNode();
    InsnList methodInsnList
            = merge(tableSwitch(loadVar(testArg),
                            throwRuntimeException("must be 0 or 1"),
                            0,
                            merge(
                                    construct(arrayListConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            ),
                            merge(
                                    construct(linkedListConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            ),
                            merge(
                                    construct(hashSetConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            )
                    ),
                    addLabel(invokePoint),
                    call(iteratorMethod, loadVar(listVar)),
                    pop(), // discard results of call
                    returnVoid()
            );

    methodNode.instructions = methodInsnList;
    
    
    
    // write out class and read it back in again so maxes and frames can be properly computed for frame analyzer
    SimpleClassWriter writer = new SimpleClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS, classRepo);
    classNode.accept(writer);
    byte[] data = writer.toByteArray();
    
    ClassReader cr = new ClassReader(data);
    classNode = new SimpleClassNode();
    cr.accept(classNode, 0);

    
    methodNode = classNode.methods.get(1);
    

    // analyze
    Frame<BasicValue>[] frames;
    try {
        frames = new Analyzer<>(new SimpleVerifier(classRepo)).analyze(classNode.name, methodNode);
    } catch (AnalyzerException ae) {
        throw new IllegalArgumentException("Analyzer failed to analyze method", ae);
    }
    
    
    // get last frame
    Frame frame = frames[frames.length - 1];
    BasicValue basicValue = (BasicValue) frame.getLocal(listVar.getIndex());
    
    
    // ensure that that the local variable for the collection we created in the switch blocks is an abstract type
    assertEquals("java/util/AbstractCollection", basicValue.getType().getInternalName());
}
 
Example #18
Source File: ConstructorThisInterpreterTest.java    From AVM with MIT License 4 votes vote down vote up
@Test
public void examineSecondConstructor() throws Exception {
    MethodNode node = buildSecondConstructor();
    Analyzer<ConstructorThisInterpreter.ThisValue> analyzer = new Analyzer<>(new ConstructorThisInterpreter());
    Frame<ConstructorThisInterpreter.ThisValue>[] frames = analyzer.analyze(ConstructorThisInterpreterTest.class.getName(), node);
    
    // Below are the totals derived from manually inspecting the bytecode below and how we interact with it.
    int bytecodeCount = 6;
    int explicitFrameCount = 0;
    int labelCount = 0;
    Assert.assertEquals(bytecodeCount + explicitFrameCount + labelCount, frames.length);
    
    // To make this clear (since this is not obvious), we write the frame stacks.
    for (Frame<ConstructorThisInterpreter.ThisValue> frame : frames) {
        int size = frame.getStackSize();
        report(size + ": ");
        for (int i = size; i > 0; --i) {
            ConstructorThisInterpreter.ThisValue val = frame.getStack(i-1);
            String value = (null != val)
                    ? (val.isThis ? "T" : "F")
                    : "_";
            report(value);
        }
        reportLine();
    }
    
    // Now, verify the top of the stack at each bytecode.
    int index = 0;
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // ALOAD
    Assert.assertEquals(true, peekStackTop(frames[index++]).isThis);
    // ALOAD
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // PUTFIELD
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // ALOAD
    Assert.assertEquals(true, peekStackTop(frames[index++]).isThis);
    // INVOKESPECIAL
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // RETURN
    Assert.assertEquals(frames.length, index);
}
 
Example #19
Source File: ConstructorThisInterpreterTest.java    From AVM with MIT License 4 votes vote down vote up
@Test
public void examineTestConstructor() throws Exception {
    MethodNode node = buildTestConstructor();
    Analyzer<ConstructorThisInterpreter.ThisValue> analyzer = new Analyzer<>(new ConstructorThisInterpreter());
    Frame<ConstructorThisInterpreter.ThisValue>[] frames = analyzer.analyze(ConstructorThisInterpreterTest.class.getName(), node);
    
    // Below are the totals derived from manually inspecting the bytecode below and how we interact with it.
    int bytecodeCount = 17;
    int explicitFrameCount = 2;
    int labelCount = 2;
    Assert.assertEquals(bytecodeCount + explicitFrameCount + labelCount, frames.length);
    
    // To make this clear (since this is not obvious), we write the frame stacks.
    for (Frame<ConstructorThisInterpreter.ThisValue> frame : frames) {
        int size = frame.getStackSize();
        report(size + ": ");
        for (int i = size; i > 0; --i) {
            ConstructorThisInterpreter.ThisValue val = frame.getStack(i-1);
            String value = (null != val)
                    ? (val.isThis ? "T" : "F")
                    : "_";
            report(value);
        }
        reportLine();
    }
    
    // Now, verify the top of the stack at each bytecode.
    int index = 0;
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // ALOAD
    Assert.assertEquals(true, peekStackTop(frames[index++]).isThis);
    // INVOKESPECIAL
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // ICONST_5
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // ILOAD
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // IF_ICMPNE
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // ALOAD
    Assert.assertEquals(true, peekStackTop(frames[index++]).isThis);
    // GOTO
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // (label)
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // (frame)
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // ALOAD
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // (label)
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // (frame)
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // ILOAD
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // PUTFIELD
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // ALOAD
    Assert.assertEquals(true, peekStackTop(frames[index++]).isThis);
    // ICONST_1
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // PUTFIELD
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // ALOAD
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // ICONST_2
    Assert.assertEquals(false, peekStackTop(frames[index++]).isThis);
    // PUTFIELD
    Assert.assertEquals(null, peekStackTop(frames[index++]));
    // RETURN
    Assert.assertEquals(frames.length, index);
}
 
Example #20
Source File: ClassVisitorExample.java    From grappa with Apache License 2.0 4 votes vote down vote up
@Override
public MethodVisitor visitMethod(final int access, final String name,
    final String desc, final String signature, final String[] exceptions)
{
    // Unused?
    /*
    final MethodVisitor mv = super.visitMethod(access, name, desc,
        signature, exceptions);
    */

    return new MethodNode(Opcodes.ASM5, access, name, desc, signature,
        exceptions)
    {
        @Override
        public void visitEnd()
        {
            super.visitEnd();

            try {
                final BasicInterpreter basicInterpreter
                    = new BasicInterpreter();
                final Analyzer<BasicValue> analyzer
                    = new Analyzer<>(basicInterpreter);
                final AbstractInsnNode[] nodes = instructions.toArray();
                final Frame<BasicValue>[] frames
                    = analyzer.analyze(className, this);
                int areturn = -1;
                for (int i = nodes.length -1; i >= 0; i--)
                {
                    if (nodes[i].getOpcode() == Opcodes.ARETURN) {
                        areturn = i;
                        System.out.println(className + "." + name + desc);
                        System.out.println("Found areturn at: " + i);
                    } else if (areturn != -1
                        && nodes[i].getOpcode() != -1
                        && frames[i].getStackSize() == 0) {
                        System.out.println("Found start of block at: " + i);

                        final InsnList list = new InsnList();
                        for (int j = i; j <= areturn; j++)
                            list.add(nodes[j]);
                        final Textifier textifier = new Textifier();
                        final PrintWriter pw = new PrintWriter(System.out);
                        list.accept(new TraceMethodVisitor(textifier));
                        textifier.print(pw);
                        pw.flush();
                        System.out.println("\n\n");
                        areturn = -1;
                    }
                }
            }
            catch (AnalyzerException e) {
                e.printStackTrace();
            }

            if (mv != null)
                accept(mv);
        }
    };
}