Search code examples
javabytecodebyte-buddy

bytebuddy - stack manipulation load/store variables by name rather than offset


Im implementing method via stack manipulation and ByteCodeAppender.

My stack manipulation compound looks something like this. Theres a lot of loadFrom(offset) and storeAt(offset) which makes it pain to update/read

    @Override
    public Size apply(MethodVisitor mv, Implementation.Context ctx, MethodDescription md) {
        StackManipulation.Size size = new StackManipulation.Compound(
                MethodVariableAccess.REFERENCE.loadFrom(2),
                ....
                MethodVariableAccess.DOUBLE.storeAt(3),
                ...
                MethodVariableAccess.DOUBLE.loadFrom(3),
                ...
                MethodVariableAccess.LONG.loadFrom(4),
    .....
                MethodReturn.REFERENCE
        ).apply(mv, ctx);
        return new Size(size.getMaximalSize(), md.getStackSize());
    }

Would there be a simpler way to reference offset for load/store instruction?

I understand that java bytecode do not have anything like variables names. On the other hand bytebuddy claims to be high level abstraction, is there anything that would let me lookup local variables by names/unique string keys rather than offsets?


Solution

  • For the JVM, variable names are optional, they are only represented by offsets internally.

    You can however look up parameter names from the supplied MethodDescription, if available, and read the parameter offset from there.