0

Alright so I'm trying to create a getter inside ClassA that returns a static field inside ClassB using Objectweb ASM. The classes I start out with look like this:

ClassA:

public class ClassA {

}

ClassB:

public class ClassB {

    static int secret = 123;

}

And I'm trying to dump ClassA to look like this once decompiled:

public class ClassA {

    public int getSecretInt(){
        return ClassB.secret;
    }
}

So far I have been able to return fields inside ClassA itself but I'm not sure how to go about returning static fields inside other classes.

What I can do: (this adds a method to ClassA that returns a variable inside its self)

        MethodNode mn = new MethodNode(ACC_PUBLIC, getterName, "()" + fieldDescriptor, signature, null);

        mn.instructions.add(new VarInsnNode(ALOAD, 0));
        mn.instructions.add(new FieldInsnNode(isStatic ? GETSTATIC : GETFIELD, cn.name, fieldName, fieldDescriptor));
        mn.instructions.add(new InsnNode(retInsn));

        mn.visitMaxs(3, 3);
        mn.visitEnd();
        cn.methods.add(mn);

What i want to do is make this method I generate return a static value from ClassB.

basically make it:

return ClassB.secret;
Aditi Parikh
  • 1,522
  • 3
  • 13
  • 34

1 Answers1

1

Generally, the easiest way to get the right calls to ASM is use the ASMifier class on the bytecode (.class file) that is compiled from some Java code.

That said, getting a static field from another class is straightforward and should not require the use of ASMifier. Assuming you have a MethodVisitor mw obtained from a ClassWriter (if you want to generate bytecode directly say), it would look like:

mw.visitFieldInsn(Opcodes.GETSTATIC, "ClassB", "secret", "I");
mw.visitInsn(Opcodes.IRETURN);

No need to load "this" (ALOAD 0). Also, you don't have to compute frames and locals yourself, you can use ClassWriter.COMPUTE_FRAMES and COMPUTE_MAXS so that ASM does it for you. And for the code you show, you only have one variable ("this" is implicit) and need only one stack element (for the value of ClassB.secret).

Matthieu Wipliez
  • 1,901
  • 1
  • 16
  • 15