JVM instruction ALOAD_0 in the 'main' method points to 'args' instead of 'this'?

2022-09-02 00:32:28

I am trying to implement a subset of Java for an academic study. Well, I'm in the last stages (code generation) and I wrote a rather simple program to see how method arguments are handled:

class Main {
    public static void main(String[] args) {
        System.out.println(args.length);
    }
}

Then I built it, and ran 'Main.class' through an online disassembler I found at: http://www.cs.cornell.edu/People/egs/kimera/disassembler.html

I get the following implementation for the 'main' method: (the disassembled output is in Jasmin)

.method public static main([Ljava/lang/String;)V
    .limit locals 1
    .limit stack 2

    getstatic   java/lang/System/out Ljava/io/PrintStream;
    aload_0
    arraylength
    invokevirtual   java/io/PrintStream.println(I)V
    return
.end method

My problem with this is:
1. is supposed to push 'this' on to the stack (thats what the JVM spec seems to say)
2. is supposed to return the length of the array whose reference is on the top-of-stackaload_0arraylength

So according to me the combination of 1 & 2 should not even work.

How/why is it working? Or is the disassembler buggy and the actual bytecode is something else?


答案 1

aload_0 is supposed to push 'this' on to the stack

Not quite … reads the first reference argument (or, more generally, the first local reference variable) of the method and pushes it onto the stack.aload_0

In member functions, the first local variable happens to be the reference.this

But is not a member function, it’s a static function so there is no argument, and the true first argument of the method is .mainthisargs


答案 2

推荐