Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix attempt for mismatched jump labels by IlProcessor #77

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions Harmony/Internal/Patching/ILManipulator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -347,9 +347,7 @@ public void WriteTo(MethodBody body, MethodBase original = null)

// We need to handle exception handler opcodes specially because ILProcessor emits them automatically
// Case 1: leave + start or end of exception block => ILProcessor generates leave automatically
if ((cur.opcode == SRE.OpCodes.Leave || cur.opcode == SRE.OpCodes.Leave_S) &&
(cur.blocks.Count > 0 || next?.blocks.Count > 0))
goto mark_block;
// Note: ILProcessor seems to generate some labels with wrong offset, clean-up code afterwards!
// Case 2: endfilter/endfinally and end of exception marker => ILProcessor will generate the correct end
if ((cur.opcode == SRE.OpCodes.Endfilter || cur.opcode == SRE.OpCodes.Endfinally) && cur.blocks.Count > 0)
goto mark_block;
Expand Down Expand Up @@ -380,6 +378,22 @@ public void WriteTo(MethodBody body, MethodBase original = null)
cur.blocks.ForEach(b => il.MarkBlockAfter(b));
}

// Remove duplicate `leave` Op-Codes to cleanup
// Should be safe if "double-jumps" are not a thing
for (int i = 0; i < body.Instructions.Count - 1; i++)
{
// Find two leave instructions in a row to clean up
if (body.Instructions[i].OpCode != OpCodes.Leave &&
body.Instructions[i].OpCode != OpCodes.Leave_S) continue;
if (body.Instructions[i + 1].OpCode != OpCodes.Leave &&
body.Instructions[i + 1].OpCode != OpCodes.Leave_S) continue;
// Not exactly sure why this happens, labels should agree here!?
// if (body.Instructions[i].Offset != body.Instructions[i + 1].Offset)
// Logger.Log(Logger.LogChannel.Warn, () =>
// "Found conescutive leave ops that don't agree");
body.Instructions.RemoveAt(i + 1);
}

// Special Harmony interop case: if no instructions exist, at least emit a quick return to attempt to get a valid method
// Vanilla Harmony (almost) always emits a `ret` which allows for skipping original method by writing an empty transpiler
if (body.Instructions.Count == 0)
Expand Down