Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically decompile a Class Object on memory?

I'm making a tool to dynamically display the sourcecode of running java class. I need a tool to help me on dynamically decompile from a Class Object to String of sourcecode. I know some decompile tools like Jad, DJ decompiler can decompile a .class file but I expect a tool can:

Class<?> c = ..; // get from runtime environment
String sourcecode = **DecompileTool**.decompileClassObject(c);
return sourcecode;

I need such a DecompileTool, anyone knows? Thanks

like image 965
JerryCai Avatar asked Jul 02 '12 03:07

JerryCai


2 Answers

I'm not aware of any decompiler that can be used like that.

Indeed, in the general case it is not possible to implement a decompiler that works like that:

  • The Class<?> object that you get from the runtime doesn't provide any way to get to the bytecodes.

  • In order to get hold of the bytecodes, you would need to redo what the classloader does when it locates the ".class" file from the classpath.

  • I don't think there's a way to find out what classloaders are in use ... if you include the possibility of dynamically instantiated classloaders. (And such classloaders are normal practice in (for example) web containers.)

  • In the general case, a classloader will do that in ways that you cannot reproduce ... without reverse engineering and hard-coding the same logic into your decompiler adapter code.

Besides, doing this on the fly is probably pointless, because there is a significant chance that the decompiler will produce source code that isn't compilable.

like image 148
Stephen C Avatar answered Oct 11 '22 16:10

Stephen C


I don't think that any of these decompilers support this type of ugly interface.

First of all, most decompilers will represent any code in a similar format to the actual compiler, so, an Abstract Syntax Tree. If you are lucky, and the decompiler does have an interface, it will probably be of this type. Handing back a raw String is unlikely to be satisfactory, because how would the person writing the decompiler have any idea as to how you wanted the code formatted (one of the biggest challenges in decompilation is presenting the result to the user!).

Instead, what you should do, is write a little wrapper, that does this properly: on the fly generation of the files that need to be decompiled, sending them through the decompiler, and extracting the result into a String (which you can get immediately if you do clever forking and piping, etc..., but in reality you probably just want to format the output file of the decompiler..)

like image 28
Kristopher Micinski Avatar answered Oct 11 '22 18:10

Kristopher Micinski