Skip to content

Instantly share code, notes, and snippets.

@dhinojosa
Created January 19, 2025 03:16
Show Gist options
  • Save dhinojosa/20feb8ea8881879cad3a25d20331853e to your computer and use it in GitHub Desktop.
Save dhinojosa/20feb8ea8881879cad3a25d20331853e to your computer and use it in GitHub Desktop.
Justin Lee ByteCode Low Down

I'm putting together an "intro to bytecode" talk for jfokus in a couple of weeks and noticed an oddity that I don't have an explanation for. If i have a method like this:

    public void someMethod() {
        int local = 17;
        local *= 18;
      
        var name = "Iron Man";
        name = "Tony Stark";
       }
    }

I get bytecode like this (using asm's Textifier to dump to text):

    LOCALVARIABLE this Lcom/antwerkz/underthehood/Methods; L0 L5 0
    LOCALVARIABLE local I L1 L5 1
    LOCALVARIABLE name Ljava/lang/String; L3 L5 2
    MAXSTACK = 2
    MAXLOCALS = 3            

but if I change it to this:

    public void someMethod() {
        int local = 17;
        local *= 18;

        {
            var name = "Iron Man";
            name = "Tony Stark";
        }
    }

Then I get this bytecode:

      LocalVariableTable:
        Start  Length  Slot  Name   Signature
           11       3     2  name   Ljava/lang/String;
            0      15     0  this   Lcom/antwerkz/underthehood/Methods;
            3      12     1 local   I

Notice that even though the slots are the same, the order is changed up. I don't know if it means anything or if it's just a quirk of asm but does anyone know?

Playing around with "local" moving to after the block and inside the block I get some variations. When "local" comes after that block, both "local" and "name" are in slot 1. My gut says this is all related to local variable hoisting and such but it's the ordering of the table that throws me. Anyone have any insight?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment