Skip to content

Commit

Permalink
Fix for unintentional removal of some leave instructions (#96)
Browse files Browse the repository at this point in the history
This will keep 2 leave instructions, but it's jump anyway, no harm done. Upstream harmony makes it this way.
These instructions are added after all transpilers have already been applied, and repatching takes original instructions anyway.
And, if someone wants to, they can find a way to remove these duplicates without offset shifting later on.

Fixes #65 and Closes #77
  • Loading branch information
kohanis authored Jan 19, 2024
1 parent 4148feb commit 2ea021a
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 30 deletions.
8 changes: 2 additions & 6 deletions Harmony/Internal/Patching/ILManipulator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -340,17 +340,13 @@ public void WriteTo(MethodBody body, MethodBase original = null)
var newInstructions = ApplyTranspilers(cil, original, vDef => il.GetLocal(vDef), il.DefineLabel);

// Step 2: Emit code
foreach (var (cur, next) in newInstructions.Pairwise())
foreach (var cur in newInstructions)
{
cur.labels.ForEach(l => il.MarkLabel(l));
cur.blocks.ForEach(b => il.MarkBlockBefore(b));

// 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;
// Case 2: endfilter/endfinally and end of exception marker => ILProcessor will generate the correct end
// Case: 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;
// Other cases are either intentional leave or invalid IL => let them be processed and let JIT generate correct exception
Expand Down
24 changes: 0 additions & 24 deletions Harmony/Tools/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -595,30 +595,6 @@ internal static Dictionary<K, V> TransformKeys<K, V>(this Dictionary<K, V> origD
dict.Add(transform(pair.Key), pair.Value);
return dict;
}

// Iterates the enumerable pairwise, i.e. by returning tuple (current, next)
internal static IEnumerable<(T, T)> Pairwise<T>(this IEnumerable<T> self)
{
var isFirst = true;
T prev = default;

foreach (var e in self)
if (isFirst)
{
prev = e;
isFirst = false;
}
else
{
yield return (prev, e);
prev = e;
}

if (isFirst)
yield break;

yield return (prev, default);
}
}

/// <summary>General extensions for collections</summary>
Expand Down

0 comments on commit 2ea021a

Please sign in to comment.