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

Fix for unintentional removal of some leave instructions #96

Merged
merged 1 commit into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
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
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