From 8102c522e91ab5d58f715b08c79353627cefce29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Tue, 17 Nov 2026 22:55:39 +0100 Subject: [PATCH] Remove COM access from finalizers and release COM objects in host lookup Finalizers run on the finalizer thread, possibly during process exit when the STA is gone (same class of bug as the crash fixed in #98). - Remove the finalizers of VbeCommandBarAdapter, OfficeApplicationHelper, Connect, AddInManager and AccessErrorTrappingObserver; COM objects are only released in Dispose(true) (OnDisconnection/OnBeginShutdown). AccessErrorTrappingObserver restores the error trapping on Dispose only. - ComTools: look up the file moniker in the ROT instead of Marshal.BindToMoniker (no activation of a new Access instance), check the result against the VBE, release non-matching candidates, ROT helper objects and the IUnknown/QueryInterface pointers. - HotKey/HotKeys: unregister hot keys on Dispose instead of in the finalizer (registration is still disabled, issue #78). --- .../Configuration/ErrorTrappingObserver.cs | 21 +- .../Commandbar/VbeCommandBarAdapter.cs | 21 +- source/Common/Common.VBIDETools/HotKey.cs | 20 +- source/Common/Common.VBIDETools/HotKeys.cs | 14 +- .../Common.VBIDETools/Integration/ComTools.cs | 259 +++++++++++++----- .../OfficeApplicationHelper.cs | 21 +- source/Common/Common.VBIDETools/VbeAdapter.cs | 1 + vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs | 24 +- vbe-add-In/AccUnit.VbeAddIn/Connect.cs | 50 ++-- 9 files changed, 284 insertions(+), 147 deletions(-) diff --git a/source/AccUnit/Configuration/ErrorTrappingObserver.cs b/source/AccUnit/Configuration/ErrorTrappingObserver.cs index 59977eb..3d644bc 100644 --- a/source/AccUnit/Configuration/ErrorTrappingObserver.cs +++ b/source/AccUnit/Configuration/ErrorTrappingObserver.cs @@ -78,17 +78,19 @@ protected virtual void Dispose(bool disposing) try { - if (_applicationHelper != null) + // COM calls only on deterministic dispose, never from a finalizer thread: + // if Dispose is not called, the error trapping is not restored. + if (disposing) { - // set the error trapping back to the initial value - if (GetAccessErrorTrapping() != _initialErrorTrapping) + if (_applicationHelper != null) { - SetErrorTrapping(_initialErrorTrapping); + // set the error trapping back to the initial value + if (GetAccessErrorTrapping() != _initialErrorTrapping) + { + SetErrorTrapping(_initialErrorTrapping); + } } - } - if (disposing) - { DisposeManagedResources(); } DisposeUnmanagedResources(); @@ -115,11 +117,6 @@ void DisposeUnmanagedResources() _hostApplication = null; } - ~AccessErrorTrappingObserver() - { - Dispose(false); - } - #endregion } } diff --git a/source/Common/Common.VBIDETools/Commandbar/VbeCommandBarAdapter.cs b/source/Common/Common.VBIDETools/Commandbar/VbeCommandBarAdapter.cs index 132dfc4..45b4c85 100644 --- a/source/Common/Common.VBIDETools/Commandbar/VbeCommandBarAdapter.cs +++ b/source/Common/Common.VBIDETools/Commandbar/VbeCommandBarAdapter.cs @@ -116,8 +116,8 @@ protected virtual void Dispose(bool disposing) if (disposing) { RemoveCommandBarButtonClickHandlers(); + ReleaseVbe(); } - DisposeUnmanagedResources(); _disposed = true; } } @@ -150,10 +150,17 @@ protected void RemoveCommandBarButtonClickHandlers() } } - private void DisposeUnmanagedResources() + /// + /// Only called from Dispose(true): there is no finalizer, because COM objects must not be + /// touched on the finalizer thread (the STA may already be gone during process exit). + /// + private void ReleaseVbe() { using (new BlockLogger()) { + if (VBE is null) + return; + Marshal.ReleaseComObject(VBE); VBE = null; } @@ -165,11 +172,6 @@ public void Dispose() GC.SuppressFinalize(this); } - ~VbeCommandBarAdapter() - { - Dispose(false); - } - #endregion private sealed class CommandBarButtonAndClickHandler : IDisposable @@ -232,11 +234,6 @@ public void Dispose() GC.SuppressFinalize(this); } - ~CommandBarButtonAndClickHandler() - { - Dispose(false); - } - #endregion } } diff --git a/source/Common/Common.VBIDETools/HotKey.cs b/source/Common/Common.VBIDETools/HotKey.cs index 247e521..8715651 100644 --- a/source/Common/Common.VBIDETools/HotKey.cs +++ b/source/Common/Common.VBIDETools/HotKey.cs @@ -4,7 +4,7 @@ namespace AccessCodeLib.Common.VBIDETools { - public class HotKey + public class HotKey : IDisposable { [Flags] public enum ModKeys @@ -50,14 +50,24 @@ public HotKey(ModKeys modKeys, uint key, IntPtr hOwner) public ModKeys Modifiers { get; private set; } public uint Key { get; private set; } - ~HotKey() + bool _disposed; + + /// + /// UnregisterHotKey only works on the thread that registered the hot key, + /// so this must be called on deterministic dispose (not from a finalizer). + /// + public void Dispose() { + if (_disposed) + return; + try { - if ((int)_hwnd != 0) + Pressed = null; + if (_hwnd != IntPtr.Zero) { UnregisterHotKey(_hwnd, HotKeyAtom); - _hwnd = (IntPtr)0; + _hwnd = IntPtr.Zero; } GlobalDeleteAtom(HotKeyAtom); } @@ -65,6 +75,8 @@ public HotKey(ModKeys modKeys, uint key, IntPtr hOwner) { Logger.Log(ex); } + + _disposed = true; } } diff --git a/source/Common/Common.VBIDETools/HotKeys.cs b/source/Common/Common.VBIDETools/HotKeys.cs index 1bddb84..fba6ea7 100644 --- a/source/Common/Common.VBIDETools/HotKeys.cs +++ b/source/Common/Common.VBIDETools/HotKeys.cs @@ -3,7 +3,7 @@ namespace AccessCodeLib.Common.VBIDETools { - public class HotKeys : List + public class HotKeys : List, IDisposable { private readonly IntPtr _hWnd; public HotKeys(IntPtr hWnd) @@ -17,5 +17,17 @@ public HotKey RegisterHotKey(HotKey.ModKeys modKeys, uint key) Add(hotKey); return hotKey; } + + /// + /// Unregisters all hot keys. + /// + public void Dispose() + { + foreach (var hotKey in this) + { + hotKey.Dispose(); + } + Clear(); + } } } \ No newline at end of file diff --git a/source/Common/Common.VBIDETools/Integration/ComTools.cs b/source/Common/Common.VBIDETools/Integration/ComTools.cs index 77e145a..3baf8a1 100644 --- a/source/Common/Common.VBIDETools/Integration/ComTools.cs +++ b/source/Common/Common.VBIDETools/Integration/ComTools.cs @@ -15,6 +15,9 @@ public static class ComTools [DllImport("ole32.dll")] private static extern int CreateBindCtx(uint reserved, out IBindCtx pctx); + [DllImport("ole32.dll")] + private static extern int CreateFileMoniker([MarshalAs(UnmanagedType.LPWStr)] string lpszPathName, out IMoniker ppmk); + private static IRunningObjectTable RunningObjectTable { get @@ -45,12 +48,16 @@ public static object GetOfficeComObjectByProgIDAndVBE(string progID, VBE vbe) if (progID.Equals("Access.Application", StringComparison.CurrentCultureIgnoreCase) && vbe.VBProjects.Count == 1) { var fileName = vbe.ActiveVBProject.FileName; - using (new BlockLogger($"Marshal.BindToMoniker({fileName})")) + using (new BlockLogger($"GetComObjectFromROTByFileName({fileName})")) { - comInstance = Marshal.BindToMoniker(fileName); + comInstance = GetComObjectFromROTByFileName(fileName); if (comInstance != null) { - return comInstance; + if (BelongsToVbe(comInstance, vbe)) + { + return comInstance; + } + ReleaseComObject(comInstance); } } } @@ -73,24 +80,50 @@ public static object GetOfficeComObjectByProgIDAndVBE(string progID, VBE vbe) } } - private static object GetOfficeComObjectByProgIDAndVBEfromFirstObjectInROT(string progID, VBE vbe) + /// + /// Looks up a file moniker in the running object table. + /// + /// + /// Unlike Marshal.BindToMoniker, IRunningObjectTable.GetObject never activates the object, + /// so no new instance of the host application is started if the file is not open. + /// + private static object GetComObjectFromROTByFileName(string fileName) { - var comInstance = Marshal.GetActiveObject(progID); - if (comInstance is null) + if (string.IsNullOrEmpty(fileName)) + return null; + + var runningObjectTable = RunningObjectTable; + if (runningObjectTable is null) return null; + IMoniker fileMoniker = null; try { - var appVbe = comInstance.GetType().InvokeMember("VBE", BindingFlags.GetProperty, null, comInstance, null); - return vbe.Equals(appVbe) ? comInstance : null; + if (CreateFileMoniker(fileName, out fileMoniker) != 0 || fileMoniker is null) + return null; + + return runningObjectTable.GetObject(fileMoniker, out object comInstance) == 0 ? comInstance : null; } - catch (Exception ex) + finally { - Logger.Log(ex); - return null; + ReleaseComObject(fileMoniker); + ReleaseComObject(runningObjectTable); } } + private static object GetOfficeComObjectByProgIDAndVBEfromFirstObjectInROT(string progID, VBE vbe) + { + var comInstance = Marshal.GetActiveObject(progID); + if (comInstance is null) + return null; + + if (BelongsToVbe(comInstance, vbe)) + return comInstance; + + ReleaseComObject(comInstance); + return null; + } + private static object GetOfficeComObjectByProgIDAndVBEfromROT(string progID, VBE vbe) { using (new BlockLogger()) @@ -99,48 +132,141 @@ private static object GetOfficeComObjectByProgIDAndVBEfromROT(string progID, VBE if (runningObjectTable is null) return null; - runningObjectTable.EnumRunning(out IEnumMoniker monikerList); - - var monikerContainer = new IMoniker[1]; - var pointerFetchedMonikers = IntPtr.Zero; - monikerList.Reset(); - while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0) + IEnumMoniker monikerList = null; + try { - CreateBindCtx(0, out IBindCtx binder); + runningObjectTable.EnumRunning(out monikerList); - monikerContainer[0].GetDisplayName(binder, null, out string displayName); - Logger.Log($"displayName: {displayName}"); - - runningObjectTable.GetObject(monikerContainer[0], out object comInstance); - if (GetTypeForComObject(comInstance, progID) is null) continue; - object appVbe; - try - { - appVbe = comInstance.GetType().InvokeMember("VBE", BindingFlags.GetProperty, null, comInstance, null); - } - catch (Exception ex) + var monikerContainer = new IMoniker[1]; + var pointerFetchedMonikers = IntPtr.Zero; + monikerList.Reset(); + while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0) { - Logger.Log($"VBE error => attempt: Application / Error: {ex.Message}"); + var moniker = monikerContainer[0]; + monikerContainer[0] = null; try { - comInstance = comInstance.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, comInstance, null); - // Microsoft Word & Co.: enable option 'Trust access to the VBA project object model'! - appVbe = comInstance.GetType().InvokeMember("VBE", BindingFlags.GetProperty, null, comInstance, null); - Logger.Log($"VBE: {comInstance.GetType()}"); + var comInstance = GetComObjectFromROTIfOfficeApplicationOfVbe(runningObjectTable, moniker, progID, vbe); + if (comInstance != null) + { + Logger.Log($"found: {comInstance}"); + return comInstance; + } } - catch (Exception ex2) + finally { - Logger.Log(ex2); - appVbe = comInstance = null; + ReleaseComObject(moniker); } } + return null; + } + finally + { + ReleaseComObject(monikerList); + ReleaseComObject(runningObjectTable); + } + } + } - if (appVbe is null || !vbe.Equals(appVbe)) continue; + private static object GetComObjectFromROTIfOfficeApplicationOfVbe(IRunningObjectTable runningObjectTable, IMoniker moniker, string progID, VBE vbe) + { + IBindCtx binder = null; + try + { + CreateBindCtx(0, out binder); + moniker.GetDisplayName(binder, null, out string displayName); + Logger.Log($"displayName: {displayName}"); + } + catch (Exception ex) + { + Logger.Log(ex); + } + finally + { + ReleaseComObject(binder); + } - Logger.Log($"found: {comInstance}"); - return comInstance; - } + if (runningObjectTable.GetObject(moniker, out object comInstance) != 0 || comInstance is null) + return null; + + if (GetTypeForComObject(comInstance, progID) is null) + { + ReleaseComObject(comInstance); + return null; + } + + if (BelongsToVbe(comInstance, vbe)) + return comInstance; + + // Microsoft Word & Co.: enable option 'Trust access to the VBA project object model'! + Logger.Log("VBE does not match or is not accessible => attempt: Application"); + object application = null; + try + { + application = comInstance.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, comInstance, null); + } + catch (Exception ex) + { + Logger.Log(ex); + } + finally + { + // each marshalled reference increments the RCW count, so this is balanced + // even if Application returns the same RCW + ReleaseComObject(comInstance); + } + + if (application is null) return null; + + if (BelongsToVbe(application, vbe)) + { + Logger.Log($"VBE: {application.GetType()}"); + return application; + } + + ReleaseComObject(application); + return null; + } + + /// + /// Checks whether the VBE property of the COM object is the given VBE. + /// + private static bool BelongsToVbe(object comInstance, VBE vbe) + { + object appVbe = null; + try + { + appVbe = comInstance.GetType().InvokeMember("VBE", BindingFlags.GetProperty, null, comInstance, null); + return appVbe != null && vbe.Equals(appVbe); + } + catch (Exception ex) + { + Logger.Log(ex); + return false; + } + finally + { + // the matching VBE is the RCW shared with the add-in => do not release it + if (!ReferenceEquals(appVbe, vbe)) + { + ReleaseComObject(appVbe); + } + } + } + + private static void ReleaseComObject(object comObject) + { + if (comObject is null || !Marshal.IsComObject(comObject)) + return; + + try + { + Marshal.ReleaseComObject(comObject); + } + catch (Exception ex) + { + Logger.Log(ex); } } @@ -159,36 +285,43 @@ public static Type GetTypeForComObject(object comObject, string progID) // get the com object and fetch its IUnknown var iunkwn = Marshal.GetIUnknownForObject(comObject); - - // enum all the types defined in the interop assembly - var comAssembly = Assembly.GetAssembly(comType); - var comTypes = comAssembly.GetTypes(); - - using (new BlockLogger("foreach loop, comTypes.Count = " + comTypes.Length)) + try { - // find the first implemented interop type - foreach (var currType in comTypes) + // enum all the types defined in the interop assembly + var comAssembly = Assembly.GetAssembly(comType); + var comTypes = comAssembly.GetTypes(); + + using (new BlockLogger("foreach loop, comTypes.Count = " + comTypes.Length)) { - // get the iid of the current type - var iid = currType.GUID; - if (!currType.IsInterface || iid == Guid.Empty) + // find the first implemented interop type + foreach (var currType in comTypes) { - // com interop type must be an interface with valid iid - continue; - } + // get the iid of the current type + var iid = currType.GUID; + if (!currType.IsInterface || iid == Guid.Empty) + { + // com interop type must be an interface with valid iid + continue; + } - // query supportability of current interface on object - Marshal.QueryInterface(iunkwn, ref iid, out IntPtr ipointer); + // query supportability of current interface on object + Marshal.QueryInterface(iunkwn, ref iid, out IntPtr ipointer); - if (ipointer != IntPtr.Zero) - { - // yeah, that’s the one we’re after - return currType; + if (ipointer != IntPtr.Zero) + { + Marshal.Release(ipointer); + // yeah, that’s the one we’re after + return currType; + } } } + // no implemented type found + return null; + } + finally + { + Marshal.Release(iunkwn); } - // no implemented type found - return null; } } diff --git a/source/Common/Common.VBIDETools/OfficeApplicationHelper.cs b/source/Common/Common.VBIDETools/OfficeApplicationHelper.cs index 9e33c54..8ce15b9 100644 --- a/source/Common/Common.VBIDETools/OfficeApplicationHelper.cs +++ b/source/Common/Common.VBIDETools/OfficeApplicationHelper.cs @@ -138,17 +138,17 @@ protected virtual void Dispose(bool disposing) _invocationHelper.Dispose(); _invocationHelper = null; } - } - if (_application != null) - { - if (_releaseApplicationComObjectOnDispose) + // COM release only on deterministic dispose, never from the finalizer thread + if (_application != null) { - Marshal.ReleaseComObject(_application); + if (_releaseApplicationComObjectOnDispose) + { + Marshal.ReleaseComObject(_application); + } + _application = null; } - _application = null; - } - + } } catch (Exception ex) { @@ -169,11 +169,6 @@ public void Dispose() GC.SuppressFinalize(this); } - ~OfficeApplicationHelper() - { - Dispose(false); - } - #endregion } diff --git a/source/Common/Common.VBIDETools/VbeAdapter.cs b/source/Common/Common.VBIDETools/VbeAdapter.cs index 4074de2..2a604e7 100644 --- a/source/Common/Common.VBIDETools/VbeAdapter.cs +++ b/source/Common/Common.VBIDETools/VbeAdapter.cs @@ -112,6 +112,7 @@ private int NewWndProc(IntPtr hWnd, int wMsg, int wParam, int lParam) } } + // when re-enabled: call HotKeys.Dispose() in DisposeManagedResources (unregisters the hot keys) public HotKeys HotKeys { get; private set; } private void CheckHotKeys(int wParam) diff --git a/vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs b/vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs index c0c91e1..e78a6a4 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/AddInManager.cs @@ -419,6 +419,7 @@ protected virtual void Dispose(bool disposing) { if (_disposed) return; + // COM objects are only released on deterministic dispose, never from a finalizer thread if (disposing) { try @@ -429,15 +430,15 @@ protected virtual void Dispose(bool disposing) { Logger.Log(ex); } - } - try - { - DisposeUnmanagedResources(); - } - catch (Exception ex) - { - Logger.Log(ex); + try + { + DisposeUnmanagedResources(); + } + catch (Exception ex) + { + Logger.Log(ex); + } } _disposed = true; @@ -524,13 +525,6 @@ public void Dispose() } } - ~AddInManager() - { - Logger.Log("~AddInManager"); - Dispose(false); - Logger.Log("~AddInManager completed"); - } - #endregion } } diff --git a/vbe-add-In/AccUnit.VbeAddIn/Connect.cs b/vbe-add-In/AccUnit.VbeAddIn/Connect.cs index bd18a00..c6a01d0 100644 --- a/vbe-add-In/AccUnit.VbeAddIn/Connect.cs +++ b/vbe-add-In/AccUnit.VbeAddIn/Connect.cs @@ -179,37 +179,40 @@ protected virtual void Dispose(bool disposing) return; } - try - { - _addInInstance.Object = null; - } - catch (Exception ex) - { - Logger.Log(ex); - } - + // COM objects are only touched on deterministic dispose (OnDisconnection/OnBeginShutdown). + // There is no finalizer: during process exit the STA may already be gone. if (disposing) { Logger.Log("disposing == true"); + + try + { + _addInInstance.Object = null; + } + catch (Exception ex) + { + Logger.Log(ex); + } + if (AddInManager != null) { Logger.Log("Start AddInManager.Dispose ..."); AddInManager.Dispose(); AddInManager = null; } - } - if (_addInInstance != null) - { - Logger.Log("Start Marshal.ReleaseComObject(_addInInstance) ..."); - Marshal.ReleaseComObject(_addInInstance); - _addInInstance = null; + if (_addInInstance != null) + { + Logger.Log("Start Marshal.ReleaseComObject(_addInInstance) ..."); + Marshal.ReleaseComObject(_addInInstance); + _addInInstance = null; + } + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + GC.WaitForPendingFinalizers(); } - - GC.Collect(); - GC.WaitForPendingFinalizers(); - GC.Collect(); - GC.WaitForPendingFinalizers(); _disposed = true; @@ -223,13 +226,6 @@ public void Dispose() GC.SuppressFinalize(this); } - ~Connect() - { - Logger.Log("~Connect"); - Dispose(false); - Logger.Log("~Connect completed"); - } - #endregion } }