Crash when MAPIUninitialize was not called before FreeLibrary of OLMAPI32.DLL | Joachim De Zutter
January 2017

Environment:
Microsoft Office 2016 1611 (Build 7571.2109) (32-bit)
Windows 10 Pro (64-bit)
OLMAPI32.DLL C:\Program Files (x86)\Microsoft Office\root\Office16\OLMAPI32.DLL 16.00.7571.6556 29.12.2016 2:33
JitV.dll C:\Program Files (x86)\Microsoft Office\root\Office16\JitV.dll 29.12.2016 0:51

Code which loads OLMAPI32.DLL and calls MAPIInitialize(0) and then does not call MAPIUninitialize() before a call to FreeLibrary with the OLMAPI32.DLL handle (or ExitProcess) causes a crash which looks like:

Exception thrown at 0x...EE37 in ...: 0xC0000005: Access violation executing location 0x...EE37
Problem signature:
...
P4: olmapi32.dll_unloaded
P5: 16.0.7571.6556
...
P7: 0007ee37
P8: c0000005

The crash is not reproducible when calling MAPIInitialize like this:

MAPIINIT_0 MAPIINIT = { 0, MAPI_MULTITHREAD_NOTIFICATIONS}
MAPIInitialize (&MAPIINIT);

There's an invisible window with these properties:
Caption: "W"
Class name: "WMS Notif Engine:Dispatch Window Class"
WindowProc: OLMAPI32.dll+0x7ee37

The call stack at the time of the crash looks more or less like:

user32.dll!__InternalCallWinProc@20
user32.dll!UserCallWinProcCheckWow()
user32.dll!DispatchMessageWorker()
user32.dll!_DispatchMessageW@4()
376d01ba()
JitV.dll + 0x51a7()
376D01B0 8B FF                mov         edi,edi  
376D01B2 55                   push        ebp  
376D01B3 8B EC                mov         ebp,esp  
376D01B5 E9 DB DD 98 3D       jmp         _DispatchMessageW@4+5h (7505DF95h)
0x566C2344: 0x376D01B0

JitV.DLL + 0x519A (the crash happens during execution of the line in bold):
JitV.DLL + 0x519A E8 52 0B 00 00       call        566A5CF1
JitV.DLL + 0x519F 5F                   pop         edi  
JitV.DLL + 0x51A0 56                   push        esi ; ESI points to a MSG structure containing the handle of "WMS Notif Engine:Dispatch Window Class"
JitV.DLL + 0x51A1 FF 15 44 23 6C 56    call        dword ptr ds:[566C2344h]
JitV.DLL + 0x51A7 8B F0                mov         esi,eax  
JitV.DLL + 0x51A9 84 DB                test        bl,bl  
JitV.DLL + 0x51AB 74 05                je          54EA51B2  
JitV.DLL + 0x51AD E8 33 0B 00 00       call        54EA5CE5  
JitV.DLL + 0x51B2 8B C6                mov         eax,esi  
JitV.DLL + 0x51B4 5E                   pop         esi  
JitV.DLL + 0x51B5 5B                   pop         ebx  
JitV.DLL + 0x51B6 8B E5                mov         esp,ebp  
JitV.DLL + 0x51B8 5D                   pop         ebp  
JitV.DLL + 0x51B9 C2 04 00             ret         4
MSG structure:
typedef struct tagMSG {
  HWND   hwnd;
  UINT   message;
  WPARAM wParam;
  LPARAM lParam;
  DWORD  time;
  POINT  pt;
} MSG, *PMSG, *LPMSG;