Search code examples
javaaspectjbytecodeaop

Java bytecode error using AspectJ


I am trying to modify the working of some code using AspectJ. The aspectJ code is of the form (Profiler.java):

public aspect Profiler {
      pointcut beforeMethod(): !within(Profiler);
      before(): beforeMethod() { /* Do something */ }
      pointcut afterMethod(): !within(Profiler);
      after(): afterMethod() { /* Do something */}
}

I am now trying to run this on the following code (Hello.java):

public class Hello {
    public static void main(String args[]) {
        for (int i = 0; i < 100; i++) {
            a(i);
        }
        System.out.println("Hello");
   }
   public static void a(int x) {
        for (int i = 0; i < 10; i++) {
            b();
        }
    }
   public static void b() {
        int j = 1;
        for (int i = 0; i < 10; i++) {
            j++;
        }
    }
}

Using ajc compiler to compile both Hello.java and Profiler.java gives me the expected result. But when I compile Profiler.java to a jar file using ajc, and try to use a javaagent, it gives a bytecode error:

Exception in thread "main" java.lang.VerifyError: Bad <init> method call from after the start of a try block

Exception Details:
  Location:
    Hello.<init>()V @55: invokespecial
  Reason:
    Error exists in the bytecode
  Bytecode:
    0000000: 2ab2 0065 0101 b800 2e3a 05b8 0034 1905
    0000010: b200 65b6 0038 00a7 0013 3a06 b800 3419
    0000020: 05b2 0065 b600 3b19 06bf 00b8 0034 1905
    0000030: b200 65b6 003b 00b7 0001 b200 622a 2ab8
    0000040: 002e 4eb8 0034 2db2 0062 b600 38b2 0028
    0000050: 2a2a b800 2e4c b800 342b b200 28b6 0038
    0000060: a700 104d b800 342b b200 28b6 003b 2cbf
    0000070: b800 342b b200 28b6 003b a700 123a 04b8
    0000080: 0034 2db2 0062 b600 3b19 04bf b800 342d
    0000090: b200 62b6 003b b1 

Any ideas what the problem is?


Solution

  • I think you are hitting a variant of https://bugs.eclipse.org/bugs/show_bug.cgi?id=443477 related to weaving of the pre-initialization joinpoint. First step I'd say try using the most recent AspectJ version (you don't mention what version you are using). However, that may not fix things because the fix for 443477 related to cflow, which you aren't using. If it does still happen I'd say raise a bug against AspectJ on bugs.eclipse.org. You do have pretty wide reaching pointcuts - we don't really recommend writing pointcuts that don't use a kinded component (call/execution/get/set/etc) - without them you are hitting those preinitialization join points alongside everything else. You could exclude preinitialization by adjusting your pointcuts, that may be a workaround.