Skip to content

Instantly share code, notes, and snippets.

@sparr
Last active December 4, 2018 08:44
Show Gist options
  • Save sparr/2d5752cf42391d17a2dadffbcceef516 to your computer and use it in GitHub Desktop.
Save sparr/2d5752cf42391d17a2dadffbcceef516 to your computer and use it in GitHub Desktop.
IL patch problem with stfld stack
I am trying to transpile a new conditional code path into an existing method.
Here is the original code that I am targeting, as output by the Harmony library's CodeInstruction class:
ldarg.0
ldflda Verse.IntVec3 startDragCell
Here is my new code that replaces it:
ldobj DraggableCorners.DraggableCorners
ldfld System.Int32 initialDragAxis
ldc.i4.0
bne.un.s Label6 // do the original code instead of the new code
call IntVec3 MouseCell()
stloc.2
ldloca.s 2
br.s Label7 // skip past the original code
ldarg.0 [Label6]
ldflda Verse.IntVec3 startDragCell
The original code takes nothing off the stack and pushes the address of an IntVec3.
Both code paths through the new code, the new call/stloc/ldloca and the old code,
should have that same behavior.
The code that comes after the above is as follows:
call Vector2 ToUIPosition() [Label7]
stloc.3
ldloca.s 3 (UnityEngine.Vector2)
ldfld System.Single y
stfld System.Single y
What this does in the original case is call theLoadedIntVec3.ToUIPosition(), get
the .y field of the resulting Vector2, then put that into the .y field of another
Vector2 that has been sitting on the stack since before any of this code ran.
I expect it to do the same thing with the new code, just the IntVec3 in question
might be different.
However, what actually happens when I try to patch this IL into the method in
question is that an error is thrown, "Invalid IL code in (wrapper dynamic-method)"
with the reported problematic IL being "stfld 0x00000035". 0x35 is a reasonable offset
into the Vector2 struct for its y property, so my hunch here is that the "Invalid IL"
is about something wonky on the stack that I am failing to spot.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment