From 6147d6d16ac603b3528d68502ea882e2c32357c4 Mon Sep 17 00:00:00 2001 From: Marco Rossignoli Date: Sat, 5 Feb 2022 22:52:42 +0100 Subject: [PATCH] fix finally --- .../Instrumentation/Instrumenter.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/coverlet.core/Instrumentation/Instrumenter.cs b/src/coverlet.core/Instrumentation/Instrumenter.cs index 7d8f6f192..cf80e90a3 100644 --- a/src/coverlet.core/Instrumentation/Instrumenter.cs +++ b/src/coverlet.core/Instrumentation/Instrumenter.cs @@ -305,10 +305,22 @@ private void InstrumentModule() onProcessExitIl.InsertAfter(lastInst, firstNullParam); onProcessExitIl.InsertAfter(firstNullParam, secondNullParam); onProcessExitIl.InsertAfter(secondNullParam, callUnload); + var endFinally = Instruction.Create(OpCodes.Endfinally); + onProcessExitIl.InsertAfter(callUnload, endFinally); var ret = onProcessExitIl.Create(OpCodes.Ret); - var leave = onProcessExitIl.Create(OpCodes.Leave, ret); - onProcessExitIl.InsertAfter(callUnload, leave); - onProcessExitIl.InsertAfter(leave, ret); + var leaveAfterFinally = onProcessExitIl.Create(OpCodes.Leave, ret); + onProcessExitIl.InsertAfter(endFinally, ret); + foreach (var inst in onProcessExitMethod.Body.Instructions.ToArray()) + { + // Patch ret to leave after the finally + if (inst.OpCode == OpCodes.Ret && inst != ret) + { + var leaveBodyInstAfterFinally = onProcessExitIl.Create(OpCodes.Leave, ret); + var prevInst = inst.Previous; + onProcessExitMethod.Body.Instructions.Remove(inst); + onProcessExitIl.InsertAfter(prevInst, leaveBodyInstAfterFinally); + } + } var handler = new ExceptionHandler(ExceptionHandlerType.Finally) { TryStart = onProcessExitIl.Body.Instructions.First(),