Exemplo n.º 1
0
  /** Generate class bytes for java.lang.Runnable implementation and return the same. */
  public byte[] generate(Method method, String className) {
    int modifiers = method.getModifiers();
    // make sure that the method is public static
    // and accepts no arguments
    if (!Modifier.isStatic(modifiers)
        || !Modifier.isPublic(modifiers)
        || method.getParameterTypes().length != 0) {
      throw new IllegalArgumentException();
    }
    Class clazz = method.getDeclaringClass();
    modifiers = clazz.getModifiers();
    // make sure that the class is public as well
    if (!Modifier.isPublic(modifiers)) {
      throw new IllegalArgumentException();
    }

    ClassWriter cw = InstrumentUtils.newClassWriter();
    cw.visit(
        V1_1, ACC_PUBLIC, className, null, "java/lang/Object", new String[] {"java/lang/Runnable"});
    // creates a MethodWriter for the (implicit) constructor
    MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    // pushes the 'this' variable
    mw.visitVarInsn(ALOAD, 0);
    // invokes the super class constructor
    mw.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    mw.visitInsn(RETURN);
    mw.visitMaxs(1, 1);
    mw.visitEnd();

    // creates a MethodWriter for the 'main' method
    mw = cw.visitMethod(ACC_PUBLIC, "run", "()V", null, null);
    // invokes the given method
    mw.visitMethodInsn(
        INVOKESTATIC,
        Type.getInternalName(method.getDeclaringClass()),
        method.getName(),
        Type.getMethodDescriptor(method));
    mw.visitInsn(RETURN);
    mw.visitMaxs(1, 1);
    mw.visitEnd();
    return cw.toByteArray();
  }
Exemplo n.º 2
0
  public static void main(final String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage: java com.sun.btrace.runtime.ErrorReturnInstrumentor <class>");
      System.exit(1);
    }

    args[0] = args[0].replace('.', '/');
    FileInputStream fis = new FileInputStream(args[0] + ".class");
    ClassReader reader = new ClassReader(new BufferedInputStream(fis));
    FileOutputStream fos = new FileOutputStream(args[0] + ".class");
    ClassWriter writer = InstrumentUtils.newClassWriter();
    InstrumentUtils.accept(
        reader,
        new ClassVisitor(Opcodes.ASM4, writer) {
          public MethodVisitor visitMethod(
              int access, String name, String desc, String signature, String[] exceptions) {
            MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
            return new ErrorReturnInstrumentor(mv, null, args[0], args[0], access, name, desc);
          }
        });
    fos.write(writer.toByteArray());
  }