-2

I can't just replace the entire method. I have to just inject a reassignment of a local var after the last time it normally gets set but before it gets used near the end of the method.

Here's some pseudocode

void test() {
/* stuff */

String thing = null;

if (case1) {
  thing = "case1"
}

if (case2) {
  thing = "case2"
}

if (case3) {
  thing = "case3"
}

if (thing == null) {
  thing = "default";
}

/* I want to insert this code below with ASM */
thing = "Injected by ASM";

/* stuff */
}

I could also just replace the default assignment when the code reaches that point where it checks if thing == null. But the byte code for the default assignment is a pretty long StringBuilder with lots of appends. There's a LDC that I can use to uniquely identify that but line I dunno how to replace the whole thing assignment for that line. I only know how to replace the LDC (which is not enough).

The idea is I want to ignore all the case1-3 so that thing is always what I tell ASM to set it as

But the /* stuff */ at the top and bottom of the method cannot be removed

vaps
  • 57
  • 5
  • Sounds like you are doing or trying to do illegal stuff with a disassembler correct me if iam wrong – Raymond Nijland Oct 12 '18 at 18:09
  • If it was illegal I wouldn't be here – vaps Oct 12 '18 at 18:14
  • You didn't ask a question. Besides that, it seems you are focusing too much on irrelevant points. When you want to set a local variable "before it gets used", do exactly that, identify the place where it is used and assign it right before that. All that happens before that point, is irrelevant. – Holger Oct 14 '18 at 14:59
  • I don't know how to visit/insert instructions before an instruction I have found (am currently visiting). Because of that I think I need to somehow store a variable pointing/marking where I found it so that I can pass over the code again and use that variable to know where to insert the new instruction. – vaps Oct 14 '18 at 21:18
  • Oh look what I found https://asm.ow2.io/javadoc/org/objectweb/asm/tree/InsnList.html Should I use this? – vaps Oct 15 '18 at 05:47

1 Answers1

0

While you could visit the instructions in the method to find the last place it is set, and then pass over the code again to inject the change, the simplest approach is to translate the code so that every time the variable is set, you set it to the value you want. This might not even need more code, just replace what is there.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thanks for the input, can you provide some code examples? – vaps Oct 12 '18 at 20:53
  • When you say visit the instructions to find the last place it is set. How would I store that information so that I know where to set it when I pass over the code again? I was thinking I was gonna have to use labels. This is just a little project I am doing to learn bytecode manipulation. It's nothing but a hello world/test project. – vaps Oct 12 '18 at 22:13