Search code examples
javastackbytecode

Java bytecode - efficient manner to replace a deep stack value


Here is the short version of the question: is there an efficient way, with bytecode manipulation, to replace a value deep on the JVM stack? To help visualize, the ideal solution would look like this in psuedo-code: stack[offset] = new_value.

Looking at the list of Jasmin instructions, it seems the only way to replace a value "deep" on the stack (really, only more than about 4 stack slots down) is as follows:

  • allocate a collection (e.g. array or list)
  • store each stack value into the collection, consuming each from the stack in the process
  • repeat until the value to replace is at the top of the stack
  • pop off the value to replace
  • push on the new value
  • push the values from the collection back onto the stack (in the correct order, of course)

Is there an more-effecient manner?

Note that the use of local variables is assumed too dangerous as the code here must work with an unknown method, of an unknown class, regardless of its local variable definitions, and without the pre-condition that it can be able to change the local variable definitions for the method, or the fields for the class.


Solution

  • No, there is no easy way to do this. The operand stack is designed to be, well, a stack.

    If you could explain what precisely you are trying to do, perhaps I could suggest a better way to do it.