@@ -297,10 +297,27 @@ private void InstrumentModule()
297
297
var onProcessExitMethod = new MethodReference ( "OnProcessExit" , module . TypeSystem . Void , appContextType ) . Resolve ( ) ;
298
298
var onProcessExitIl = onProcessExitMethod . Body . GetILProcessor ( ) ;
299
299
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 ) ;
304
321
}
305
322
306
323
module . Write ( stream , new WriterParameters { WriteSymbols = true } ) ;
0 commit comments