Question

Given the .class file of Java Class A, is there a way (with BCEL, ASM, etc. for instance) to extract a given bytecode sequence (assuming it's a basic block), place it in a separate location, and then later execute that sequence of bytecodes?

Example: Source code has the lines ... a += b; b += 21; . .

I only have access to the bytecode representation. I want to extract those bytecodes and treat them as a black box. In Class A's instructions, instead of the source line 'a += b;' I want it to point to this external black box X which holds the appropriate missing bytecode sequence. I want to feed the black box all necessary variables on the stack frame (for instance, the current values of a, b, perhaps method parameters to be used in black box X...) and then, after execution of the bytecode sequence, the black box will return control to the original Class A along with the newly updated frame variables...

Thanks for any ideas.

Edit:

As suggested below, the black box most reasonably would be a stub method inside of a stub class file. The question then becomes, how do I most reasonably create this well formed stub class and method from this instruction sequence, and how to do the transfer of control to, from the original Class A. Ideally this would be done 'offline', at compile time.

Was it helpful?

Solution

The tricky part is how you going to identify your instruction sequence. I can think of doing that by line number or some marker method call at the beginning and end of the sequence.

When you get that sorted out, you can use ASM's analysis package to calculate types of local variables and stack slots and expose them as parameters of some method where you'd copy your bytecode sequence.

My article from AOSD'07 should give you a good starting point with ASM. Replace Method Body and Inline Method sections describing transformations very similar to what you may need to use.

OTHER TIPS

The only way to execute bytecodes on a JVM spec compliant implementation of Java is to put the bytecodes into a (well-formed) class file and load that file. (That means that the bytecodes need to be wrapped in "methods" in the class file, because that's the only place that bytecodes can go.)

In addition, the bytecodes have to obey all of the safety rules that are enforced by the bytecode verifier. That is going to limit your ability to execute arbitrary sequences.

If you are just trying to figure out what a bytecode sequence does, you are better of hand-executing it, or using some kind of bytecode emulator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top