From d4803b80970369c26479f9563cbeda7419ba5d39 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Fri, 20 Nov 2026 22:54:49 -0600 Subject: [PATCH 01/11] Fix duplicate module IDs in error events --- .../Extensions/ToErrorModelExtensions.cs | 64 ++++++----- .../Plugins/020_ErrorPluginTests.cs | 107 ++++++++++++++++++ 2 files changed, 140 insertions(+), 31 deletions(-) diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index fcc6a350..e8c663ca 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -1,10 +1,10 @@ using System; using System.Collections; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; using System.Security; using Exceptionless.Dependency; using Exceptionless.Extensions; @@ -16,7 +16,7 @@ namespace Exceptionless { internal static class ToErrorModelExtensions { - private static readonly ConcurrentDictionary _moduleCache = new ConcurrentDictionary(); + private static readonly ConditionalWeakTable _moduleMetadata = new ConditionalWeakTable(); private static readonly string[] _exceptionExclusions = { "@exceptionless", "Data", "HelpLink", "ExceptionContext", "InnerExceptions", "InnerException", "Errors", "Types", "Message", "Source", "StackTrace", "TargetSite", "HResult", @@ -35,10 +35,11 @@ public static Error ToErrorModel(this Exception exception, ExceptionlessClient c if (client == null) client = ExceptionlessClient.Default; - return ToErrorModelInternal(exception, client); + var moduleIds = client.Configuration.IncludeModules ? new Dictionary() : null; + return ToErrorModelInternal(exception, client, moduleIds); } - private static Error ToErrorModelInternal(Exception exception, ExceptionlessClient client, bool isInner = false) { + private static Error ToErrorModelInternal(Exception exception, ExceptionlessClient client, Dictionary moduleIds, bool isInner = false) { var log = client.Configuration.Resolver.GetLog(); Type type = exception.GetType(); string typeName = type.GetTypeDisplayName(); @@ -48,10 +49,10 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie Type = typeName }; - if (!isInner && client.Configuration.IncludeModules) - error.Modules = GetLoadedModules(log); + if (!isInner && moduleIds != null) + error.Modules = GetLoadedModules(log, moduleIds: moduleIds); - error.PopulateStackTrace(error, exception, log); + error.PopulateStackTrace(exception, log, moduleIds); try { PropertyInfo info = type.GetProperty("HResult", BindingFlags.Public | BindingFlags.Instance); @@ -65,7 +66,7 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie try { if (exception.TargetSite != null) { error.TargetMethod = new Method(); - error.TargetMethod.PopulateMethod(error, exception.TargetSite); + error.TargetMethod.PopulateMethod(exception.TargetSite, moduleIds); } } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating TargetMethod: " + ex.Message); @@ -116,7 +117,7 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie } if (exception.InnerException != null) - error.Inner = ToErrorModelInternal(exception.InnerException, client, true); + error.Inner = ToErrorModelInternal(exception.InnerException, client, moduleIds, isInner: true); return error; } @@ -145,7 +146,7 @@ private static string GetMessage(this Exception exception, string typeName) { return !String.IsNullOrEmpty(message) ? message : defaultMessage; } - internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem = false, bool includeDynamic = false) { + internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem = false, bool includeDynamic = false, Dictionary moduleIds = null) { var modules = new ModuleCollection(); try { int id = 1; @@ -178,6 +179,7 @@ internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool in var module = assembly.ToModuleInfo(); module.ModuleId = id; modules.Add(module); + moduleIds?.Add(assembly, id); id++; } @@ -188,7 +190,7 @@ internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool in return modules; } - private static void PopulateStackTrace(this Error error, Error root, Exception exception, IExceptionlessLog log) { + private static void PopulateStackTrace(this Error error, Exception exception, IExceptionlessLog log, Dictionary moduleIds) { StackFrame[] frames = null; try { var st = new EnhancedStackTrace(exception); @@ -220,7 +222,7 @@ private static void PopulateStackTrace(this Error error, Error root, Exception e } try { - stackFrame.PopulateMethod(root, frame.GetMethod()); + stackFrame.PopulateMethod(frame.GetMethod(), moduleIds); } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating StackFrame method info: " + ex.Message); } @@ -229,7 +231,7 @@ private static void PopulateStackTrace(this Error error, Error root, Exception e } } - private static void PopulateMethod(this Method method, Error root, MethodBase methodBase) { + private static void PopulateMethod(this Method method, MethodBase methodBase, Dictionary moduleIds) { if (methodBase == null) return; @@ -267,16 +269,7 @@ private static void PopulateMethod(this Method method, Error root, MethodBase me method.Parameters.Add(parm); } - method.ModuleId = GetModuleId(root, methodBase.Module); - } - - private static int GetModuleId(Error root, System.Reflection.Module module) { - foreach (Module mod in root.Modules) { - if (module.Assembly.FullName.StartsWith(mod.Name, StringComparison.OrdinalIgnoreCase)) - return mod.ModuleId; - } - - return -1; + method.ModuleId = moduleIds != null && moduleIds.TryGetValue(methodBase.Module.Assembly, out int moduleId) ? moduleId : -1; } public static Module ToModuleInfo(this System.Reflection.Module module) { @@ -287,11 +280,11 @@ public static Module ToModuleInfo(this Assembly assembly) { if (assembly == null) return null; - return _moduleCache.GetOrAdd(assembly.FullName, k => { + var metadata = _moduleMetadata.GetValue(assembly, a => { var mod = new Module(); - var name = assembly.GetAssemblyName(); - string infoVersion = assembly.GetInformationalVersion(); - string fileVersion = assembly.GetFileVersion(); + var name = a.GetAssemblyName(); + string infoVersion = a.GetInformationalVersion(); + string fileVersion = a.GetFileVersion(); if (name != null) { mod.Name = name.Name; @@ -311,19 +304,28 @@ public static Module ToModuleInfo(this Assembly assembly) { if (!String.IsNullOrEmpty(fileVersion) && fileVersion != mod.Version) mod.Data["FileVersion"] = fileVersion; - DateTime? creationTime = assembly.GetCreationTime(); + DateTime? creationTime = a.GetCreationTime(); if (creationTime.HasValue) mod.CreatedDate = creationTime.Value; - DateTime? lastWriteTime = assembly.GetLastWriteTime(); + DateTime? lastWriteTime = a.GetLastWriteTime(); if (lastWriteTime.HasValue) mod.ModifiedDate = lastWriteTime.Value; - if (assembly == Assembly.GetEntryAssembly()) + if (a == Assembly.GetEntryAssembly()) mod.IsEntry = true; return mod; }); + + return new Module { + Name = metadata.Name, + Version = metadata.Version, + IsEntry = metadata.IsEntry, + CreatedDate = metadata.CreatedDate, + ModifiedDate = metadata.ModifiedDate, + Data = new DataDictionary(metadata.Data) + }; } } -} \ No newline at end of file +} diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index e0610a50..0eabc882 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -1,6 +1,16 @@ using System; using System.Collections; using System.Collections.Generic; +#if NET10_0 +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Runtime.Loader; +using Exceptionless.Dependency; +using Exceptionless.Extensions; +#endif using Exceptionless.Plugins; using Exceptionless.Plugins.Default; using Exceptionless.Models; @@ -11,6 +21,103 @@ namespace Exceptionless.Tests.Plugins { public class ErrorPluginTests : PluginTestBase { public ErrorPluginTests(ITestOutputHelper output) : base(output) { } +#if NET10_0 + private const string ModuleFixtureType = "ModuleIdFixture"; + private const string ModuleFixtureMethod = "Throw"; + + [Fact] + public void WillMapDuplicateAssemblyIdentitiesToDistinctEventModules() { + var directory = Directory.CreateTempSubdirectory(); + WeakReference outerContext = null; + WeakReference innerContext = null; + + try { + VerifyModuleMappings(directory.FullName, out outerContext, out innerContext); + } finally { + // Windows can hold the assembly files open until the collectible contexts are released. + if (OperatingSystem.IsWindows()) { + for (int i = 0; i < 10 && (outerContext?.IsAlive == true || innerContext?.IsAlive == true); i++) { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + } + + directory.Delete(recursive: true); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private void VerifyModuleMappings(string directory, out WeakReference outerContextReference, out WeakReference innerContextReference) { + const string assemblyName = "Exceptionless.ModuleIdRegressionFixture"; + const string outerVersion = "1.0.1.0"; + const string innerVersion = "1.0.2.0"; + var outerContext = new AssemblyLoadContext("Outer module fixture", isCollectible: true); + var innerContext = new AssemblyLoadContext("Inner module fixture", isCollectible: true); + outerContextReference = new WeakReference(outerContext, trackResurrection: true); + innerContextReference = new WeakReference(innerContext, trackResurrection: true); + + try { + string outerPath = Path.Combine(directory, "outer.dll"); + string innerPath = Path.Combine(directory, "inner.dll"); + WriteThrowingAssembly(outerPath, assemblyName, outerVersion); + WriteThrowingAssembly(innerPath, assemblyName, innerVersion); + + var outerAssembly = outerContext.LoadFromAssemblyPath(outerPath); + var innerAssembly = innerContext.LoadFromAssemblyPath(innerPath); + Assert.Equal(outerAssembly.FullName, innerAssembly.FullName); + Assert.NotSame(outerAssembly, innerAssembly); + + var throwOuter = outerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate>(); + var throwInner = innerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate>(); + var inner = Record.Exception(() => throwInner(null)); + var outer = Record.Exception(() => throwOuter(inner)); + + using var client = CreateClient(c => c.IncludeModules = true); + var context = new EventPluginContext(client, new Event()); + context.ContextData.SetException(outer); + new ErrorPlugin().Run(context); + var serializer = client.Configuration.Resolver.GetJsonSerializer(); + string json = serializer.Serialize(context.Event); + var error = serializer.Deserialize(json).GetError(serializer); + + Assert.Equal(error.Modules.Count, error.Modules.Select(m => m.ModuleId).Distinct().Count()); + var fixtureModules = error.Modules.Where(m => m.Name == assemblyName).ToList(); + Assert.Equal(2, fixtureModules.Count); + var outerModule = Assert.Single(fixtureModules, m => m.Version == outerVersion); + var innerModule = Assert.Single(fixtureModules, m => m.Version == innerVersion); + Assert.True(outerModule.ModuleId > 0); + Assert.True(innerModule.ModuleId > 0); + Assert.Equal(outerModule.ModuleId, Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId); + Assert.Equal(innerModule.ModuleId, Assert.Single(error.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId); + + var nextError = Record.Exception(() => throwOuter(null)).ToErrorModel(client); + var originalModule = Assert.Single(context.Event.GetError().Modules, m => m.ModuleId == outerModule.ModuleId); + var nextModule = Assert.Single(nextError.Modules, m => m.Name == assemblyName && m.Version == outerVersion); + Assert.NotSame(originalModule, nextModule); + Assert.NotSame(originalModule.Data, nextModule.Data); + } finally { + innerContext.Unload(); + outerContext.Unload(); + } + } + + private static void WriteThrowingAssembly(string path, string name, string fileVersion) { + var assembly = new PersistedAssemblyBuilder(new AssemblyName(name) { Version = new Version(1, 0, 0, 0) }, typeof(object).Assembly); + var versionConstructor = typeof(AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) }); + assembly.SetCustomAttribute(new CustomAttributeBuilder(versionConstructor, new object[] { fileVersion })); + var type = assembly.DefineDynamicModule(name).DefineType(ModuleFixtureType, TypeAttributes.Public); + var method = type.DefineMethod(ModuleFixtureMethod, MethodAttributes.Public | MethodAttributes.Static, typeof(void), new[] { typeof(Exception) }); + method.SetImplementationFlags(MethodImplAttributes.NoInlining); + var il = method.GetILGenerator(); + il.Emit(OpCodes.Ldstr, "Synthetic module exception"); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Newobj, typeof(InvalidOperationException).GetConstructor(new[] { typeof(string), typeof(Exception) })); + il.Emit(OpCodes.Throw); + type.CreateType(); + assembly.Save(path); + } +#endif + [Fact] public void WillPreserveLineBreaks() { const string message = "Test\r\nLine\r\n\tBreaks"; From 0f76250858542b060c79178f377056c2ee2cc151 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Wed, 25 Nov 2026 08:47:06 -0800 Subject: [PATCH 02/11] Scope assembly references to a single error conversion --- .../Extensions/ReflectionExtensions.cs | 22 +---- .../Extensions/ToErrorModelExtensions.cs | 86 +++++++------------ .../Plugins/020_ErrorPluginTests.cs | 49 ++++++----- 3 files changed, 63 insertions(+), 94 deletions(-) diff --git a/src/Exceptionless/Extensions/ReflectionExtensions.cs b/src/Exceptionless/Extensions/ReflectionExtensions.cs index bd3715ae..80e35acc 100644 --- a/src/Exceptionless/Extensions/ReflectionExtensions.cs +++ b/src/Exceptionless/Extensions/ReflectionExtensions.cs @@ -1,6 +1,4 @@ -using System; -using System.IO; -using System.Reflection; +using System.Reflection; namespace Exceptionless { internal static class ReflectionExtensions { @@ -12,22 +10,6 @@ public static AssemblyName GetAssemblyName(this Assembly assembly) { return new AssemblyName(assembly.FullName); } - public static DateTime? GetCreationTime(this Assembly assembly) { - try { - return File.GetCreationTimeUtc(assembly.Location); - } catch {} - - return null; - } - - public static DateTime? GetLastWriteTime(this Assembly assembly) { - try { - return File.GetLastWriteTimeUtc(assembly.Location); - } catch {} - - return null; - } - public static string GetVersion(this Assembly assembly) { var attr = assembly.GetCustomAttribute(typeof(AssemblyVersionAttribute)) as AssemblyVersionAttribute; if (attr != null) @@ -51,4 +33,4 @@ public static string GetCompany(this Assembly assembly) { return attr != null ? attr.Company : null; } } -} \ No newline at end of file +} diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index e8c663ca..e8e8b96c 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -2,9 +2,9 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; using System.Reflection; -using System.Runtime.CompilerServices; using System.Security; using Exceptionless.Dependency; using Exceptionless.Extensions; @@ -16,7 +16,6 @@ namespace Exceptionless { internal static class ToErrorModelExtensions { - private static readonly ConditionalWeakTable _moduleMetadata = new ConditionalWeakTable(); private static readonly string[] _exceptionExclusions = { "@exceptionless", "Data", "HelpLink", "ExceptionContext", "InnerExceptions", "InnerException", "Errors", "Types", "Message", "Source", "StackTrace", "TargetSite", "HResult", @@ -162,21 +161,22 @@ internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool in log.Error(typeof(ExceptionlessClient), ex, message); } + var name = assembly.GetAssemblyName(); + var token = name?.GetPublicKeyToken(); + string publicKeyToken = token?.Length > 0 ? token.ToHex() : null; if (!includeSystem) { try { - string publicKeyToken = assembly.GetAssemblyName().GetPublicKeyToken().ToHex(); if (_msPublicKeyTokens.Contains(publicKeyToken)) continue; - var attrs = assembly.GetCustomAttributes(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute)).ToList(); - if (attrs.Count > 0) + if (assembly.IsDefined(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), inherit: false)) continue; } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error while checking if assembly " + assembly.FullName + " should be added to modules:" + ex.Message); } } - var module = assembly.ToModuleInfo(); + var module = CreateModule(assembly, name, publicKeyToken); module.ModuleId = id; modules.Add(module); moduleIds?.Add(assembly, id); @@ -272,60 +272,38 @@ private static void PopulateMethod(this Method method, MethodBase methodBase, Di method.ModuleId = moduleIds != null && moduleIds.TryGetValue(methodBase.Module.Assembly, out int moduleId) ? moduleId : -1; } - public static Module ToModuleInfo(this System.Reflection.Module module) { - return ToModuleInfo(module.Assembly); - } - - public static Module ToModuleInfo(this Assembly assembly) { - if (assembly == null) - return null; - - var metadata = _moduleMetadata.GetValue(assembly, a => { - var mod = new Module(); - var name = a.GetAssemblyName(); - string infoVersion = a.GetInformationalVersion(); - string fileVersion = a.GetFileVersion(); - - if (name != null) { - mod.Name = name.Name; - mod.Version = infoVersion ?? fileVersion ?? name.Version.ToString(); - byte[] pkt = name.GetPublicKeyToken(); - if (pkt.Length > 0) - mod.Data["PublicKeyToken"] = pkt.ToHex(); - - var version = name.Version.ToString(); - if (!String.IsNullOrEmpty(version) && version != mod.Version) - mod.Data["Version"] = name.Version.ToString(); - } - - if (!String.IsNullOrEmpty(infoVersion) && infoVersion != mod.Version) - mod.Data["ProductVersion"] = infoVersion; + private static Module CreateModule(Assembly assembly, AssemblyName name, string publicKeyToken) { + var mod = new Module(); + string infoVersion = assembly.GetInformationalVersion(); + string fileVersion = assembly.GetFileVersion(); - if (!String.IsNullOrEmpty(fileVersion) && fileVersion != mod.Version) - mod.Data["FileVersion"] = fileVersion; + if (name != null) { + mod.Name = name.Name; + mod.Version = infoVersion ?? fileVersion ?? name.Version.ToString(); + if (publicKeyToken != null) + mod.Data["PublicKeyToken"] = publicKeyToken; - DateTime? creationTime = a.GetCreationTime(); - if (creationTime.HasValue) - mod.CreatedDate = creationTime.Value; + var version = name.Version.ToString(); + if (!String.IsNullOrEmpty(version) && version != mod.Version) + mod.Data["Version"] = version; + } - DateTime? lastWriteTime = a.GetLastWriteTime(); - if (lastWriteTime.HasValue) - mod.ModifiedDate = lastWriteTime.Value; + if (!String.IsNullOrEmpty(infoVersion) && infoVersion != mod.Version) + mod.Data["ProductVersion"] = infoVersion; - if (a == Assembly.GetEntryAssembly()) - mod.IsEntry = true; + if (!String.IsNullOrEmpty(fileVersion) && fileVersion != mod.Version) + mod.Data["FileVersion"] = fileVersion; - return mod; - }); + try { + var file = new FileInfo(assembly.Location); + mod.ModifiedDate = file.LastWriteTimeUtc; + mod.CreatedDate = file.CreationTimeUtc; + } catch { + // Some assemblies have no accessible file timestamps. + } - return new Module { - Name = metadata.Name, - Version = metadata.Version, - IsEntry = metadata.IsEntry, - CreatedDate = metadata.CreatedDate, - ModifiedDate = metadata.ModifiedDate, - Data = new DataDictionary(metadata.Data) - }; + mod.IsEntry = assembly == Assembly.GetEntryAssembly(); + return mod; } } } diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index 0eabc882..b4fea5da 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -25,29 +25,34 @@ public ErrorPluginTests(ITestOutputHelper output) : base(output) { } private const string ModuleFixtureType = "ModuleIdFixture"; private const string ModuleFixtureMethod = "Throw"; - [Fact] - public void WillMapDuplicateAssemblyIdentitiesToDistinctEventModules() { + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WillMapDuplicateAssemblyIdentitiesToDistinctEventModules(bool loadSameFile) { var directory = Directory.CreateTempSubdirectory(); WeakReference outerContext = null; WeakReference innerContext = null; + Event capturedEvent; try { - VerifyModuleMappings(directory.FullName, out outerContext, out innerContext); + capturedEvent = VerifyModuleMappings(directory.FullName, loadSameFile, out outerContext, out innerContext); } finally { - // Windows can hold the assembly files open until the collectible contexts are released. - if (OperatingSystem.IsWindows()) { - for (int i = 0; i < 10 && (outerContext?.IsAlive == true || innerContext?.IsAlive == true); i++) { - GC.Collect(); - GC.WaitForPendingFinalizers(); - } + for (int i = 0; i < 10 && (outerContext?.IsAlive == true || innerContext?.IsAlive == true); i++) { + GC.Collect(); + GC.WaitForPendingFinalizers(); } directory.Delete(recursive: true); } + + Assert.False(outerContext.IsAlive); + Assert.False(innerContext.IsAlive); + // A queued event can outlive the assemblies that produced its stack frames. + GC.KeepAlive(capturedEvent); } [MethodImpl(MethodImplOptions.NoInlining)] - private void VerifyModuleMappings(string directory, out WeakReference outerContextReference, out WeakReference innerContextReference) { + private Event VerifyModuleMappings(string directory, bool loadSameFile, out WeakReference outerContextReference, out WeakReference innerContextReference) { const string assemblyName = "Exceptionless.ModuleIdRegressionFixture"; const string outerVersion = "1.0.1.0"; const string innerVersion = "1.0.2.0"; @@ -58,9 +63,10 @@ private void VerifyModuleMappings(string directory, out WeakReference outerConte try { string outerPath = Path.Combine(directory, "outer.dll"); - string innerPath = Path.Combine(directory, "inner.dll"); + string innerPath = loadSameFile ? outerPath : Path.Combine(directory, "inner.dll"); WriteThrowingAssembly(outerPath, assemblyName, outerVersion); - WriteThrowingAssembly(innerPath, assemblyName, innerVersion); + if (!loadSameFile) + WriteThrowingAssembly(innerPath, assemblyName, innerVersion); var outerAssembly = outerContext.LoadFromAssemblyPath(outerPath); var innerAssembly = innerContext.LoadFromAssemblyPath(innerPath); @@ -83,18 +89,21 @@ private void VerifyModuleMappings(string directory, out WeakReference outerConte Assert.Equal(error.Modules.Count, error.Modules.Select(m => m.ModuleId).Distinct().Count()); var fixtureModules = error.Modules.Where(m => m.Name == assemblyName).ToList(); Assert.Equal(2, fixtureModules.Count); - var outerModule = Assert.Single(fixtureModules, m => m.Version == outerVersion); - var innerModule = Assert.Single(fixtureModules, m => m.Version == innerVersion); - Assert.True(outerModule.ModuleId > 0); - Assert.True(innerModule.ModuleId > 0); - Assert.Equal(outerModule.ModuleId, Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId); - Assert.Equal(innerModule.ModuleId, Assert.Single(error.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId); + int outerId = Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + int innerId = Assert.Single(error.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + Assert.True(outerId > 0); + Assert.True(innerId > 0); + Assert.NotEqual(outerId, innerId); + Assert.Equal(outerVersion, Assert.Single(fixtureModules, m => m.ModuleId == outerId).Version); + Assert.Equal(loadSameFile ? outerVersion : innerVersion, Assert.Single(fixtureModules, m => m.ModuleId == innerId).Version); var nextError = Record.Exception(() => throwOuter(null)).ToErrorModel(client); - var originalModule = Assert.Single(context.Event.GetError().Modules, m => m.ModuleId == outerModule.ModuleId); - var nextModule = Assert.Single(nextError.Modules, m => m.Name == assemblyName && m.Version == outerVersion); + var originalModule = Assert.Single(context.Event.GetError().Modules, m => m.ModuleId == outerId); + int nextId = Assert.Single(nextError.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + var nextModule = Assert.Single(nextError.Modules, m => m.ModuleId == nextId); Assert.NotSame(originalModule, nextModule); Assert.NotSame(originalModule.Data, nextModule.Data); + return context.Event; } finally { innerContext.Unload(); outerContext.Unload(); From 983d00cbd2548c9c190f6c0d1491395e9e6deb1f Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Wed, 25 Nov 2026 09:08:16 -0800 Subject: [PATCH 03/11] Bound cached module metadata and preserve loader behavior --- .../Extensions/ReflectionExtensions.cs | 22 +- .../Extensions/ToErrorModelExtensions.cs | 120 ++++++++-- .../Plugins/020_ErrorPluginTests.cs | 224 +++++++++++++----- 3 files changed, 277 insertions(+), 89 deletions(-) diff --git a/src/Exceptionless/Extensions/ReflectionExtensions.cs b/src/Exceptionless/Extensions/ReflectionExtensions.cs index 80e35acc..bd3715ae 100644 --- a/src/Exceptionless/Extensions/ReflectionExtensions.cs +++ b/src/Exceptionless/Extensions/ReflectionExtensions.cs @@ -1,4 +1,6 @@ -using System.Reflection; +using System; +using System.IO; +using System.Reflection; namespace Exceptionless { internal static class ReflectionExtensions { @@ -10,6 +12,22 @@ public static AssemblyName GetAssemblyName(this Assembly assembly) { return new AssemblyName(assembly.FullName); } + public static DateTime? GetCreationTime(this Assembly assembly) { + try { + return File.GetCreationTimeUtc(assembly.Location); + } catch {} + + return null; + } + + public static DateTime? GetLastWriteTime(this Assembly assembly) { + try { + return File.GetLastWriteTimeUtc(assembly.Location); + } catch {} + + return null; + } + public static string GetVersion(this Assembly assembly) { var attr = assembly.GetCustomAttribute(typeof(AssemblyVersionAttribute)) as AssemblyVersionAttribute; if (attr != null) @@ -33,4 +51,4 @@ public static string GetCompany(this Assembly assembly) { return attr != null ? attr.Company : null; } } -} +} \ No newline at end of file diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index e8e8b96c..6737ab5e 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -1,8 +1,8 @@ using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using System.Linq; using System.Reflection; using System.Security; @@ -16,6 +16,9 @@ namespace Exceptionless { internal static class ToErrorModelExtensions { + private const int MaxCachedModules = 512; + private static readonly ConcurrentDictionary _moduleCache = new ConcurrentDictionary(StringComparer.Ordinal); + private static readonly Queue _cachedPaths = new Queue(); private static readonly string[] _exceptionExclusions = { "@exceptionless", "Data", "HelpLink", "ExceptionContext", "InnerExceptions", "InnerException", "Errors", "Types", "Message", "Source", "StackTrace", "TargetSite", "HResult", @@ -49,7 +52,7 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie }; if (!isInner && moduleIds != null) - error.Modules = GetLoadedModules(log, moduleIds: moduleIds); + error.Modules = GetLoadedModules(log, false, false, moduleIds); error.PopulateStackTrace(exception, log, moduleIds); @@ -145,7 +148,11 @@ private static string GetMessage(this Exception exception, string typeName) { return !String.IsNullOrEmpty(message) ? message : defaultMessage; } - internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem = false, bool includeDynamic = false, Dictionary moduleIds = null) { + internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem = false, bool includeDynamic = false) { + return GetLoadedModules(log, includeSystem, includeDynamic, null); + } + + private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem, bool includeDynamic, Dictionary moduleIds) { var modules = new ModuleCollection(); try { int id = 1; @@ -153,30 +160,34 @@ internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool in if (!includeDynamic && assembly.IsDynamic) continue; + string path = null; try { - if (!includeDynamic && String.IsNullOrEmpty(assembly.Location)) - continue; + if (!includeDynamic) { + path = assembly.Location; + if (String.IsNullOrEmpty(path)) + continue; + } } catch (SecurityException ex) { const string message = "An error occurred while getting the Assembly.Location value. This error will occur when when you are not running under full trust."; log.Error(typeof(ExceptionlessClient), ex, message); } - var name = assembly.GetAssemblyName(); - var token = name?.GetPublicKeyToken(); - string publicKeyToken = token?.Length > 0 ? token.ToHex() : null; if (!includeSystem) { try { + string publicKeyToken = assembly.GetAssemblyName().GetPublicKeyToken().ToHex(); if (_msPublicKeyTokens.Contains(publicKeyToken)) continue; - if (assembly.IsDefined(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), inherit: false)) + var attrs = assembly.GetCustomAttributes(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute)).ToList(); + if (attrs.Count > 0) continue; } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error while checking if assembly " + assembly.FullName + " should be added to modules:" + ex.Message); } } - var module = CreateModule(assembly, name, publicKeyToken); + // A single large inventory must not evict every entry on each error. + var module = ToModuleInfo(assembly, path, cacheMetadata: id <= MaxCachedModules); module.ModuleId = id; modules.Add(module); moduleIds?.Add(assembly, id); @@ -272,20 +283,86 @@ private static void PopulateMethod(this Method method, MethodBase methodBase, Di method.ModuleId = moduleIds != null && moduleIds.TryGetValue(methodBase.Module.Assembly, out int moduleId) ? moduleId : -1; } - private static Module CreateModule(Assembly assembly, AssemblyName name, string publicKeyToken) { + public static Module ToModuleInfo(this System.Reflection.Module module) { + return ToModuleInfo(module.Assembly); + } + + public static Module ToModuleInfo(this Assembly assembly) { + return ToModuleInfo(assembly, null, cacheMetadata: true); + } + + private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMetadata) { + if (assembly == null) + return null; + + Guid versionId = Guid.Empty; + if (cacheMetadata) { + try { + if (path == null && !assembly.IsDynamic) + path = assembly.Location; + if (!String.IsNullOrEmpty(path)) + versionId = assembly.ManifestModule.ModuleVersionId; + } catch { + // Restricted reflection can still provide the usual module metadata. + } + } + + var module = versionId == Guid.Empty ? ReadModuleMetadata(assembly) : CopyCachedMetadata(assembly, path, versionId); + module.IsEntry = assembly == Assembly.GetEntryAssembly(); + return module; + } + + private static Module CopyCachedMetadata(Assembly assembly, string path, Guid versionId) { + if (!_moduleCache.TryGetValue(path, out var cached) || cached.VersionId != versionId) { + cached = new CachedModule(versionId, ReadModuleMetadata(assembly)); + lock (_cachedPaths) { + if (!_moduleCache.ContainsKey(path)) { + if (_cachedPaths.Count == MaxCachedModules) + _moduleCache.TryRemove(_cachedPaths.Dequeue(), out _); + _cachedPaths.Enqueue(path); + } + _moduleCache[path] = cached; + } + } + + var metadata = cached.Metadata; + var module = new Module { + Name = metadata.Name, + Version = metadata.Version, + CreatedDate = metadata.CreatedDate, + ModifiedDate = metadata.ModifiedDate + }; + foreach (var entry in metadata.Data) + module.Data.Add(entry.Key, entry.Value); + return module; + } + + private sealed class CachedModule { + public CachedModule(Guid versionId, Module metadata) { + VersionId = versionId; + Metadata = metadata; + } + + public Guid VersionId { get; } + public Module Metadata { get; } + } + + private static Module ReadModuleMetadata(Assembly assembly) { var mod = new Module(); + var name = assembly.GetAssemblyName(); string infoVersion = assembly.GetInformationalVersion(); string fileVersion = assembly.GetFileVersion(); if (name != null) { mod.Name = name.Name; mod.Version = infoVersion ?? fileVersion ?? name.Version.ToString(); - if (publicKeyToken != null) - mod.Data["PublicKeyToken"] = publicKeyToken; + byte[] pkt = name.GetPublicKeyToken(); + if (pkt.Length > 0) + mod.Data["PublicKeyToken"] = pkt.ToHex(); var version = name.Version.ToString(); if (!String.IsNullOrEmpty(version) && version != mod.Version) - mod.Data["Version"] = version; + mod.Data["Version"] = name.Version.ToString(); } if (!String.IsNullOrEmpty(infoVersion) && infoVersion != mod.Version) @@ -294,15 +371,14 @@ private static Module CreateModule(Assembly assembly, AssemblyName name, string if (!String.IsNullOrEmpty(fileVersion) && fileVersion != mod.Version) mod.Data["FileVersion"] = fileVersion; - try { - var file = new FileInfo(assembly.Location); - mod.ModifiedDate = file.LastWriteTimeUtc; - mod.CreatedDate = file.CreationTimeUtc; - } catch { - // Some assemblies have no accessible file timestamps. - } + DateTime? creationTime = assembly.GetCreationTime(); + if (creationTime.HasValue) + mod.CreatedDate = creationTime.Value; + + DateTime? lastWriteTime = assembly.GetLastWriteTime(); + if (lastWriteTime.HasValue) + mod.ModifiedDate = lastWriteTime.Value; - mod.IsEntry = assembly == Assembly.GetEntryAssembly(); return mod; } } diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index b4fea5da..d08a65d9 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -1,16 +1,16 @@ using System; using System.Collections; using System.Collections.Generic; -#if NET10_0 using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; +#if NET10_0 using System.Runtime.CompilerServices; using System.Runtime.Loader; +#endif using Exceptionless.Dependency; using Exceptionless.Extensions; -#endif using Exceptionless.Plugins; using Exceptionless.Plugins.Default; using Exceptionless.Models; @@ -21,100 +21,159 @@ namespace Exceptionless.Tests.Plugins { public class ErrorPluginTests : PluginTestBase { public ErrorPluginTests(ITestOutputHelper output) : base(output) { } -#if NET10_0 + private const string FixtureAssemblyName = "Exceptionless.ModuleIdRegressionFixture"; private const string ModuleFixtureType = "ModuleIdFixture"; private const string ModuleFixtureMethod = "Throw"; +#if NET10_0 [Theory] [InlineData(false)] [InlineData(true)] public void WillMapDuplicateAssemblyIdentitiesToDistinctEventModules(bool loadSameFile) { var directory = Directory.CreateTempSubdirectory(); - WeakReference outerContext = null; - WeakReference innerContext = null; - Event capturedEvent; - try { - capturedEvent = VerifyModuleMappings(directory.FullName, loadSameFile, out outerContext, out innerContext); - } finally { - for (int i = 0; i < 10 && (outerContext?.IsAlive == true || innerContext?.IsAlive == true); i++) { - GC.Collect(); - GC.WaitForPendingFinalizers(); - } + // Rebuild at the same paths after unloading. Each generation has new file versions. + for (int generation = 1; generation <= 2; generation++) { + WeakReference outerContext = null; + WeakReference innerContext = null; + Event capturedEvent; + try { + capturedEvent = VerifyModuleMappings(directory.FullName, loadSameFile, generation, out outerContext, out innerContext); + } finally { + for (int i = 0; i < 10 && (outerContext?.IsAlive == true || innerContext?.IsAlive == true); i++) { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + } + Assert.False(outerContext.IsAlive); + Assert.False(innerContext.IsAlive); + GC.KeepAlive(capturedEvent); + } + } finally { directory.Delete(recursive: true); } - - Assert.False(outerContext.IsAlive); - Assert.False(innerContext.IsAlive); - // A queued event can outlive the assemblies that produced its stack frames. - GC.KeepAlive(capturedEvent); } [MethodImpl(MethodImplOptions.NoInlining)] - private Event VerifyModuleMappings(string directory, bool loadSameFile, out WeakReference outerContextReference, out WeakReference innerContextReference) { - const string assemblyName = "Exceptionless.ModuleIdRegressionFixture"; - const string outerVersion = "1.0.1.0"; - const string innerVersion = "1.0.2.0"; + private static Event VerifyModuleMappings(string directory, bool loadSameFile, int generation, out WeakReference outerReference, out WeakReference innerReference) { var outerContext = new AssemblyLoadContext("Outer module fixture", isCollectible: true); var innerContext = new AssemblyLoadContext("Inner module fixture", isCollectible: true); - outerContextReference = new WeakReference(outerContext, trackResurrection: true); - innerContextReference = new WeakReference(innerContext, trackResurrection: true); - + outerReference = new WeakReference(outerContext, trackResurrection: true); + innerReference = new WeakReference(innerContext, trackResurrection: true); try { + string outerVersion = $"{generation}.0.1.0"; + string innerVersion = loadSameFile ? outerVersion : $"{generation}.0.2.0"; string outerPath = Path.Combine(directory, "outer.dll"); string innerPath = loadSameFile ? outerPath : Path.Combine(directory, "inner.dll"); - WriteThrowingAssembly(outerPath, assemblyName, outerVersion); + WriteThrowingAssembly(outerPath, FixtureAssemblyName, outerVersion); if (!loadSameFile) - WriteThrowingAssembly(innerPath, assemblyName, innerVersion); - - var outerAssembly = outerContext.LoadFromAssemblyPath(outerPath); - var innerAssembly = innerContext.LoadFromAssemblyPath(innerPath); - Assert.Equal(outerAssembly.FullName, innerAssembly.FullName); - Assert.NotSame(outerAssembly, innerAssembly); + WriteThrowingAssembly(innerPath, FixtureAssemblyName, innerVersion); - var throwOuter = outerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate>(); - var throwInner = innerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate>(); - var inner = Record.Exception(() => throwInner(null)); - var outer = Record.Exception(() => throwOuter(inner)); - - using var client = CreateClient(c => c.IncludeModules = true); - var context = new EventPluginContext(client, new Event()); - context.ContextData.SetException(outer); - new ErrorPlugin().Run(context); - var serializer = client.Configuration.Resolver.GetJsonSerializer(); - string json = serializer.Serialize(context.Event); - var error = serializer.Deserialize(json).GetError(serializer); - - Assert.Equal(error.Modules.Count, error.Modules.Select(m => m.ModuleId).Distinct().Count()); - var fixtureModules = error.Modules.Where(m => m.Name == assemblyName).ToList(); - Assert.Equal(2, fixtureModules.Count); - int outerId = Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; - int innerId = Assert.Single(error.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; - Assert.True(outerId > 0); - Assert.True(innerId > 0); - Assert.NotEqual(outerId, innerId); - Assert.Equal(outerVersion, Assert.Single(fixtureModules, m => m.ModuleId == outerId).Version); - Assert.Equal(loadSameFile ? outerVersion : innerVersion, Assert.Single(fixtureModules, m => m.ModuleId == innerId).Version); - - var nextError = Record.Exception(() => throwOuter(null)).ToErrorModel(client); - var originalModule = Assert.Single(context.Event.GetError().Modules, m => m.ModuleId == outerId); - int nextId = Assert.Single(nextError.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; - var nextModule = Assert.Single(nextError.Modules, m => m.ModuleId == nextId); - Assert.NotSame(originalModule, nextModule); - Assert.NotSame(originalModule.Data, nextModule.Data); - return context.Event; + return VerifyCapturedModules(outerContext.LoadFromAssemblyPath(outerPath), innerContext.LoadFromAssemblyPath(innerPath), outerVersion, innerVersion); } finally { innerContext.Unload(); outerContext.Unload(); } } +#else + [Fact] + public void WillMapFileLoadsInAnUnloadableAppDomain() { + var directory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"))); + try { + var fixtureType = typeof(ModuleDomainFixture); + var setup = new AppDomainSetup { + ApplicationBase = Path.GetDirectoryName(fixtureType.Assembly.Location), + ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile + }; + var domain = AppDomain.CreateDomain("Module ID fixture", null, setup); + try { + var fixture = (ModuleDomainFixture)domain.CreateInstanceAndUnwrap(fixtureType.Assembly.FullName, fixtureType.FullName); + fixture.Verify(directory.FullName); + } finally { + AppDomain.Unload(domain); + } + } finally { + directory.Delete(recursive: true); + } + } + + public sealed class ModuleDomainFixture : MarshalByRefObject { + public void Verify(string directory) { + string outerPath = Path.Combine(directory, "outer.dll"); + string innerPath = Path.Combine(directory, "inner.dll"); + WriteThrowingAssembly(outerPath, FixtureAssemblyName, "1.0.1.0"); + WriteThrowingAssembly(innerPath, FixtureAssemblyName, "1.0.2.0"); + VerifyCapturedModules(Assembly.LoadFile(outerPath), Assembly.LoadFile(innerPath), "1.0.1.0", "1.0.2.0"); + } + } +#endif + + private static Event VerifyCapturedModules(Assembly outerAssembly, Assembly innerAssembly, string outerVersion, string innerVersion) { + Assert.Equal(outerAssembly.FullName, innerAssembly.FullName); + Assert.NotSame(outerAssembly, innerAssembly); + + var throwOuter = (Action)outerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate(typeof(Action)); + var throwInner = (Action)innerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate(typeof(Action)); + var inner = Record.Exception(() => throwInner(null)); + var outer = Record.Exception(() => throwOuter(inner)); + + using var client = new ExceptionlessClient(c => { + c.IncludeModules = true; + c.UpdateSettingsWhenIdleInterval = TimeSpan.Zero; + }); + var context = new EventPluginContext(client, new Event()); + context.ContextData.SetException(outer); + new ErrorPlugin().Run(context); + var serializer = client.Configuration.Resolver.GetJsonSerializer(); + string json = serializer.Serialize(context.Event); + var error = serializer.Deserialize(json).GetError(serializer); + + Assert.Equal(error.Modules.Count, error.Modules.Select(m => m.ModuleId).Distinct().Count()); + var fixtureModules = error.Modules.Where(m => m.Name == FixtureAssemblyName).ToList(); + Assert.Equal(2, fixtureModules.Count); + int outerId = Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + int innerId = Assert.Single(error.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + Assert.True(outerId > 0); + Assert.True(innerId > 0); + Assert.NotEqual(outerId, innerId); + Assert.Equal(outerVersion, Assert.Single(fixtureModules, m => m.ModuleId == outerId).Version); + Assert.Equal(innerVersion, Assert.Single(fixtureModules, m => m.ModuleId == innerId).Version); + + var originalModule = Assert.Single(context.Event.GetError().Modules, m => m.ModuleId == outerId); + originalModule.Data["Version"] = "changed on the event"; + var nextError = Record.Exception(() => throwOuter(null)).ToErrorModel(client); + int nextId = Assert.Single(nextError.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + var nextModule = Assert.Single(nextError.Modules, m => m.ModuleId == nextId); + Assert.NotSame(originalModule, nextModule); + Assert.NotSame(originalModule.Data, nextModule.Data); + Assert.Equal("1.0.0.0", nextModule.Data["Version"]); +#if NET45 + Assert.Equal(outerId, error.TargetMethod.ModuleId); + Assert.Equal(innerId, error.Inner.TargetMethod.ModuleId); +#endif + var simple = outer.ToSimpleErrorModel(client); + Assert.Equal(2, simple.Modules.Where(m => m.Name == FixtureAssemblyName).Select(m => m.ModuleId).Distinct().Count()); + + client.Configuration.IncludeModules = false; + var withoutModules = outer.ToErrorModel(client); + Assert.Empty(withoutModules.Modules); + Assert.Equal(-1, Assert.Single(withoutModules.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId); + return context.Event; + } private static void WriteThrowingAssembly(string path, string name, string fileVersion) { - var assembly = new PersistedAssemblyBuilder(new AssemblyName(name) { Version = new Version(1, 0, 0, 0) }, typeof(object).Assembly); + var identity = new AssemblyName(name) { Version = new Version(1, 0, 0, 0) }; +#if NET10_0 + var assembly = new PersistedAssemblyBuilder(identity, typeof(object).Assembly); + var module = assembly.DefineDynamicModule(name); +#else + var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(identity, AssemblyBuilderAccess.Save, Path.GetDirectoryName(path)); + var module = assembly.DefineDynamicModule(name, Path.GetFileName(path)); +#endif var versionConstructor = typeof(AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) }); assembly.SetCustomAttribute(new CustomAttributeBuilder(versionConstructor, new object[] { fileVersion })); - var type = assembly.DefineDynamicModule(name).DefineType(ModuleFixtureType, TypeAttributes.Public); + var type = module.DefineType(ModuleFixtureType, TypeAttributes.Public); var method = type.DefineMethod(ModuleFixtureMethod, MethodAttributes.Public | MethodAttributes.Static, typeof(void), new[] { typeof(Exception) }); method.SetImplementationFlags(MethodImplAttributes.NoInlining); var il = method.GetILGenerator(); @@ -123,9 +182,44 @@ private static void WriteThrowingAssembly(string path, string name, string fileV il.Emit(OpCodes.Newobj, typeof(InvalidOperationException).GetConstructor(new[] { typeof(string), typeof(Exception) })); il.Emit(OpCodes.Throw); type.CreateType(); +#if NET10_0 assembly.Save(path); +#else + assembly.Save(Path.GetFileName(path)); +#endif } + + [Fact] + public void WillHonorDynamicAndLocationlessModuleFiltering() { + var name = new AssemblyName("Synthetic.Dynamic" + Guid.NewGuid().ToString("N")) { Version = new Version(2, 3, 4, 5) }; +#if NET10_0 + var dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); +#else + var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); #endif + var dynamicModule = dynamicAssembly.DefineDynamicModule(name.Name); + Assert.Equal("2.3.4.5", dynamicModule.ToModuleInfo().Version); + + string memoryName = "Synthetic.InMemory" + Guid.NewGuid().ToString("N"); + string path = Path.Combine(Path.GetTempPath(), memoryName + ".dll"); + try { + WriteThrowingAssembly(path, memoryName, "1.2.3.4"); + var memoryAssembly = Assembly.Load(File.ReadAllBytes(path)); + Assert.Empty(memoryAssembly.Location); + Assert.Equal("1.2.3.4", memoryAssembly.ToModuleInfo().Version); + + var log = new Logging.NullExceptionlessLog(); + var regular = ToErrorModelExtensions.GetLoadedModules(log); + Assert.DoesNotContain(regular, m => m.Name == name.Name || m.Name == memoryName); + var system = ToErrorModelExtensions.GetLoadedModules(log, includeSystem: true); + Assert.Contains(system, m => m.Name == typeof(object).Assembly.GetName().Name); + var all = ToErrorModelExtensions.GetLoadedModules(log, includeDynamic: true); + Assert.Contains(all, m => m.Name == name.Name && m.Version == "2.3.4.5"); + Assert.Contains(all, m => m.Name == memoryName && m.Version == "1.2.3.4"); + } finally { + File.Delete(path); + } + } [Fact] public void WillPreserveLineBreaks() { From d7f75c19d065bc8f69e198c81e30c44041c2240c Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Wed, 25 Nov 2026 10:54:55 -0800 Subject: [PATCH 04/11] Keep larger module inventories warm and look up the entry assembly once --- .../Extensions/ToErrorModelExtensions.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index 6737ab5e..d685ac0c 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -16,7 +16,7 @@ namespace Exceptionless { internal static class ToErrorModelExtensions { - private const int MaxCachedModules = 512; + private const int MaxCachedModules = 1024; private static readonly ConcurrentDictionary _moduleCache = new ConcurrentDictionary(StringComparer.Ordinal); private static readonly Queue _cachedPaths = new Queue(); private static readonly string[] _exceptionExclusions = { @@ -156,6 +156,7 @@ private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool inc var modules = new ModuleCollection(); try { int id = 1; + var entryAssembly = Assembly.GetEntryAssembly(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!includeDynamic && assembly.IsDynamic) continue; @@ -187,7 +188,7 @@ private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool inc } // A single large inventory must not evict every entry on each error. - var module = ToModuleInfo(assembly, path, cacheMetadata: id <= MaxCachedModules); + var module = ToModuleInfo(assembly, path, entryAssembly, cacheMetadata: id <= MaxCachedModules); module.ModuleId = id; modules.Add(module); moduleIds?.Add(assembly, id); @@ -288,13 +289,13 @@ public static Module ToModuleInfo(this System.Reflection.Module module) { } public static Module ToModuleInfo(this Assembly assembly) { - return ToModuleInfo(assembly, null, cacheMetadata: true); - } - - private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMetadata) { if (assembly == null) return null; + return ToModuleInfo(assembly, null, Assembly.GetEntryAssembly(), cacheMetadata: true); + } + + private static Module ToModuleInfo(Assembly assembly, string path, Assembly entryAssembly, bool cacheMetadata) { Guid versionId = Guid.Empty; if (cacheMetadata) { try { @@ -308,7 +309,7 @@ private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMet } var module = versionId == Guid.Empty ? ReadModuleMetadata(assembly) : CopyCachedMetadata(assembly, path, versionId); - module.IsEntry = assembly == Assembly.GetEntryAssembly(); + module.IsEntry = assembly == entryAssembly; return module; } From ad52ebecb902f8501cf69e5d660f032d5ab46b99 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Wed, 25 Nov 2026 11:50:55 -0800 Subject: [PATCH 05/11] Assign module IDs by event position and reuse cached metadata during filtering --- .../Extensions/ToErrorModelExtensions.cs | 126 ++++++++++-------- .../Plugins/020_ErrorPluginTests.cs | 15 ++- 2 files changed, 88 insertions(+), 53 deletions(-) diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index d685ac0c..f815bdba 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; using System.Reflection; using System.Security; @@ -37,11 +38,11 @@ public static Error ToErrorModel(this Exception exception, ExceptionlessClient c if (client == null) client = ExceptionlessClient.Default; - var moduleIds = client.Configuration.IncludeModules ? new Dictionary() : null; - return ToErrorModelInternal(exception, client, moduleIds); + var moduleAssemblies = client.Configuration.IncludeModules ? new List() : null; + return ToErrorModelInternal(exception, client, moduleAssemblies); } - private static Error ToErrorModelInternal(Exception exception, ExceptionlessClient client, Dictionary moduleIds, bool isInner = false) { + private static Error ToErrorModelInternal(Exception exception, ExceptionlessClient client, List moduleAssemblies, bool isInner = false) { var log = client.Configuration.Resolver.GetLog(); Type type = exception.GetType(); string typeName = type.GetTypeDisplayName(); @@ -51,10 +52,10 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie Type = typeName }; - if (!isInner && moduleIds != null) - error.Modules = GetLoadedModules(log, false, false, moduleIds); + if (!isInner && moduleAssemblies != null) + error.Modules = GetLoadedModules(log, false, false, moduleAssemblies); - error.PopulateStackTrace(exception, log, moduleIds); + error.PopulateStackTrace(exception, log, moduleAssemblies); try { PropertyInfo info = type.GetProperty("HResult", BindingFlags.Public | BindingFlags.Instance); @@ -68,7 +69,7 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie try { if (exception.TargetSite != null) { error.TargetMethod = new Method(); - error.TargetMethod.PopulateMethod(exception.TargetSite, moduleIds); + error.TargetMethod.PopulateMethod(exception.TargetSite, moduleAssemblies); } } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating TargetMethod: " + ex.Message); @@ -119,7 +120,7 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie } if (exception.InnerException != null) - error.Inner = ToErrorModelInternal(exception.InnerException, client, moduleIds, isInner: true); + error.Inner = ToErrorModelInternal(exception.InnerException, client, moduleAssemblies, isInner: true); return error; } @@ -152,10 +153,9 @@ internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool in return GetLoadedModules(log, includeSystem, includeDynamic, null); } - private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem, bool includeDynamic, Dictionary moduleIds) { + private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem, bool includeDynamic, List moduleAssemblies) { var modules = new ModuleCollection(); try { - int id = 1; var entryAssembly = Assembly.GetEntryAssembly(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!includeDynamic && assembly.IsDynamic) @@ -173,27 +173,15 @@ private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool inc log.Error(typeof(ExceptionlessClient), ex, message); } - if (!includeSystem) { - try { - string publicKeyToken = assembly.GetAssemblyName().GetPublicKeyToken().ToHex(); - if (_msPublicKeyTokens.Contains(publicKeyToken)) - continue; - - var attrs = assembly.GetCustomAttributes(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute)).ToList(); - if (attrs.Count > 0) - continue; - } catch (Exception ex) { - log.Error(typeof(ExceptionlessClient), ex, "Error while checking if assembly " + assembly.FullName + " should be added to modules:" + ex.Message); - } - } - // A single large inventory must not evict every entry on each error. - var module = ToModuleInfo(assembly, path, entryAssembly, cacheMetadata: id <= MaxCachedModules); - module.ModuleId = id; - modules.Add(module); - moduleIds?.Add(assembly, id); + var module = ToModuleInfo(assembly, path, modules.Count < MaxCachedModules, includeSystem, log); + if (module == null) + continue; - id++; + module.IsEntry = assembly == entryAssembly; + module.ModuleId = modules.Count + 1; + modules.Add(module); + moduleAssemblies?.Add(assembly); } } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error loading modules: " + ex.Message); @@ -202,7 +190,7 @@ private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool inc return modules; } - private static void PopulateStackTrace(this Error error, Exception exception, IExceptionlessLog log, Dictionary moduleIds) { + private static void PopulateStackTrace(this Error error, Exception exception, IExceptionlessLog log, List moduleAssemblies) { StackFrame[] frames = null; try { var st = new EnhancedStackTrace(exception); @@ -234,7 +222,7 @@ private static void PopulateStackTrace(this Error error, Exception exception, IE } try { - stackFrame.PopulateMethod(frame.GetMethod(), moduleIds); + stackFrame.PopulateMethod(frame.GetMethod(), moduleAssemblies); } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating StackFrame method info: " + ex.Message); } @@ -243,7 +231,7 @@ private static void PopulateStackTrace(this Error error, Exception exception, IE } } - private static void PopulateMethod(this Method method, MethodBase methodBase, Dictionary moduleIds) { + private static void PopulateMethod(this Method method, MethodBase methodBase, List moduleAssemblies) { if (methodBase == null) return; @@ -281,7 +269,16 @@ private static void PopulateMethod(this Method method, MethodBase methodBase, Di method.Parameters.Add(parm); } - method.ModuleId = moduleIds != null && moduleIds.TryGetValue(methodBase.Module.Assembly, out int moduleId) ? moduleId : -1; + method.ModuleId = moduleAssemblies == null ? -1 : GetModuleId(moduleAssemblies, methodBase.Module.Assembly); + } + + private static int GetModuleId(List moduleAssemblies, Assembly assembly) { + for (int i = 0; i < moduleAssemblies.Count; i++) { + if (ReferenceEquals(moduleAssemblies[i], assembly)) + return i + 1; + } + + return -1; } public static Module ToModuleInfo(this System.Reflection.Module module) { @@ -292,10 +289,12 @@ public static Module ToModuleInfo(this Assembly assembly) { if (assembly == null) return null; - return ToModuleInfo(assembly, null, Assembly.GetEntryAssembly(), cacheMetadata: true); + var module = ToModuleInfo(assembly, null, cacheMetadata: true, includeSystem: true, log: null); + module.IsEntry = assembly == Assembly.GetEntryAssembly(); + return module; } - private static Module ToModuleInfo(Assembly assembly, string path, Assembly entryAssembly, bool cacheMetadata) { + private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMetadata, bool includeSystem, IExceptionlessLog log) { Guid versionId = Guid.Empty; if (cacheMetadata) { try { @@ -308,25 +307,42 @@ private static Module ToModuleInfo(Assembly assembly, string path, Assembly entr } } - var module = versionId == Guid.Empty ? ReadModuleMetadata(assembly) : CopyCachedMetadata(assembly, path, versionId); - module.IsEntry = assembly == entryAssembly; - return module; - } + Module metadata = null; + if (versionId != Guid.Empty && _moduleCache.TryGetValue(path, out var cached) && cached.VersionId == versionId) + metadata = cached.Metadata; + + AssemblyName name = null; + if (!includeSystem) { + try { + string publicKeyToken = metadata?.Data.GetString("PublicKeyToken"); + if (metadata == null) { + name = assembly.GetAssemblyName(); + var token = name.GetPublicKeyToken(); + publicKeyToken = token.Length == 0 ? null : token.ToHex(); + } + + if (_msPublicKeyTokens.Contains(publicKeyToken) || assembly.IsDefined(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), inherit: false)) + return null; + } catch (Exception ex) { + log.Error(typeof(ExceptionlessClient), ex, "Error while checking if assembly " + assembly.FullName + " should be added to modules:" + ex.Message); + } + } + + if (metadata == null) { + metadata = ReadModuleMetadata(assembly, name, path); + if (versionId == Guid.Empty) + return metadata; - private static Module CopyCachedMetadata(Assembly assembly, string path, Guid versionId) { - if (!_moduleCache.TryGetValue(path, out var cached) || cached.VersionId != versionId) { - cached = new CachedModule(versionId, ReadModuleMetadata(assembly)); lock (_cachedPaths) { if (!_moduleCache.ContainsKey(path)) { if (_cachedPaths.Count == MaxCachedModules) _moduleCache.TryRemove(_cachedPaths.Dequeue(), out _); _cachedPaths.Enqueue(path); } - _moduleCache[path] = cached; + _moduleCache[path] = new CachedModule(versionId, metadata); } } - var metadata = cached.Metadata; var module = new Module { Name = metadata.Name, Version = metadata.Version, @@ -348,9 +364,9 @@ public CachedModule(Guid versionId, Module metadata) { public Module Metadata { get; } } - private static Module ReadModuleMetadata(Assembly assembly) { + private static Module ReadModuleMetadata(Assembly assembly, AssemblyName name, string path) { var mod = new Module(); - var name = assembly.GetAssemblyName(); + name ??= assembly.GetAssemblyName(); string infoVersion = assembly.GetInformationalVersion(); string fileVersion = assembly.GetFileVersion(); @@ -372,13 +388,19 @@ private static Module ReadModuleMetadata(Assembly assembly) { if (!String.IsNullOrEmpty(fileVersion) && fileVersion != mod.Version) mod.Data["FileVersion"] = fileVersion; - DateTime? creationTime = assembly.GetCreationTime(); - if (creationTime.HasValue) - mod.CreatedDate = creationTime.Value; + if (!String.IsNullOrEmpty(path)) { + try { + var file = new FileInfo(path); + mod.CreatedDate = file.CreationTimeUtc; + mod.ModifiedDate = file.LastWriteTimeUtc; + return mod; + } catch { + // Try each timestamp independently on restricted or unavailable files. + } + } - DateTime? lastWriteTime = assembly.GetLastWriteTime(); - if (lastWriteTime.HasValue) - mod.ModifiedDate = lastWriteTime.Value; + mod.CreatedDate = assembly.GetCreationTime().GetValueOrDefault(); + mod.ModifiedDate = assembly.GetLastWriteTime().GetValueOrDefault(); return mod; } diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index d08a65d9..73e5dbd2 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -129,7 +129,7 @@ private static Event VerifyCapturedModules(Assembly outerAssembly, Assembly inne string json = serializer.Serialize(context.Event); var error = serializer.Deserialize(json).GetError(serializer); - Assert.Equal(error.Modules.Count, error.Modules.Select(m => m.ModuleId).Distinct().Count()); + Assert.Equal(Enumerable.Range(1, error.Modules.Count), error.Modules.Select(m => m.ModuleId)); var fixtureModules = error.Modules.Where(m => m.Name == FixtureAssemblyName).ToList(); Assert.Equal(2, fixtureModules.Count); int outerId = Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; @@ -141,6 +141,8 @@ private static Event VerifyCapturedModules(Assembly outerAssembly, Assembly inne Assert.Equal(innerVersion, Assert.Single(fixtureModules, m => m.ModuleId == innerId).Version); var originalModule = Assert.Single(context.Event.GetError().Modules, m => m.ModuleId == outerId); + Assert.Equal(File.GetCreationTimeUtc(outerAssembly.Location), originalModule.CreatedDate); + Assert.Equal(File.GetLastWriteTimeUtc(outerAssembly.Location), originalModule.ModifiedDate); originalModule.Data["Version"] = "changed on the event"; var nextError = Record.Exception(() => throwOuter(null)).ToErrorModel(client); int nextId = Assert.Single(nextError.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; @@ -148,6 +150,10 @@ private static Event VerifyCapturedModules(Assembly outerAssembly, Assembly inne Assert.NotSame(originalModule, nextModule); Assert.NotSame(originalModule.Data, nextModule.Data); Assert.Equal("1.0.0.0", nextModule.Data["Version"]); + var filtered = Record.Exception(() => Enumerable.Empty().First()).ToErrorModel(client); + var frameworkFrames = filtered.StackTrace.Where(f => f.DeclaringNamespace == typeof(Enumerable).Namespace).ToList(); + Assert.NotEmpty(frameworkFrames); + Assert.All(frameworkFrames, frame => Assert.Equal(-1, frame.ModuleId)); #if NET45 Assert.Equal(outerId, error.TargetMethod.ModuleId); Assert.Equal(innerId, error.Inner.TargetMethod.ModuleId); @@ -213,9 +219,16 @@ public void WillHonorDynamicAndLocationlessModuleFiltering() { Assert.DoesNotContain(regular, m => m.Name == name.Name || m.Name == memoryName); var system = ToErrorModelExtensions.GetLoadedModules(log, includeSystem: true); Assert.Contains(system, m => m.Name == typeof(object).Assembly.GetName().Name); + string linqAssembly = typeof(Enumerable).Assembly.GetName().Name; + Assert.Contains(system, m => m.Name == linqAssembly); var all = ToErrorModelExtensions.GetLoadedModules(log, includeDynamic: true); + Assert.DoesNotContain(all, m => m.Name == linqAssembly); Assert.Contains(all, m => m.Name == name.Name && m.Version == "2.3.4.5"); Assert.Contains(all, m => m.Name == memoryName && m.Version == "1.2.3.4"); + + var generated = typeof(System.CodeDom.Compiler.GeneratedCodeAttribute).GetConstructor(new[] { typeof(string), typeof(string) }); + dynamicAssembly.SetCustomAttribute(new CustomAttributeBuilder(generated, new object[] { "Synthetic", "1" })); + Assert.DoesNotContain(ToErrorModelExtensions.GetLoadedModules(log, includeDynamic: true), m => m.Name == name.Name); } finally { File.Delete(path); } From 3dd19493b348c9cacd77ddf13f91a8effe72c4fd Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Wed, 25 Nov 2026 12:23:10 -0800 Subject: [PATCH 06/11] Isolate unreadable module metadata and exercise concurrent captures --- .../Extensions/ReflectionExtensions.cs | 10 +-- .../Extensions/ToErrorModelExtensions.cs | 55 +++++++----- .../Plugins/020_ErrorPluginTests.cs | 84 +++++++++++-------- 3 files changed, 87 insertions(+), 62 deletions(-) diff --git a/src/Exceptionless/Extensions/ReflectionExtensions.cs b/src/Exceptionless/Extensions/ReflectionExtensions.cs index bd3715ae..4eb92626 100644 --- a/src/Exceptionless/Extensions/ReflectionExtensions.cs +++ b/src/Exceptionless/Extensions/ReflectionExtensions.cs @@ -37,13 +37,13 @@ public static string GetVersion(this Assembly assembly) { } public static string GetFileVersion(this Assembly assembly) { - var attr = assembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute; - return attr != null ? attr.Version : null; + var attributes = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), inherit: false); + return attributes.Length == 1 ? ((AssemblyFileVersionAttribute)attributes[0]).Version : null; } public static string GetInformationalVersion(this Assembly assembly) { - var attr = assembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute; - return attr != null ? attr.InformationalVersion : null; + var attributes = assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), inherit: false); + return attributes.Length == 1 ? ((AssemblyInformationalVersionAttribute)attributes[0]).InformationalVersion : null; } public static string GetCompany(this Assembly assembly) { @@ -51,4 +51,4 @@ public static string GetCompany(this Assembly assembly) { return attr != null ? attr.Company : null; } } -} \ No newline at end of file +} diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index f815bdba..c8e2caf1 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -158,23 +158,8 @@ private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool inc try { var entryAssembly = Assembly.GetEntryAssembly(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { - if (!includeDynamic && assembly.IsDynamic) - continue; - - string path = null; - try { - if (!includeDynamic) { - path = assembly.Location; - if (String.IsNullOrEmpty(path)) - continue; - } - } catch (SecurityException ex) { - const string message = "An error occurred while getting the Assembly.Location value. This error will occur when when you are not running under full trust."; - log.Error(typeof(ExceptionlessClient), ex, message); - } - // A single large inventory must not evict every entry on each error. - var module = ToModuleInfo(assembly, path, modules.Count < MaxCachedModules, includeSystem, log); + var module = TryGetModuleInfo(assembly, modules.Count < MaxCachedModules, includeSystem, includeDynamic, log); if (module == null) continue; @@ -289,11 +274,34 @@ public static Module ToModuleInfo(this Assembly assembly) { if (assembly == null) return null; - var module = ToModuleInfo(assembly, null, cacheMetadata: true, includeSystem: true, log: null); - module.IsEntry = assembly == Assembly.GetEntryAssembly(); + var module = TryGetModuleInfo(assembly, cacheMetadata: true, includeSystem: true, includeDynamic: true, log: null); + if (module != null) + module.IsEntry = assembly == Assembly.GetEntryAssembly(); return module; } + private static Module TryGetModuleInfo(Assembly assembly, bool cacheMetadata, bool includeSystem, bool includeDynamic, IExceptionlessLog log) { + try { + string path = null; + if (!includeDynamic) { + if (assembly.IsDynamic) + return null; + try { + path = assembly.Location; + if (String.IsNullOrEmpty(path)) + return null; + } catch (SecurityException ex) { + log?.Error(typeof(ExceptionlessClient), ex, "Assembly.Location is unavailable under partial trust."); + } + } + + return ToModuleInfo(assembly, path, cacheMetadata, includeSystem, log); + } catch (Exception ex) { + log?.Error(typeof(ExceptionlessClient), ex, "Error reading module metadata."); + return null; + } + } + private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMetadata, bool includeSystem, IExceptionlessLog log) { Guid versionId = Guid.Empty; if (cacheMetadata) { @@ -318,7 +326,7 @@ private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMet if (metadata == null) { name = assembly.GetAssemblyName(); var token = name.GetPublicKeyToken(); - publicKeyToken = token.Length == 0 ? null : token.ToHex(); + publicKeyToken = token?.Length > 0 ? token.ToHex() : null; } if (_msPublicKeyTokens.Contains(publicKeyToken) || assembly.IsDefined(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), inherit: false)) @@ -333,6 +341,7 @@ private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMet if (versionId == Guid.Empty) return metadata; + // Publish and evict under the same lock so each cached path is queued exactly once. lock (_cachedPaths) { if (!_moduleCache.ContainsKey(path)) { if (_cachedPaths.Count == MaxCachedModules) @@ -372,14 +381,14 @@ private static Module ReadModuleMetadata(Assembly assembly, AssemblyName name, s if (name != null) { mod.Name = name.Name; - mod.Version = infoVersion ?? fileVersion ?? name.Version.ToString(); + string version = name.Version?.ToString(); + mod.Version = infoVersion ?? fileVersion ?? version; byte[] pkt = name.GetPublicKeyToken(); - if (pkt.Length > 0) + if (pkt?.Length > 0) mod.Data["PublicKeyToken"] = pkt.ToHex(); - var version = name.Version.ToString(); if (!String.IsNullOrEmpty(version) && version != mod.Version) - mod.Data["Version"] = name.Version.ToString(); + mod.Data["Version"] = version; } if (!String.IsNullOrEmpty(infoVersion) && infoVersion != mod.Version) diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index 73e5dbd2..1c7a0414 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -9,6 +9,7 @@ using System.Runtime.CompilerServices; using System.Runtime.Loader; #endif +using System.Threading.Tasks; using Exceptionless.Dependency; using Exceptionless.Extensions; using Exceptionless.Plugins; @@ -115,49 +116,51 @@ private static Event VerifyCapturedModules(Assembly outerAssembly, Assembly inne var throwOuter = (Action)outerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate(typeof(Action)); var throwInner = (Action)innerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate(typeof(Action)); - var inner = Record.Exception(() => throwInner(null)); - var outer = Record.Exception(() => throwOuter(inner)); - using var client = new ExceptionlessClient(c => { c.IncludeModules = true; c.UpdateSettingsWhenIdleInterval = TimeSpan.Zero; }); - var context = new EventPluginContext(client, new Event()); - context.ContextData.SetException(outer); - new ErrorPlugin().Run(context); + var events = new Event[4]; + Parallel.For(0, events.Length, i => { + var inner = Record.Exception(() => throwInner(null)); + var context = new EventPluginContext(client, new Event()); + context.ContextData.SetException(Record.Exception(() => throwOuter(inner))); + new ErrorPlugin().Run(context); + events[i] = context.Event; + }); + var serializer = client.Configuration.Resolver.GetJsonSerializer(); - string json = serializer.Serialize(context.Event); - var error = serializer.Deserialize(json).GetError(serializer); - - Assert.Equal(Enumerable.Range(1, error.Modules.Count), error.Modules.Select(m => m.ModuleId)); - var fixtureModules = error.Modules.Where(m => m.Name == FixtureAssemblyName).ToList(); - Assert.Equal(2, fixtureModules.Count); - int outerId = Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; - int innerId = Assert.Single(error.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; - Assert.True(outerId > 0); - Assert.True(innerId > 0); - Assert.NotEqual(outerId, innerId); - Assert.Equal(outerVersion, Assert.Single(fixtureModules, m => m.ModuleId == outerId).Version); - Assert.Equal(innerVersion, Assert.Single(fixtureModules, m => m.ModuleId == innerId).Version); - - var originalModule = Assert.Single(context.Event.GetError().Modules, m => m.ModuleId == outerId); - Assert.Equal(File.GetCreationTimeUtc(outerAssembly.Location), originalModule.CreatedDate); - Assert.Equal(File.GetLastWriteTimeUtc(outerAssembly.Location), originalModule.ModifiedDate); - originalModule.Data["Version"] = "changed on the event"; - var nextError = Record.Exception(() => throwOuter(null)).ToErrorModel(client); + foreach (var captured in events) { + var error = serializer.Deserialize(serializer.Serialize(captured)).GetError(serializer); + Assert.Equal(Enumerable.Range(1, error.Modules.Count), error.Modules.Select(m => m.ModuleId)); + var fixtureModules = error.Modules.Where(m => m.Name == FixtureAssemblyName).ToList(); + Assert.Equal(2, fixtureModules.Count); + int outerId = Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + int innerId = Assert.Single(error.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + Assert.NotEqual(outerId, innerId); + Assert.Equal(outerVersion, Assert.Single(fixtureModules, m => m.ModuleId == outerId).Version); + Assert.Equal(innerVersion, Assert.Single(fixtureModules, m => m.ModuleId == innerId).Version); +#if NET45 + Assert.Equal(outerId, error.TargetMethod.ModuleId); + Assert.Equal(innerId, error.Inner.TargetMethod.ModuleId); +#endif + var module = Assert.Single(captured.GetError().Modules, m => m.ModuleId == outerId); + Assert.Equal(File.GetCreationTimeUtc(outerAssembly.Location), module.CreatedDate); + Assert.Equal(File.GetLastWriteTimeUtc(outerAssembly.Location), module.ModifiedDate); + Assert.Equal("1.0.0.0", module.Data["Version"]); + module.Data["Version"] = "changed on the event"; + } + + var nextInner = Record.Exception(() => throwInner(null)); + var outer = Record.Exception(() => throwOuter(nextInner)); + var nextError = outer.ToErrorModel(client); int nextId = Assert.Single(nextError.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; var nextModule = Assert.Single(nextError.Modules, m => m.ModuleId == nextId); - Assert.NotSame(originalModule, nextModule); - Assert.NotSame(originalModule.Data, nextModule.Data); Assert.Equal("1.0.0.0", nextModule.Data["Version"]); var filtered = Record.Exception(() => Enumerable.Empty().First()).ToErrorModel(client); var frameworkFrames = filtered.StackTrace.Where(f => f.DeclaringNamespace == typeof(Enumerable).Namespace).ToList(); Assert.NotEmpty(frameworkFrames); Assert.All(frameworkFrames, frame => Assert.Equal(-1, frame.ModuleId)); -#if NET45 - Assert.Equal(outerId, error.TargetMethod.ModuleId); - Assert.Equal(innerId, error.Inner.TargetMethod.ModuleId); -#endif var simple = outer.ToSimpleErrorModel(client); Assert.Equal(2, simple.Modules.Where(m => m.Name == FixtureAssemblyName).Select(m => m.ModuleId).Distinct().Count()); @@ -165,10 +168,10 @@ private static Event VerifyCapturedModules(Assembly outerAssembly, Assembly inne var withoutModules = outer.ToErrorModel(client); Assert.Empty(withoutModules.Modules); Assert.Equal(-1, Assert.Single(withoutModules.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId); - return context.Event; + return events[0]; } - private static void WriteThrowingAssembly(string path, string name, string fileVersion) { + private static void WriteThrowingAssembly(string path, string name, string fileVersion, bool ambiguousInformationalVersion = false) { var identity = new AssemblyName(name) { Version = new Version(1, 0, 0, 0) }; #if NET10_0 var assembly = new PersistedAssemblyBuilder(identity, typeof(object).Assembly); @@ -179,6 +182,11 @@ private static void WriteThrowingAssembly(string path, string name, string fileV #endif var versionConstructor = typeof(AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) }); assembly.SetCustomAttribute(new CustomAttributeBuilder(versionConstructor, new object[] { fileVersion })); + if (ambiguousInformationalVersion) { + var constructor = typeof(AssemblyInformationalVersionAttribute).GetConstructor(new[] { typeof(string) }); + assembly.SetCustomAttribute(new CustomAttributeBuilder(constructor, new object[] { "first" })); + assembly.SetCustomAttribute(new CustomAttributeBuilder(constructor, new object[] { "second" })); + } var type = module.DefineType(ModuleFixtureType, TypeAttributes.Public); var method = type.DefineMethod(ModuleFixtureMethod, MethodAttributes.Public | MethodAttributes.Static, typeof(void), new[] { typeof(Exception) }); method.SetImplementationFlags(MethodImplAttributes.NoInlining); @@ -209,7 +217,7 @@ public void WillHonorDynamicAndLocationlessModuleFiltering() { string memoryName = "Synthetic.InMemory" + Guid.NewGuid().ToString("N"); string path = Path.Combine(Path.GetTempPath(), memoryName + ".dll"); try { - WriteThrowingAssembly(path, memoryName, "1.2.3.4"); + WriteThrowingAssembly(path, memoryName, "1.2.3.4", ambiguousInformationalVersion: true); var memoryAssembly = Assembly.Load(File.ReadAllBytes(path)); Assert.Empty(memoryAssembly.Location); Assert.Equal("1.2.3.4", memoryAssembly.ToModuleInfo().Version); @@ -229,6 +237,14 @@ public void WillHonorDynamicAndLocationlessModuleFiltering() { var generated = typeof(System.CodeDom.Compiler.GeneratedCodeAttribute).GetConstructor(new[] { typeof(string), typeof(string) }); dynamicAssembly.SetCustomAttribute(new CustomAttributeBuilder(generated, new object[] { "Synthetic", "1" })); Assert.DoesNotContain(ToErrorModelExtensions.GetLoadedModules(log, includeDynamic: true), m => m.Name == name.Name); + + // A malformed attribute on one assembly must not interrupt the inventory. + var fileVersion = typeof(AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) }); + dynamicAssembly.SetCustomAttribute(fileVersion, new byte[] { 0, 0 }); + Assert.Null(dynamicModule.ToModuleInfo()); + var remaining = ToErrorModelExtensions.GetLoadedModules(log, includeSystem: true, includeDynamic: true); + Assert.DoesNotContain(remaining, m => m.Name == name.Name); + Assert.Contains(remaining, m => m.Name == memoryName && m.Version == "1.2.3.4"); } finally { File.Delete(path); } From d5c746287cb3d147a6a0ad026bab3dd65bd63999 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Wed, 25 Nov 2026 14:29:24 -0800 Subject: [PATCH 07/11] Clarify version fallback, module lookup, and loader regressions --- .../Extensions/ReflectionExtensions.cs | 14 +- .../Extensions/ToErrorModelExtensions.cs | 127 +++++----- .../Plugins/020_ErrorPluginTests.cs | 217 +++++++++++------- 3 files changed, 204 insertions(+), 154 deletions(-) diff --git a/src/Exceptionless/Extensions/ReflectionExtensions.cs b/src/Exceptionless/Extensions/ReflectionExtensions.cs index 4eb92626..a698d279 100644 --- a/src/Exceptionless/Extensions/ReflectionExtensions.cs +++ b/src/Exceptionless/Extensions/ReflectionExtensions.cs @@ -37,13 +37,19 @@ public static string GetVersion(this Assembly assembly) { } public static string GetFileVersion(this Assembly assembly) { - var attributes = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), inherit: false); - return attributes.Length == 1 ? ((AssemblyFileVersionAttribute)attributes[0]).Version : null; + return assembly.GetSingleVersionAttribute()?.Version; } public static string GetInformationalVersion(this Assembly assembly) { - var attributes = assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), inherit: false); - return attributes.Length == 1 ? ((AssemblyInformationalVersionAttribute)attributes[0]).InformationalVersion : null; + return assembly.GetSingleVersionAttribute()?.InformationalVersion; + } + + private static T GetSingleVersionAttribute(this Assembly assembly) where T : Attribute { + var matches = assembly.GetCustomAttributes(typeof(T), inherit: false); + if (matches.Length is not 1) + return null; + + return matches[0] as T; } public static string GetCompany(this Assembly assembly) { diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index c8e2caf1..74bb6e9a 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; @@ -18,8 +19,8 @@ namespace Exceptionless { internal static class ToErrorModelExtensions { private const int MaxCachedModules = 1024; - private static readonly ConcurrentDictionary _moduleCache = new ConcurrentDictionary(StringComparer.Ordinal); - private static readonly Queue _cachedPaths = new Queue(); + private static readonly ConcurrentDictionary _moduleCache = new(); + private static readonly Queue _cachedPaths = new(); private static readonly string[] _exceptionExclusions = { "@exceptionless", "Data", "HelpLink", "ExceptionContext", "InnerExceptions", "InnerException", "Errors", "Types", "Message", "Source", "StackTrace", "TargetSite", "HResult", @@ -35,14 +36,13 @@ internal static class ToErrorModelExtensions { /// ExceptionlessClient.Default. /// public static Error ToErrorModel(this Exception exception, ExceptionlessClient client = null) { - if (client == null) + if (client is null) client = ExceptionlessClient.Default; - var moduleAssemblies = client.Configuration.IncludeModules ? new List() : null; - return ToErrorModelInternal(exception, client, moduleAssemblies); + return ToErrorModelInternal(exception, client); } - private static Error ToErrorModelInternal(Exception exception, ExceptionlessClient client, List moduleAssemblies, bool isInner = false) { + private static Error ToErrorModelInternal(Exception exception, ExceptionlessClient client, List moduleAssemblies = null, bool isInner = false) { var log = client.Configuration.Resolver.GetLog(); Type type = exception.GetType(); string typeName = type.GetTypeDisplayName(); @@ -52,10 +52,12 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie Type = typeName }; - if (!isInner && moduleAssemblies != null) - error.Modules = GetLoadedModules(log, false, false, moduleAssemblies); + if (!isInner && client.Configuration.IncludeModules) { + moduleAssemblies = new List(); + error.Modules = GetLoadedModules(log, moduleAssemblies: moduleAssemblies); + } - error.PopulateStackTrace(exception, log, moduleAssemblies); + error.PopulateStackTrace(moduleAssemblies, exception, log); try { PropertyInfo info = type.GetProperty("HResult", BindingFlags.Public | BindingFlags.Instance); @@ -67,9 +69,9 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie #if NET45 try { - if (exception.TargetSite != null) { + if (exception.TargetSite is not null) { error.TargetMethod = new Method(); - error.TargetMethod.PopulateMethod(exception.TargetSite, moduleAssemblies); + error.TargetMethod.PopulateMethod(moduleAssemblies, exception.TargetSite); } } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating TargetMethod: " + ex.Message); @@ -119,7 +121,7 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie log.Error(typeof(ExceptionlessClient), ex, "Error populating extra exception properties: " + ex.Message); } - if (exception.InnerException != null) + if (exception.InnerException is not null) error.Inner = ToErrorModelInternal(exception.InnerException, client, moduleAssemblies, isInner: true); return error; @@ -149,21 +151,17 @@ private static string GetMessage(this Exception exception, string typeName) { return !String.IsNullOrEmpty(message) ? message : defaultMessage; } - internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem = false, bool includeDynamic = false) { - return GetLoadedModules(log, includeSystem, includeDynamic, null); - } - - private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem, bool includeDynamic, List moduleAssemblies) { + internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool includeSystem = false, bool includeDynamic = false, List moduleAssemblies = null) { var modules = new ModuleCollection(); try { var entryAssembly = Assembly.GetEntryAssembly(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { // A single large inventory must not evict every entry on each error. - var module = TryGetModuleInfo(assembly, modules.Count < MaxCachedModules, includeSystem, includeDynamic, log); - if (module == null) + bool cacheMetadata = modules.Count < MaxCachedModules; + var module = TryGetModuleInfo(assembly, entryAssembly, log, includeSystem, includeDynamic, cacheMetadata); + if (module is null) continue; - module.IsEntry = assembly == entryAssembly; module.ModuleId = modules.Count + 1; modules.Add(module); moduleAssemblies?.Add(assembly); @@ -175,7 +173,7 @@ private static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool inc return modules; } - private static void PopulateStackTrace(this Error error, Exception exception, IExceptionlessLog log, List moduleAssemblies) { + private static void PopulateStackTrace(this Error error, List moduleAssemblies, Exception exception, IExceptionlessLog log) { StackFrame[] frames = null; try { var st = new EnhancedStackTrace(exception); @@ -207,7 +205,7 @@ private static void PopulateStackTrace(this Error error, Exception exception, IE } try { - stackFrame.PopulateMethod(frame.GetMethod(), moduleAssemblies); + stackFrame.PopulateMethod(moduleAssemblies, frame.GetMethod()); } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating StackFrame method info: " + ex.Message); } @@ -216,8 +214,8 @@ private static void PopulateStackTrace(this Error error, Exception exception, IE } } - private static void PopulateMethod(this Method method, MethodBase methodBase, List moduleAssemblies) { - if (methodBase == null) + private static void PopulateMethod(this Method method, List moduleAssemblies, MethodBase methodBase) { + if (methodBase is null) return; method.Name = methodBase.Name; @@ -254,10 +252,14 @@ private static void PopulateMethod(this Method method, MethodBase methodBase, Li method.Parameters.Add(parm); } - method.ModuleId = moduleAssemblies == null ? -1 : GetModuleId(moduleAssemblies, methodBase.Module.Assembly); + method.ModuleId = GetModuleId(moduleAssemblies, methodBase); } - private static int GetModuleId(List moduleAssemblies, Assembly assembly) { + private static int GetModuleId(List moduleAssemblies, MethodBase method) { + if (moduleAssemblies is null) + return -1; + + var assembly = method.Module.Assembly; for (int i = 0; i < moduleAssemblies.Count; i++) { if (ReferenceEquals(moduleAssemblies[i], assembly)) return i + 1; @@ -271,45 +273,40 @@ public static Module ToModuleInfo(this System.Reflection.Module module) { } public static Module ToModuleInfo(this Assembly assembly) { - if (assembly == null) + if (assembly is null) return null; - var module = TryGetModuleInfo(assembly, cacheMetadata: true, includeSystem: true, includeDynamic: true, log: null); - if (module != null) - module.IsEntry = assembly == Assembly.GetEntryAssembly(); - return module; + return TryGetModuleInfo(assembly, Assembly.GetEntryAssembly(), log: null, includeSystem: true, includeDynamic: true); } - private static Module TryGetModuleInfo(Assembly assembly, bool cacheMetadata, bool includeSystem, bool includeDynamic, IExceptionlessLog log) { + private static Module TryGetModuleInfo(Assembly assembly, Assembly entryAssembly, IExceptionlessLog log, + bool includeSystem, bool includeDynamic, bool cacheMetadata = true) { try { string path = null; - if (!includeDynamic) { - if (assembly.IsDynamic) - return null; - try { + try { + if (!assembly.IsDynamic) path = assembly.Location; - if (String.IsNullOrEmpty(path)) - return null; - } catch (SecurityException ex) { - log?.Error(typeof(ExceptionlessClient), ex, "Assembly.Location is unavailable under partial trust."); - } + if (!includeDynamic && String.IsNullOrEmpty(path)) + return null; + } catch (Exception ex) when (includeDynamic || ex is SecurityException) { + log?.Error(typeof(ExceptionlessClient), ex, "Assembly location is unavailable."); } - return ToModuleInfo(assembly, path, cacheMetadata, includeSystem, log); + var module = GetModuleMetadata(assembly, path, cacheMetadata, includeSystem, log); + if (module is not null) + module.IsEntry = ReferenceEquals(assembly, entryAssembly); + return module; } catch (Exception ex) { log?.Error(typeof(ExceptionlessClient), ex, "Error reading module metadata."); return null; } } - private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMetadata, bool includeSystem, IExceptionlessLog log) { + private static Module GetModuleMetadata(Assembly assembly, string path, bool cacheMetadata, bool includeSystem, IExceptionlessLog log) { Guid versionId = Guid.Empty; - if (cacheMetadata) { + if (cacheMetadata && !String.IsNullOrEmpty(path)) { try { - if (path == null && !assembly.IsDynamic) - path = assembly.Location; - if (!String.IsNullOrEmpty(path)) - versionId = assembly.ManifestModule.ModuleVersionId; + versionId = assembly.ManifestModule.ModuleVersionId; } catch { // Restricted reflection can still provide the usual module metadata. } @@ -320,31 +317,33 @@ private static Module ToModuleInfo(Assembly assembly, string path, bool cacheMet metadata = cached.Metadata; AssemblyName name = null; + string publicKeyToken = null; + if (metadata is null) { + name = assembly.GetAssemblyName(); + if (name?.GetPublicKeyToken() is { Length: > 0 } token) + publicKeyToken = token.ToHex(); + } else { + publicKeyToken = metadata.Data.GetString("PublicKeyToken"); + } + if (!includeSystem) { try { - string publicKeyToken = metadata?.Data.GetString("PublicKeyToken"); - if (metadata == null) { - name = assembly.GetAssemblyName(); - var token = name.GetPublicKeyToken(); - publicKeyToken = token?.Length > 0 ? token.ToHex() : null; - } - - if (_msPublicKeyTokens.Contains(publicKeyToken) || assembly.IsDefined(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), inherit: false)) + if (_msPublicKeyTokens.Contains(publicKeyToken) || assembly.IsDefined(typeof(GeneratedCodeAttribute), inherit: false)) return null; } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error while checking if assembly " + assembly.FullName + " should be added to modules:" + ex.Message); } } - if (metadata == null) { - metadata = ReadModuleMetadata(assembly, name, path); + if (metadata is null) { + metadata = ReadModuleMetadata(assembly, name, publicKeyToken, path); if (versionId == Guid.Empty) return metadata; // Publish and evict under the same lock so each cached path is queued exactly once. lock (_cachedPaths) { if (!_moduleCache.ContainsKey(path)) { - if (_cachedPaths.Count == MaxCachedModules) + if (_cachedPaths.Count >= MaxCachedModules) _moduleCache.TryRemove(_cachedPaths.Dequeue(), out _); _cachedPaths.Enqueue(path); } @@ -373,19 +372,17 @@ public CachedModule(Guid versionId, Module metadata) { public Module Metadata { get; } } - private static Module ReadModuleMetadata(Assembly assembly, AssemblyName name, string path) { + private static Module ReadModuleMetadata(Assembly assembly, AssemblyName name, string publicKeyToken, string path) { var mod = new Module(); - name ??= assembly.GetAssemblyName(); string infoVersion = assembly.GetInformationalVersion(); string fileVersion = assembly.GetFileVersion(); - if (name != null) { + if (name is not null) { mod.Name = name.Name; string version = name.Version?.ToString(); mod.Version = infoVersion ?? fileVersion ?? version; - byte[] pkt = name.GetPublicKeyToken(); - if (pkt?.Length > 0) - mod.Data["PublicKeyToken"] = pkt.ToHex(); + if (publicKeyToken is not null) + mod.Data["PublicKeyToken"] = publicKeyToken; if (!String.IsNullOrEmpty(version) && version != mod.Version) mod.Data["Version"] = version; diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index 1c7a0414..a02ff2e1 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -16,6 +16,7 @@ using Exceptionless.Plugins.Default; using Exceptionless.Models; using Exceptionless.Models.Data; +using Exceptionless.Serializer; using Xunit; namespace Exceptionless.Tests.Plugins { @@ -30,7 +31,8 @@ public ErrorPluginTests(ITestOutputHelper output) : base(output) { } [Theory] [InlineData(false)] [InlineData(true)] - public void WillMapDuplicateAssemblyIdentitiesToDistinctEventModules(bool loadSameFile) { + public void ToErrorModel_DuplicateAssembliesInLoadContexts_MapsFramesAndAllowsUnload(bool loadSameFile) { + // Arrange var directory = Directory.CreateTempSubdirectory(); try { // Rebuild at the same paths after unloading. Each generation has new file versions. @@ -39,14 +41,16 @@ public void WillMapDuplicateAssemblyIdentitiesToDistinctEventModules(bool loadSa WeakReference innerContext = null; Event capturedEvent; try { + // Act capturedEvent = VerifyModuleMappings(directory.FullName, loadSameFile, generation, out outerContext, out innerContext); } finally { - for (int i = 0; i < 10 && (outerContext?.IsAlive == true || innerContext?.IsAlive == true); i++) { + for (int i = 0; i < 10 && (outerContext?.IsAlive is true || innerContext?.IsAlive is true); i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } + // Assert Assert.False(outerContext.IsAlive); Assert.False(innerContext.IsAlive); GC.KeepAlive(capturedEvent); @@ -79,7 +83,8 @@ private static Event VerifyModuleMappings(string directory, bool loadSameFile, i } #else [Fact] - public void WillMapFileLoadsInAnUnloadableAppDomain() { + public void ToErrorModel_DuplicateAssembliesInAppDomain_MapsTargetMethodsToTheirModules() { + // Arrange var directory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"))); try { var fixtureType = typeof(ModuleDomainFixture); @@ -88,90 +93,108 @@ public void WillMapFileLoadsInAnUnloadableAppDomain() { ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; var domain = AppDomain.CreateDomain("Module ID fixture", null, setup); + string json; try { var fixture = (ModuleDomainFixture)domain.CreateInstanceAndUnwrap(fixtureType.Assembly.FullName, fixtureType.FullName); - fixture.Verify(directory.FullName); + // Act + json = fixture.Capture(directory.FullName); } finally { AppDomain.Unload(domain); } + + // Assert + var serializer = new DefaultJsonSerializer(); + var error = serializer.Deserialize(json).GetError(serializer); + Assert.Equal(FixtureModuleId(error), error.TargetMethod.ModuleId); + Assert.Equal(FixtureModuleId(error.Inner), error.Inner.TargetMethod.ModuleId); } finally { directory.Delete(recursive: true); } } public sealed class ModuleDomainFixture : MarshalByRefObject { - public void Verify(string directory) { + public string Capture(string directory) { string outerPath = Path.Combine(directory, "outer.dll"); string innerPath = Path.Combine(directory, "inner.dll"); WriteThrowingAssembly(outerPath, FixtureAssemblyName, "1.0.1.0"); WriteThrowingAssembly(innerPath, FixtureAssemblyName, "1.0.2.0"); - VerifyCapturedModules(Assembly.LoadFile(outerPath), Assembly.LoadFile(innerPath), "1.0.1.0", "1.0.2.0"); + var captured = VerifyCapturedModules(Assembly.LoadFile(outerPath), Assembly.LoadFile(innerPath), "1.0.1.0", "1.0.2.0"); + return new DefaultJsonSerializer().Serialize(captured); } } #endif private static Event VerifyCapturedModules(Assembly outerAssembly, Assembly innerAssembly, string outerVersion, string innerVersion) { - Assert.Equal(outerAssembly.FullName, innerAssembly.FullName); - Assert.NotSame(outerAssembly, innerAssembly); - - var throwOuter = (Action)outerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate(typeof(Action)); - var throwInner = (Action)innerAssembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod).CreateDelegate(typeof(Action)); + // Arrange + var throwOuter = GetThrower(outerAssembly); + var throwInner = GetThrower(innerAssembly); using var client = new ExceptionlessClient(c => { c.IncludeModules = true; c.UpdateSettingsWhenIdleInterval = TimeSpan.Zero; }); + var serializer = client.Configuration.Resolver.GetJsonSerializer(); var events = new Event[4]; + + // Act Parallel.For(0, events.Length, i => { var inner = Record.Exception(() => throwInner(null)); var context = new EventPluginContext(client, new Event()); context.ContextData.SetException(Record.Exception(() => throwOuter(inner))); new ErrorPlugin().Run(context); + foreach (var module in context.Event.GetError().Modules.Where(m => m.Name is FixtureAssemblyName)) + module.Data["Version"] = $"capture {i}"; events[i] = context.Event; }); - var serializer = client.Configuration.Resolver.GetJsonSerializer(); - foreach (var captured in events) { - var error = serializer.Deserialize(serializer.Serialize(captured)).GetError(serializer); - Assert.Equal(Enumerable.Range(1, error.Modules.Count), error.Modules.Select(m => m.ModuleId)); - var fixtureModules = error.Modules.Where(m => m.Name == FixtureAssemblyName).ToList(); - Assert.Equal(2, fixtureModules.Count); - int outerId = Assert.Single(error.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; - int innerId = Assert.Single(error.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; - Assert.NotEqual(outerId, innerId); - Assert.Equal(outerVersion, Assert.Single(fixtureModules, m => m.ModuleId == outerId).Version); - Assert.Equal(innerVersion, Assert.Single(fixtureModules, m => m.ModuleId == innerId).Version); -#if NET45 - Assert.Equal(outerId, error.TargetMethod.ModuleId); - Assert.Equal(innerId, error.Inner.TargetMethod.ModuleId); -#endif - var module = Assert.Single(captured.GetError().Modules, m => m.ModuleId == outerId); - Assert.Equal(File.GetCreationTimeUtc(outerAssembly.Location), module.CreatedDate); - Assert.Equal(File.GetLastWriteTimeUtc(outerAssembly.Location), module.ModifiedDate); - Assert.Equal("1.0.0.0", module.Data["Version"]); - module.Data["Version"] = "changed on the event"; - } - + var errors = events.Select(e => serializer.Deserialize(serializer.Serialize(e)).GetError(serializer)).ToArray(); var nextInner = Record.Exception(() => throwInner(null)); var outer = Record.Exception(() => throwOuter(nextInner)); var nextError = outer.ToErrorModel(client); - int nextId = Assert.Single(nextError.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId; + var filtered = Record.Exception(() => Enumerable.Empty().First()).ToErrorModel(client); + var simple = outer.ToSimpleErrorModel(client); + client.Configuration.IncludeModules = false; + var withoutModules = outer.ToErrorModel(client); + + // Assert + Assert.Equal(outerAssembly.FullName, innerAssembly.FullName); + Assert.NotSame(outerAssembly, innerAssembly); + for (int i = 0; i < errors.Length; i++) { + var error = errors[i]; + Assert.Equal(Enumerable.Range(1, error.Modules.Count), error.Modules.Select(m => m.ModuleId)); + var modules = error.Modules.Where(m => m.Name is FixtureAssemblyName).ToList(); + Assert.Equal(2, modules.Count); + int outerId = FixtureModuleId(error); + int innerId = FixtureModuleId(error.Inner); + Assert.NotEqual(outerId, innerId); + var outerModule = Assert.Single(modules, m => m.ModuleId == outerId); + Assert.Equal(outerVersion, outerModule.Version); + Assert.Equal(innerVersion, Assert.Single(modules, m => m.ModuleId == innerId).Version); + Assert.Equal(File.GetCreationTimeUtc(outerAssembly.Location), outerModule.CreatedDate); + Assert.Equal(File.GetLastWriteTimeUtc(outerAssembly.Location), outerModule.ModifiedDate); + Assert.Equal($"capture {i}", outerModule.Data["Version"]); + } + int nextId = FixtureModuleId(nextError); var nextModule = Assert.Single(nextError.Modules, m => m.ModuleId == nextId); Assert.Equal("1.0.0.0", nextModule.Data["Version"]); - var filtered = Record.Exception(() => Enumerable.Empty().First()).ToErrorModel(client); var frameworkFrames = filtered.StackTrace.Where(f => f.DeclaringNamespace == typeof(Enumerable).Namespace).ToList(); Assert.NotEmpty(frameworkFrames); Assert.All(frameworkFrames, frame => Assert.Equal(-1, frame.ModuleId)); - var simple = outer.ToSimpleErrorModel(client); - Assert.Equal(2, simple.Modules.Where(m => m.Name == FixtureAssemblyName).Select(m => m.ModuleId).Distinct().Count()); - - client.Configuration.IncludeModules = false; - var withoutModules = outer.ToErrorModel(client); + Assert.Equal(2, simple.Modules.Where(m => m.Name is FixtureAssemblyName).Select(m => m.ModuleId).Distinct().Count()); Assert.Empty(withoutModules.Modules); - Assert.Equal(-1, Assert.Single(withoutModules.Inner.StackTrace, f => f.DeclaringType == ModuleFixtureType).ModuleId); + Assert.Equal(-1, FixtureModuleId(withoutModules.Inner)); return events[0]; } - private static void WriteThrowingAssembly(string path, string name, string fileVersion, bool ambiguousInformationalVersion = false) { + private static int FixtureModuleId(InnerError error) { + return Assert.Single(error.StackTrace, f => f.DeclaringType is ModuleFixtureType).ModuleId; + } + + private static Action GetThrower(Assembly assembly) { + var method = assembly.GetType(ModuleFixtureType, throwOnError: true).GetMethod(ModuleFixtureMethod); + return (Action)method.CreateDelegate(typeof(Action)); + } + + private static void WriteThrowingAssembly(string path, string name, string fileVersion, params CustomAttributeBuilder[] extraVersions) { var identity = new AssemblyName(name) { Version = new Version(1, 0, 0, 0) }; #if NET10_0 var assembly = new PersistedAssemblyBuilder(identity, typeof(object).Assembly); @@ -180,13 +203,9 @@ private static void WriteThrowingAssembly(string path, string name, string fileV var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(identity, AssemblyBuilderAccess.Save, Path.GetDirectoryName(path)); var module = assembly.DefineDynamicModule(name, Path.GetFileName(path)); #endif - var versionConstructor = typeof(AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) }); - assembly.SetCustomAttribute(new CustomAttributeBuilder(versionConstructor, new object[] { fileVersion })); - if (ambiguousInformationalVersion) { - var constructor = typeof(AssemblyInformationalVersionAttribute).GetConstructor(new[] { typeof(string) }); - assembly.SetCustomAttribute(new CustomAttributeBuilder(constructor, new object[] { "first" })); - assembly.SetCustomAttribute(new CustomAttributeBuilder(constructor, new object[] { "second" })); - } + assembly.SetCustomAttribute(VersionAttribute(fileVersion)); + foreach (var attribute in extraVersions) + assembly.SetCustomAttribute(attribute); var type = module.DefineType(ModuleFixtureType, TypeAttributes.Public); var method = type.DefineMethod(ModuleFixtureMethod, MethodAttributes.Public | MethodAttributes.Static, typeof(void), new[] { typeof(Exception) }); method.SetImplementationFlags(MethodImplAttributes.NoInlining); @@ -203,8 +222,43 @@ private static void WriteThrowingAssembly(string path, string name, string fileV #endif } + private static CustomAttributeBuilder VersionAttribute(string value) where T : Attribute { + return new CustomAttributeBuilder(typeof(T).GetConstructor(new[] { typeof(string) }), new object[] { value }); + } + + private static Assembly LoadInMemory(string name, params CustomAttributeBuilder[] extraVersions) { + string path = Path.Combine(Path.GetTempPath(), name + ".dll"); + try { + WriteThrowingAssembly(path, name, "1.2.3.4", extraVersions); + return Assembly.Load(File.ReadAllBytes(path)); + } finally { + File.Delete(path); + } + } + + [Theory] + [InlineData(false, false, "release")] + [InlineData(true, false, "1.2.3.4")] + [InlineData(true, true, "1.0.0.0")] + public void ToModuleInfo_VersionAttributes_UsesMostSpecificUnambiguousVersion(bool repeatInfo, bool repeatFile, string expected) { + // Arrange + var versions = new List { VersionAttribute("release") }; + if (repeatInfo) + versions.Add(VersionAttribute("other")); + if (repeatFile) + versions.Add(VersionAttribute("9.9.9.9")); + var assembly = LoadInMemory("Synthetic.Version" + Guid.NewGuid().ToString("N"), versions.ToArray()); + + // Act + var module = assembly.ToModuleInfo(); + + // Assert + Assert.Equal(expected, module.Version); + } + [Fact] - public void WillHonorDynamicAndLocationlessModuleFiltering() { + public void GetLoadedModules_DynamicAndLocationlessAssemblies_HonorsFiltersAndSkipsUnreadableMetadata() { + // Arrange var name = new AssemblyName("Synthetic.Dynamic" + Guid.NewGuid().ToString("N")) { Version = new Version(2, 3, 4, 5) }; #if NET10_0 var dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); @@ -212,42 +266,35 @@ public void WillHonorDynamicAndLocationlessModuleFiltering() { var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); #endif var dynamicModule = dynamicAssembly.DefineDynamicModule(name.Name); - Assert.Equal("2.3.4.5", dynamicModule.ToModuleInfo().Version); - string memoryName = "Synthetic.InMemory" + Guid.NewGuid().ToString("N"); - string path = Path.Combine(Path.GetTempPath(), memoryName + ".dll"); - try { - WriteThrowingAssembly(path, memoryName, "1.2.3.4", ambiguousInformationalVersion: true); - var memoryAssembly = Assembly.Load(File.ReadAllBytes(path)); - Assert.Empty(memoryAssembly.Location); - Assert.Equal("1.2.3.4", memoryAssembly.ToModuleInfo().Version); - - var log = new Logging.NullExceptionlessLog(); - var regular = ToErrorModelExtensions.GetLoadedModules(log); - Assert.DoesNotContain(regular, m => m.Name == name.Name || m.Name == memoryName); - var system = ToErrorModelExtensions.GetLoadedModules(log, includeSystem: true); - Assert.Contains(system, m => m.Name == typeof(object).Assembly.GetName().Name); - string linqAssembly = typeof(Enumerable).Assembly.GetName().Name; - Assert.Contains(system, m => m.Name == linqAssembly); - var all = ToErrorModelExtensions.GetLoadedModules(log, includeDynamic: true); - Assert.DoesNotContain(all, m => m.Name == linqAssembly); - Assert.Contains(all, m => m.Name == name.Name && m.Version == "2.3.4.5"); - Assert.Contains(all, m => m.Name == memoryName && m.Version == "1.2.3.4"); - - var generated = typeof(System.CodeDom.Compiler.GeneratedCodeAttribute).GetConstructor(new[] { typeof(string), typeof(string) }); - dynamicAssembly.SetCustomAttribute(new CustomAttributeBuilder(generated, new object[] { "Synthetic", "1" })); - Assert.DoesNotContain(ToErrorModelExtensions.GetLoadedModules(log, includeDynamic: true), m => m.Name == name.Name); - - // A malformed attribute on one assembly must not interrupt the inventory. - var fileVersion = typeof(AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) }); - dynamicAssembly.SetCustomAttribute(fileVersion, new byte[] { 0, 0 }); - Assert.Null(dynamicModule.ToModuleInfo()); - var remaining = ToErrorModelExtensions.GetLoadedModules(log, includeSystem: true, includeDynamic: true); - Assert.DoesNotContain(remaining, m => m.Name == name.Name); - Assert.Contains(remaining, m => m.Name == memoryName && m.Version == "1.2.3.4"); - } finally { - File.Delete(path); - } + var memoryAssembly = LoadInMemory(memoryName); + var log = new Logging.NullExceptionlessLog(); + string linqAssembly = typeof(Enumerable).Assembly.GetName().Name; + var generated = typeof(System.CodeDom.Compiler.GeneratedCodeAttribute).GetConstructor(new[] { typeof(string), typeof(string) }); + var fileVersion = typeof(AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) }); + + // Act + var regular = ToErrorModelExtensions.GetLoadedModules(log); + var system = ToErrorModelExtensions.GetLoadedModules(log, includeSystem: true); + var all = ToErrorModelExtensions.GetLoadedModules(log, includeDynamic: true); + dynamicAssembly.SetCustomAttribute(new CustomAttributeBuilder(generated, new object[] { "Synthetic", "1" })); + var afterGenerated = ToErrorModelExtensions.GetLoadedModules(log, includeDynamic: true); + dynamicAssembly.SetCustomAttribute(fileVersion, new byte[] { 0, 0 }); + var unreadable = dynamicModule.ToModuleInfo(); + var remaining = ToErrorModelExtensions.GetLoadedModules(log, includeSystem: true, includeDynamic: true); + + // Assert + Assert.Empty(memoryAssembly.Location); + Assert.DoesNotContain(regular, m => m.Name == name.Name || m.Name == memoryName); + Assert.Contains(system, m => m.Name == typeof(object).Assembly.GetName().Name); + Assert.Contains(system, m => m.Name == linqAssembly); + Assert.DoesNotContain(all, m => m.Name == linqAssembly); + Assert.Contains(all, m => m.Name == name.Name && m.Version is "2.3.4.5"); + Assert.Contains(all, m => m.Name == memoryName && m.Version is "1.2.3.4"); + Assert.DoesNotContain(afterGenerated, m => m.Name == name.Name); + Assert.Null(unreadable); + Assert.DoesNotContain(remaining, m => m.Name == name.Name); + Assert.Contains(remaining, m => m.Name == memoryName && m.Version is "1.2.3.4"); } [Fact] From 04453701dfb599efb36556856a49123abd9fda76 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Wed, 25 Nov 2026 14:48:56 -0800 Subject: [PATCH 08/11] Explain module lookup lifetime and duplicate version fallback --- src/Exceptionless/Extensions/ReflectionExtensions.cs | 1 + src/Exceptionless/Extensions/ToErrorModelExtensions.cs | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/Exceptionless/Extensions/ReflectionExtensions.cs b/src/Exceptionless/Extensions/ReflectionExtensions.cs index a698d279..dd30a3b2 100644 --- a/src/Exceptionless/Extensions/ReflectionExtensions.cs +++ b/src/Exceptionless/Extensions/ReflectionExtensions.cs @@ -45,6 +45,7 @@ public static string GetInformationalVersion(this Assembly assembly) { } private static T GetSingleVersionAttribute(this Assembly assembly) where T : Attribute { + // Version attributes are single-use. If an emitted assembly repeats one, fall back to the next version source. var matches = assembly.GetCustomAttributes(typeof(T), inherit: false); if (matches.Length is not 1) return null; diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index 74bb6e9a..5805dd14 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -53,6 +53,8 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie }; if (!isInner && client.Configuration.IncludeModules) { + // Rebuild the frame lookup once per exception chain because assemblies can load or unload. + // Only file-backed module metadata is reused across errors. moduleAssemblies = new List(); error.Modules = GetLoadedModules(log, moduleAssemblies: moduleAssemblies); } From 08e1443cfe7039113de4e2d0aaf975589df0440f Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Thu, 26 Nov 2026 08:21:43 -0800 Subject: [PATCH 09/11] Preserve matching assembly version attributes --- .../Extensions/ReflectionExtensions.cs | 19 +++++++++++++------ .../Plugins/020_ErrorPluginTests.cs | 19 +++++++++++-------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/Exceptionless/Extensions/ReflectionExtensions.cs b/src/Exceptionless/Extensions/ReflectionExtensions.cs index dd30a3b2..5ddd12d3 100644 --- a/src/Exceptionless/Extensions/ReflectionExtensions.cs +++ b/src/Exceptionless/Extensions/ReflectionExtensions.cs @@ -37,20 +37,27 @@ public static string GetVersion(this Assembly assembly) { } public static string GetFileVersion(this Assembly assembly) { - return assembly.GetSingleVersionAttribute()?.Version; + return assembly.GetVersionAttributeValue(static attribute => attribute.Version); } public static string GetInformationalVersion(this Assembly assembly) { - return assembly.GetSingleVersionAttribute()?.InformationalVersion; + return assembly.GetVersionAttributeValue(static attribute => attribute.InformationalVersion); } - private static T GetSingleVersionAttribute(this Assembly assembly) where T : Attribute { - // Version attributes are single-use. If an emitted assembly repeats one, fall back to the next version source. + private static string GetVersionAttributeValue(this Assembly assembly, Func getValue) where T : Attribute { var matches = assembly.GetCustomAttributes(typeof(T), inherit: false); - if (matches.Length is not 1) + if (matches.Length is 0) return null; - return matches[0] as T; + string version = getValue((T)matches[0]); + // Emitted assemblies can repeat a single-use attribute. Keep the value when the copies agree. + // A conflict skips only this version source, so the module can still use its file or assembly version. + for (int i = 1; i < matches.Length; i++) { + if (!String.Equals(version, getValue((T)matches[i]), StringComparison.Ordinal)) + return null; + } + + return version; } public static string GetCompany(this Assembly assembly) { diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index a02ff2e1..891dbbb9 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -237,16 +237,19 @@ private static Assembly LoadInMemory(string name, params CustomAttributeBuilder[ } [Theory] - [InlineData(false, false, "release")] - [InlineData(true, false, "1.2.3.4")] - [InlineData(true, true, "1.0.0.0")] - public void ToModuleInfo_VersionAttributes_UsesMostSpecificUnambiguousVersion(bool repeatInfo, bool repeatFile, string expected) { + [InlineData(null, null, "release")] + [InlineData("release", null, "release")] + [InlineData(null, "9.9.9.9", "release")] + [InlineData("other", null, "1.2.3.4")] + [InlineData("other", "1.2.3.4", "1.2.3.4")] + [InlineData("other", "9.9.9.9", "1.0.0.0")] + public void ToModuleInfo_VersionAttributes_UsesMostSpecificUnambiguousVersion(string? extraInfoVersion, string? extraFileVersion, string expected) { // Arrange var versions = new List { VersionAttribute("release") }; - if (repeatInfo) - versions.Add(VersionAttribute("other")); - if (repeatFile) - versions.Add(VersionAttribute("9.9.9.9")); + if (extraInfoVersion is not null) + versions.Add(VersionAttribute(extraInfoVersion)); + if (extraFileVersion is not null) + versions.Add(VersionAttribute(extraFileVersion)); var assembly = LoadInMemory("Synthetic.Version" + Guid.NewGuid().ToString("N"), versions.ToArray()); // Act From e3410260078e12b9a8dbb488edb06936f257c130 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Thu, 26 Nov 2026 09:28:51 -0800 Subject: [PATCH 10/11] Use the first assembly version attribute of each kind --- .../Extensions/ReflectionExtensions.cs | 22 +++------------- .../Plugins/020_ErrorPluginTests.cs | 25 ++++++++----------- 2 files changed, 14 insertions(+), 33 deletions(-) diff --git a/src/Exceptionless/Extensions/ReflectionExtensions.cs b/src/Exceptionless/Extensions/ReflectionExtensions.cs index 5ddd12d3..267af04d 100644 --- a/src/Exceptionless/Extensions/ReflectionExtensions.cs +++ b/src/Exceptionless/Extensions/ReflectionExtensions.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using System.Reflection; namespace Exceptionless { @@ -36,28 +37,13 @@ public static string GetVersion(this Assembly assembly) { return assembly.GetAssemblyName().Version.ToString(); } + // Emitted assemblies can repeat version attributes. Take the first match to avoid AmbiguousMatchException. public static string GetFileVersion(this Assembly assembly) { - return assembly.GetVersionAttributeValue(static attribute => attribute.Version); + return assembly.GetCustomAttributes().FirstOrDefault()?.Version; } public static string GetInformationalVersion(this Assembly assembly) { - return assembly.GetVersionAttributeValue(static attribute => attribute.InformationalVersion); - } - - private static string GetVersionAttributeValue(this Assembly assembly, Func getValue) where T : Attribute { - var matches = assembly.GetCustomAttributes(typeof(T), inherit: false); - if (matches.Length is 0) - return null; - - string version = getValue((T)matches[0]); - // Emitted assemblies can repeat a single-use attribute. Keep the value when the copies agree. - // A conflict skips only this version source, so the module can still use its file or assembly version. - for (int i = 1; i < matches.Length; i++) { - if (!String.Equals(version, getValue((T)matches[i]), StringComparison.Ordinal)) - return null; - } - - return version; + return assembly.GetCustomAttributes().FirstOrDefault()?.InformationalVersion; } public static string GetCompany(this Assembly assembly) { diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index 891dbbb9..d14d8d57 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -236,27 +236,22 @@ private static Assembly LoadInMemory(string name, params CustomAttributeBuilder[ } } - [Theory] - [InlineData(null, null, "release")] - [InlineData("release", null, "release")] - [InlineData(null, "9.9.9.9", "release")] - [InlineData("other", null, "1.2.3.4")] - [InlineData("other", "1.2.3.4", "1.2.3.4")] - [InlineData("other", "9.9.9.9", "1.0.0.0")] - public void ToModuleInfo_VersionAttributes_UsesMostSpecificUnambiguousVersion(string? extraInfoVersion, string? extraFileVersion, string expected) { + [Fact] + public void ToModuleInfo_DuplicateVersionAttributes_UsesFirstOfEachKind() { // Arrange - var versions = new List { VersionAttribute("release") }; - if (extraInfoVersion is not null) - versions.Add(VersionAttribute(extraInfoVersion)); - if (extraFileVersion is not null) - versions.Add(VersionAttribute(extraFileVersion)); - var assembly = LoadInMemory("Synthetic.Version" + Guid.NewGuid().ToString("N"), versions.ToArray()); + var assembly = LoadInMemory("Synthetic.Version" + Guid.NewGuid().ToString("N"), + VersionAttribute("preview"), + VersionAttribute("release"), + VersionAttribute("9.9.9.9")); + var firstInfo = assembly.GetCustomAttributes().First(); + var firstFile = assembly.GetCustomAttributes().First(); // Act var module = assembly.ToModuleInfo(); // Assert - Assert.Equal(expected, module.Version); + Assert.Equal(firstInfo.InformationalVersion, module.Version); + Assert.Equal(firstFile.Version, module.Data["FileVersion"]); } [Fact] From 2bdfbeb13fda0ddd12b72eee443887873f588428 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Sat, 28 Nov 2026 12:10:14 -0600 Subject: [PATCH 11/11] Reuse cached module metadata at every event position --- .../Extensions/ToErrorModelExtensions.cs | 137 +----------------- src/Exceptionless/Utility/ModuleMetadata.cs | 73 ++++++++++ .../Utility/ModuleMetadataReader.cs | 85 +++++++++++ .../Plugins/020_ErrorPluginTests.cs | 30 ++++ 4 files changed, 196 insertions(+), 129 deletions(-) create mode 100644 src/Exceptionless/Utility/ModuleMetadata.cs create mode 100644 src/Exceptionless/Utility/ModuleMetadataReader.cs diff --git a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs index 5805dd14..03e836c6 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -1,10 +1,7 @@ using System; -using System.CodeDom.Compiler; using System.Collections; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using System.Linq; using System.Reflection; using System.Security; @@ -13,14 +10,13 @@ using Exceptionless.Logging; using Exceptionless.Models; using Exceptionless.Models.Data; +using Exceptionless.Utility; using Module = Exceptionless.Models.Data.Module; using StackFrame = System.Diagnostics.StackFrame; namespace Exceptionless { internal static class ToErrorModelExtensions { - private const int MaxCachedModules = 1024; - private static readonly ConcurrentDictionary _moduleCache = new(); - private static readonly Queue _cachedPaths = new(); + private static readonly ModuleMetadataReader _moduleMetadata = new(cacheCapacity: 1024); private static readonly string[] _exceptionExclusions = { "@exceptionless", "Data", "HelpLink", "ExceptionContext", "InnerExceptions", "InnerException", "Errors", "Types", "Message", "Source", "StackTrace", "TargetSite", "HResult", @@ -141,12 +137,6 @@ private static bool ValueIsEmpty(object value) { return false; } - private static readonly List _msPublicKeyTokens = new List { - "b77a5c561934e089", - "b03f5f7f11d50a3a", - "31bf3856ad364e35" - }; - private static string GetMessage(this Exception exception, string typeName) { string defaultMessage = $"Exception of type '{typeName}' was thrown."; string message = !String.IsNullOrEmpty(exception.Message) ? exception.Message.Trim() : null; @@ -158,9 +148,9 @@ internal static ModuleCollection GetLoadedModules(IExceptionlessLog log, bool in try { var entryAssembly = Assembly.GetEntryAssembly(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { - // A single large inventory must not evict every entry on each error. - bool cacheMetadata = modules.Count < MaxCachedModules; - var module = TryGetModuleInfo(assembly, entryAssembly, log, includeSystem, includeDynamic, cacheMetadata); + // Later modules can reuse any cached path without evicting the start of a large inventory. + bool allowCacheEviction = modules.Count < _moduleMetadata.CacheCapacity; + var module = TryGetModuleInfo(assembly, entryAssembly, log, includeSystem, includeDynamic, allowCacheEviction); if (module is null) continue; @@ -282,7 +272,7 @@ public static Module ToModuleInfo(this Assembly assembly) { } private static Module TryGetModuleInfo(Assembly assembly, Assembly entryAssembly, IExceptionlessLog log, - bool includeSystem, bool includeDynamic, bool cacheMetadata = true) { + bool includeSystem, bool includeDynamic, bool allowCacheEviction = true) { try { string path = null; try { @@ -294,123 +284,12 @@ private static Module TryGetModuleInfo(Assembly assembly, Assembly entryAssembly log?.Error(typeof(ExceptionlessClient), ex, "Assembly location is unavailable."); } - var module = GetModuleMetadata(assembly, path, cacheMetadata, includeSystem, log); - if (module is not null) - module.IsEntry = ReferenceEquals(assembly, entryAssembly); - return module; + var metadata = _moduleMetadata.Read(assembly, path, includeSystem, allowCacheEviction, log); + return metadata?.CreateModule(isEntry: ReferenceEquals(assembly, entryAssembly)); } catch (Exception ex) { log?.Error(typeof(ExceptionlessClient), ex, "Error reading module metadata."); return null; } } - - private static Module GetModuleMetadata(Assembly assembly, string path, bool cacheMetadata, bool includeSystem, IExceptionlessLog log) { - Guid versionId = Guid.Empty; - if (cacheMetadata && !String.IsNullOrEmpty(path)) { - try { - versionId = assembly.ManifestModule.ModuleVersionId; - } catch { - // Restricted reflection can still provide the usual module metadata. - } - } - - Module metadata = null; - if (versionId != Guid.Empty && _moduleCache.TryGetValue(path, out var cached) && cached.VersionId == versionId) - metadata = cached.Metadata; - - AssemblyName name = null; - string publicKeyToken = null; - if (metadata is null) { - name = assembly.GetAssemblyName(); - if (name?.GetPublicKeyToken() is { Length: > 0 } token) - publicKeyToken = token.ToHex(); - } else { - publicKeyToken = metadata.Data.GetString("PublicKeyToken"); - } - - if (!includeSystem) { - try { - if (_msPublicKeyTokens.Contains(publicKeyToken) || assembly.IsDefined(typeof(GeneratedCodeAttribute), inherit: false)) - return null; - } catch (Exception ex) { - log.Error(typeof(ExceptionlessClient), ex, "Error while checking if assembly " + assembly.FullName + " should be added to modules:" + ex.Message); - } - } - - if (metadata is null) { - metadata = ReadModuleMetadata(assembly, name, publicKeyToken, path); - if (versionId == Guid.Empty) - return metadata; - - // Publish and evict under the same lock so each cached path is queued exactly once. - lock (_cachedPaths) { - if (!_moduleCache.ContainsKey(path)) { - if (_cachedPaths.Count >= MaxCachedModules) - _moduleCache.TryRemove(_cachedPaths.Dequeue(), out _); - _cachedPaths.Enqueue(path); - } - _moduleCache[path] = new CachedModule(versionId, metadata); - } - } - - var module = new Module { - Name = metadata.Name, - Version = metadata.Version, - CreatedDate = metadata.CreatedDate, - ModifiedDate = metadata.ModifiedDate - }; - foreach (var entry in metadata.Data) - module.Data.Add(entry.Key, entry.Value); - return module; - } - - private sealed class CachedModule { - public CachedModule(Guid versionId, Module metadata) { - VersionId = versionId; - Metadata = metadata; - } - - public Guid VersionId { get; } - public Module Metadata { get; } - } - - private static Module ReadModuleMetadata(Assembly assembly, AssemblyName name, string publicKeyToken, string path) { - var mod = new Module(); - string infoVersion = assembly.GetInformationalVersion(); - string fileVersion = assembly.GetFileVersion(); - - if (name is not null) { - mod.Name = name.Name; - string version = name.Version?.ToString(); - mod.Version = infoVersion ?? fileVersion ?? version; - if (publicKeyToken is not null) - mod.Data["PublicKeyToken"] = publicKeyToken; - - if (!String.IsNullOrEmpty(version) && version != mod.Version) - mod.Data["Version"] = version; - } - - if (!String.IsNullOrEmpty(infoVersion) && infoVersion != mod.Version) - mod.Data["ProductVersion"] = infoVersion; - - if (!String.IsNullOrEmpty(fileVersion) && fileVersion != mod.Version) - mod.Data["FileVersion"] = fileVersion; - - if (!String.IsNullOrEmpty(path)) { - try { - var file = new FileInfo(path); - mod.CreatedDate = file.CreationTimeUtc; - mod.ModifiedDate = file.LastWriteTimeUtc; - return mod; - } catch { - // Try each timestamp independently on restricted or unavailable files. - } - } - - mod.CreatedDate = assembly.GetCreationTime().GetValueOrDefault(); - mod.ModifiedDate = assembly.GetLastWriteTime().GetValueOrDefault(); - - return mod; - } } } diff --git a/src/Exceptionless/Utility/ModuleMetadata.cs b/src/Exceptionless/Utility/ModuleMetadata.cs new file mode 100644 index 00000000..a6291ecd --- /dev/null +++ b/src/Exceptionless/Utility/ModuleMetadata.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using System.Reflection; +using Module = Exceptionless.Models.Data.Module; + +namespace Exceptionless.Utility { + // The cache can outlive an assembly's load context. Keep only strings and values here. + internal sealed class ModuleMetadata { + private readonly string _name; + private readonly string _version; + private readonly string _assemblyVersion; + private readonly string _productVersion; + private readonly string _fileVersion; + private readonly DateTime _createdDate; + private readonly DateTime _modifiedDate; + + public ModuleMetadata(Assembly assembly, AssemblyName name, string publicKeyToken, string path, Guid versionId) { + VersionId = versionId; + PublicKeyToken = publicKeyToken; + _name = name?.Name; + + string assemblyVersion = name?.Version?.ToString(); + string infoVersion = assembly.GetInformationalVersion(); + string fileVersion = assembly.GetFileVersion(); + if (name is not null) + _version = infoVersion ?? fileVersion ?? assemblyVersion; + + // Module.Data carries only versions that differ from the displayed version. + if (!String.IsNullOrEmpty(assemblyVersion) && assemblyVersion != _version) + _assemblyVersion = assemblyVersion; + if (!String.IsNullOrEmpty(infoVersion) && infoVersion != _version) + _productVersion = infoVersion; + if (!String.IsNullOrEmpty(fileVersion) && fileVersion != _version) + _fileVersion = fileVersion; + + if (!String.IsNullOrEmpty(path)) { + try { + var file = new FileInfo(path); + _createdDate = file.CreationTimeUtc; + _modifiedDate = file.LastWriteTimeUtc; + return; + } catch { + // Try each timestamp independently on restricted or unavailable files. + } + } + + _createdDate = assembly.GetCreationTime().GetValueOrDefault(); + _modifiedDate = assembly.GetLastWriteTime().GetValueOrDefault(); + } + + public Guid VersionId { get; } + public string PublicKeyToken { get; } + + public Module CreateModule(bool isEntry) { + var module = new Module { + Name = _name, + Version = _version, + IsEntry = isEntry, + CreatedDate = _createdDate, + ModifiedDate = _modifiedDate + }; + if (PublicKeyToken is not null) + module.Data["PublicKeyToken"] = PublicKeyToken; + if (_assemblyVersion is not null) + module.Data["Version"] = _assemblyVersion; + if (_productVersion is not null) + module.Data["ProductVersion"] = _productVersion; + if (_fileVersion is not null) + module.Data["FileVersion"] = _fileVersion; + return module; + } + } +} diff --git a/src/Exceptionless/Utility/ModuleMetadataReader.cs b/src/Exceptionless/Utility/ModuleMetadataReader.cs new file mode 100644 index 00000000..8fed0e2e --- /dev/null +++ b/src/Exceptionless/Utility/ModuleMetadataReader.cs @@ -0,0 +1,85 @@ +using System; +using System.CodeDom.Compiler; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Exceptionless.Extensions; +using Exceptionless.Logging; + +namespace Exceptionless.Utility { + internal sealed class ModuleMetadataReader { + private static readonly string[] _msPublicKeyTokens = { + "b77a5c561934e089", + "b03f5f7f11d50a3a", + "31bf3856ad364e35" + }; + private readonly ConcurrentDictionary _cache = new(); + private readonly Queue _paths = new(); + + public ModuleMetadataReader(int cacheCapacity) { + if (cacheCapacity <= 0) + throw new ArgumentOutOfRangeException(nameof(cacheCapacity)); + CacheCapacity = cacheCapacity; + } + + public int CacheCapacity { get; } + + public ModuleMetadata Read(Assembly assembly, string path, bool includeSystem, bool allowCacheEviction, IExceptionlessLog log) { + Guid versionId = Guid.Empty; + if (!String.IsNullOrEmpty(path)) { + try { + versionId = assembly.ManifestModule.ModuleVersionId; + } catch { + // Restricted reflection can still provide the usual module metadata. + } + } + + ModuleMetadata metadata = null; + if (versionId != Guid.Empty && _cache.TryGetValue(path, out var cached) && cached.VersionId == versionId) + metadata = cached; + + AssemblyName name = null; + string publicKeyToken = metadata?.PublicKeyToken; + if (metadata is null) { + name = assembly.GetAssemblyName(); + if (name?.GetPublicKeyToken() is { Length: > 0 } token) + publicKeyToken = token.ToHex(); + } + + if (!includeSystem) { + try { + if (_msPublicKeyTokens.Contains(publicKeyToken) || assembly.IsDefined(typeof(GeneratedCodeAttribute), inherit: false)) + return null; + } catch (Exception ex) { + log?.Error(typeof(ExceptionlessClient), ex, "Error while checking if assembly " + assembly.FullName + " should be added to modules:" + ex.Message); + } + } + + if (metadata is not null) + return metadata; + + metadata = new ModuleMetadata(assembly, name, publicKeyToken, path, versionId); + if (versionId != Guid.Empty) + Store(path, metadata, allowCacheEviction); + return metadata; + } + + private void Store(string path, ModuleMetadata metadata, bool allowEviction) { + lock (_paths) { + if (!_cache.ContainsKey(path)) { + if (_paths.Count == CacheCapacity) { + if (!allowEviction) + return; + + _cache.TryRemove(_paths.Dequeue(), out _); + } + + _paths.Enqueue(path); + } + + _cache[path] = metadata; + } + } + } +} diff --git a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs index d14d8d57..f8571d86 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -17,6 +17,7 @@ using Exceptionless.Models; using Exceptionless.Models.Data; using Exceptionless.Serializer; +using Exceptionless.Utility; using Xunit; namespace Exceptionless.Tests.Plugins { @@ -236,6 +237,35 @@ private static Assembly LoadInMemory(string name, params CustomAttributeBuilder[ } } + [Fact] + public void Read_EvictionDisabled_FillsFreeSlotsAndReusesCachedMetadata() { + // Arrange + var directory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"))); + try { + var reader = new ModuleMetadataReader(cacheCapacity: 1); + string firstPath = Path.Combine(directory.FullName, "first.dll"); + string secondPath = Path.Combine(directory.FullName, "second.dll"); + WriteThrowingAssembly(firstPath, "Synthetic.Cache", "1.2.3.4"); + File.Copy(firstPath, secondPath); + ModuleMetadata ReadCopy(string path) => reader.Read(Assembly.Load(File.ReadAllBytes(path)), path, + includeSystem: false, allowCacheEviction: false, log: null); + + // Act + var first = ReadCopy(firstPath); + var overflow = ReadCopy(secondPath); + var firstAgain = ReadCopy(firstPath); + var overflowAgain = ReadCopy(secondPath); + + // Assert + Assert.NotNull(first); + Assert.Same(first, firstAgain); + Assert.NotSame(overflow, overflowAgain); + Assert.Equal("1.2.3.4", overflow.CreateModule(isEntry: false).Version); + } finally { + directory.Delete(recursive: true); + } + } + [Fact] public void ToModuleInfo_DuplicateVersionAttributes_UsesFirstOfEachKind() { // Arrange