user1912475
user1912475

Reputation: 49

understanding bytecode java

Is it possible to read or identify what class is being referenced by the INVOKESPECIAL instruction from java bytecode? If yes, how? Also, how do I know what will be the next line executed after a jump?

Keep in mind that I wanna make a program that do this. What I'm trying to do is find a way to automaticaly localize exception handling through the bytecode alone.

Upvotes: 2

Views: 366

Answers (2)

Akdeniz
Akdeniz

Reputation: 1270

There are lots of framework them out there for bytecode manipulation. But I personally prefer ASM. It's XML-parsing like mechanism is a lot easier to learn.

For example, you can use this code to list all INVOKESPECIAL callings in a jar file: It will print lines like this:

INVOKESPECIAL[ opcode=183, owner=java/lang/StringBuilder, name=<init>, desc=()V].

You can say it is the <init> function of java/lang/StringBuilder that is referenced by INVOKESPECIAL.

JarFile jarFile = new JarFile("xxx.jar");
Enumeration<JarEntry> entries = jarFile.entries();

while (entries.hasMoreElements()) {
    JarEntry jarEntry = entries.nextElement();
    if (jarEntry != null && jarEntry.getName().endsWith(".class")) {
        InputStream eis = jarFile.getInputStream(jarEntry);
        ClassReader classReader = new ClassReader(eis);
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        MyClassVisitor mcw = new MyClassVisitor(Opcodes.ASM4, cw);
        classReader.accept(mcw, 0);
        eis.close();
    }
}


class MyClassVisitor extends ClassVisitor {
private int api;
public MyClassVisitor(int api, ClassWriter cw) {
    super(api, cw);
    this.api = api;
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
    return new MyMethodVisitor(api, mv);
}
class MyMethodVisitor extends MethodVisitor {

    public MyMethodVisitor(int api, MethodVisitor mv) {
        super(api, mv);
    }
    @Override
    public void visitMethodInsn(int opcode, String owner, String name, String desc) {
        if (opcode == Opcodes.INVOKESPECIAL) {
            System.out.println("INVOKESPECIAL[ opcode=" + opcode + ", owner=" + owner + ", name=" + name
                    + ", desc=" + desc+"]");
        }
        super.visitMethodInsn(opcode, owner, name, desc);
    }
}
}

Upvotes: 0

umert
umert

Reputation: 138

you can check this framework about http://asm.ow2.org/. "The ASM framework is the fastest, most flexible and well known framework around for doing bytecode manipulation"

Upvotes: 1

Related Questions