Wednesday, March 10, 2010

"Reverse engineering" Java class magic errors

A quick post that has nothing to do with security.

When Java loads class files, be that over the network or from disk, it verifies the magic number, ie. the 4 first bytes of the file. In a valid Java class file these are always (in hex): CA FE BA BE. That's 3405691582 as a decimal integer value.

If the local file or a network resource that Java is trying to read as class is corrupted or, in fact, is not a class file, you'll get an error:

java.lang.ClassFormatError: Incompatible magic value [number] in class file [package.class]

For example:

java.lang.ClassFormatError: Incompatible magic value 1008813135 in class file test.MyClass

A simple, but neat trick I picked up from a Brazilian forum some years ago, was to reverse the invalid magic value in order to better understand what file Java was reading.

In the example above, 1008813135 in hex is 3C 21 44 4F.

That, in ASCII translates into:
<!DO

Which, in all probability is the beginning of the HTML4.0 declaration:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

In other words, Java is trying to load the binary class file, but instead is getting a HTML page.

Another example would be:

Invalid magic integer from the error message: 1013478509
Hex: 3C 68 74 6D
ASCII: <htm (another HTML page)

Update: Adding the link from Tom's comment: http://stackoverflow.com/questions/1871501/embedding-an-applet-doesnt-work-on-my-website

2 comments:

Unknown said...

That turned up in one of the more interesting questions on stackoverflow a few months ago. http://stackoverflow.com/questions/1871501/embedding-an-applet-doesnt-work-on-my-website

Erik said...

I like that the header for Class files is Cafe Babe - nice!