Skip to content

Commit c8eafe5

Browse files
Put AppContext.OnProcessExit body inside a try/finally (#1290)
Put AppContext.OnProcessExit body inside a try/finally
1 parent f4f0bad commit c8eafe5

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

src/coverlet.core/Instrumentation/Instrumenter.cs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -297,10 +297,27 @@ private void InstrumentModule()
297297
var onProcessExitMethod = new MethodReference("OnProcessExit", module.TypeSystem.Void, appContextType).Resolve();
298298
var onProcessExitIl = onProcessExitMethod.Body.GetILProcessor();
299299

300-
lastInstr = onProcessExitIl.Body.Instructions.Last();
301-
onProcessExitIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Ldnull));
302-
onProcessExitIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Ldnull));
303-
onProcessExitIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Call, customTrackerUnloadModule));
300+
// Put the OnProcessExit body inside try/finally to ensure the call to the UnloadModule.
301+
var lastInst = onProcessExitMethod.Body.Instructions.Last();
302+
var firstNullParam = Instruction.Create(OpCodes.Ldnull);
303+
var secondNullParam = Instruction.Create(OpCodes.Ldnull);
304+
var callUnload = Instruction.Create(OpCodes.Call, customTrackerUnloadModule);
305+
onProcessExitIl.InsertAfter(lastInst, firstNullParam);
306+
onProcessExitIl.InsertAfter(firstNullParam, secondNullParam);
307+
onProcessExitIl.InsertAfter(secondNullParam, callUnload);
308+
var ret = onProcessExitIl.Create(OpCodes.Ret);
309+
var leave = onProcessExitIl.Create(OpCodes.Leave, ret);
310+
onProcessExitIl.InsertAfter(callUnload, leave);
311+
onProcessExitIl.InsertAfter(leave, ret);
312+
var handler = new ExceptionHandler(ExceptionHandlerType.Finally)
313+
{
314+
TryStart = onProcessExitIl.Body.Instructions.First(),
315+
TryEnd = firstNullParam,
316+
HandlerStart = firstNullParam,
317+
HandlerEnd = ret
318+
};
319+
320+
onProcessExitMethod.Body.ExceptionHandlers.Add(handler);
304321
}
305322

306323
module.Write(stream, new WriterParameters { WriteSymbols = true });

0 commit comments

Comments
 (0)