Java Code Examples for org.objectweb.asm.tree.analysis.Analyzer#analyze()

The following examples show how to use org.objectweb.asm.tree.analysis.Analyzer#analyze() . 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
/**
 * 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 4
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 5
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 6
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 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: 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 9
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 10
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 11
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 12
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 13
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);
        }
    };
}