Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing a .class file directly, playing around with opcodes

Tags:

java

jvm

bytecode

today I just tried to play a little bit around with the opcodes in compiled java class file. After inserting

iinc 1,1

the java virtual machine responds with:

Exception in thread "main" java.lang.ClassFormatError: Truncated class file
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: Test.  Program will exit.

This is my example source code:

public class Test {

    public static void main(String[] args) {
        int i = 5;
        i++;
        i++;
        i++;
        System.out.println("Number: " + i + "\n");
    }
}

The opcode for an increment is 0x84 + 2 bytes for operands. There's only one section in the resulting class file, which contains 0x84:

[..] 8401 0184 0101 8401 01[..]

So I would translate this as:

iinc 1,1
iinc 1,1
iinc 1,1

corresponding to my i++; i++; i++;

I then tried to append just 840101 to increment the variable once more, but that didn't work and resulted in the ClassFormatError.

Is there anything like a checksum for the class file? I looked up the format of a classfile in http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html but could not find anything which points out to some kind of bytes_of_classfile or something. I also don't understand why the error is "Truncated Class File", because I did append something :-)

I know its not a good idea to edit class files directly, but I'm just interested on the VM internals here.

like image 755
echox Avatar asked Feb 28 '23 01:02

echox


1 Answers

(Disclaimer: I didn't disassemble your example.)

If you look at the structure of the class format, you'll see that method_info contains in its attributes Code_attributes (4.7.3), which in turn specify among others the code_length.

Because of your editing, you first violate the declared length, and second of course any subsequent data after the method you modified would now be at different offsets.

like image 104
Volker Stolz Avatar answered Mar 05 '23 15:03

Volker Stolz