java文件怎么直接编辑,直接编辑.class文件,使用操作码

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.

解决方案

(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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值