diff --git a/src/Exceptionless/Extensions/ReflectionExtensions.cs b/src/Exceptionless/Extensions/ReflectionExtensions.cs index bd3715ae..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,14 +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) { - var attr = assembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute; - return attr != null ? attr.Version : null; + return assembly.GetCustomAttributes().FirstOrDefault()?.Version; } public static string GetInformationalVersion(this Assembly assembly) { - var attr = assembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute; - return attr != null ? attr.InformationalVersion : null; + return assembly.GetCustomAttributes().FirstOrDefault()?.InformationalVersion; } 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 fcc6a350..03e836c6 100644 --- a/src/Exceptionless/Extensions/ToErrorModelExtensions.cs +++ b/src/Exceptionless/Extensions/ToErrorModelExtensions.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -11,12 +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 static readonly ConcurrentDictionary _moduleCache = new ConcurrentDictionary(); + 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", @@ -32,13 +32,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; return ToErrorModelInternal(exception, client); } - private static Error ToErrorModelInternal(Exception exception, ExceptionlessClient client, 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(); @@ -48,10 +48,14 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie Type = typeName }; - if (!isInner && client.Configuration.IncludeModules) - error.Modules = GetLoadedModules(log); + 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); + } - error.PopulateStackTrace(error, exception, log); + error.PopulateStackTrace(moduleAssemblies, exception, log); try { PropertyInfo info = type.GetProperty("HResult", BindingFlags.Public | BindingFlags.Instance); @@ -63,9 +67,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(error, exception.TargetSite); + error.TargetMethod.PopulateMethod(moduleAssemblies, exception.TargetSite); } } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating TargetMethod: " + ex.Message); @@ -115,8 +119,8 @@ private static Error ToErrorModelInternal(Exception exception, ExceptionlessClie log.Error(typeof(ExceptionlessClient), ex, "Error populating extra exception properties: " + ex.Message); } - if (exception.InnerException != null) - error.Inner = ToErrorModelInternal(exception.InnerException, client, true); + if (exception.InnerException is not null) + error.Inner = ToErrorModelInternal(exception.InnerException, client, moduleAssemblies, isInner: true); return error; } @@ -133,53 +137,26 @@ 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; 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, List moduleAssemblies = null) { var modules = new ModuleCollection(); try { - int id = 1; + var entryAssembly = Assembly.GetEntryAssembly(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { - if (!includeDynamic && assembly.IsDynamic) + // 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; - try { - if (!includeDynamic && String.IsNullOrEmpty(assembly.Location)) - 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); - } - - 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); - } - } - - var module = assembly.ToModuleInfo(); - module.ModuleId = id; + module.ModuleId = modules.Count + 1; modules.Add(module); - - id++; + moduleAssemblies?.Add(assembly); } } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error loading modules: " + ex.Message); @@ -188,7 +165,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, List moduleAssemblies, Exception exception, IExceptionlessLog log) { StackFrame[] frames = null; try { var st = new EnhancedStackTrace(exception); @@ -220,7 +197,7 @@ private static void PopulateStackTrace(this Error error, Error root, Exception e } try { - stackFrame.PopulateMethod(root, frame.GetMethod()); + stackFrame.PopulateMethod(moduleAssemblies, frame.GetMethod()); } catch (Exception ex) { log.Error(typeof(ExceptionlessClient), ex, "Error populating StackFrame method info: " + ex.Message); } @@ -229,8 +206,8 @@ private static void PopulateStackTrace(this Error error, Error root, Exception e } } - private static void PopulateMethod(this Method method, Error root, MethodBase methodBase) { - if (methodBase == null) + private static void PopulateMethod(this Method method, List moduleAssemblies, MethodBase methodBase) { + if (methodBase is null) return; method.Name = methodBase.Name; @@ -267,13 +244,17 @@ private static void PopulateMethod(this Method method, Error root, MethodBase me method.Parameters.Add(parm); } - method.ModuleId = GetModuleId(root, methodBase.Module); + method.ModuleId = GetModuleId(moduleAssemblies, methodBase); } - 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; + 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; } return -1; @@ -284,46 +265,31 @@ 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; - return _moduleCache.GetOrAdd(assembly.FullName, k => { - 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(); - 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; - - if (!String.IsNullOrEmpty(fileVersion) && fileVersion != mod.Version) - mod.Data["FileVersion"] = fileVersion; - - DateTime? creationTime = assembly.GetCreationTime(); - if (creationTime.HasValue) - mod.CreatedDate = creationTime.Value; - - DateTime? lastWriteTime = assembly.GetLastWriteTime(); - if (lastWriteTime.HasValue) - mod.ModifiedDate = lastWriteTime.Value; + return TryGetModuleInfo(assembly, Assembly.GetEntryAssembly(), log: null, includeSystem: true, includeDynamic: true); + } - if (assembly == Assembly.GetEntryAssembly()) - mod.IsEntry = true; + private static Module TryGetModuleInfo(Assembly assembly, Assembly entryAssembly, IExceptionlessLog log, + bool includeSystem, bool includeDynamic, bool allowCacheEviction = true) { + try { + string path = null; + try { + if (!assembly.IsDynamic) + path = assembly.Location; + 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 mod; - }); + 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; + } } } -} \ No newline at end of file +} 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 e0610a50..f8571d86 100644 --- a/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs +++ b/test/Exceptionless.Tests/Plugins/020_ErrorPluginTests.cs @@ -1,16 +1,330 @@ using System; using System.Collections; using System.Collections.Generic; +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 System.Threading.Tasks; +using Exceptionless.Dependency; +using Exceptionless.Extensions; using Exceptionless.Plugins; using Exceptionless.Plugins.Default; using Exceptionless.Models; using Exceptionless.Models.Data; +using Exceptionless.Serializer; +using Exceptionless.Utility; using Xunit; namespace Exceptionless.Tests.Plugins { public class ErrorPluginTests : PluginTestBase { public ErrorPluginTests(ITestOutputHelper output) : base(output) { } + 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 ToErrorModel_DuplicateAssembliesInLoadContexts_MapsFramesAndAllowsUnload(bool loadSameFile) { + // Arrange + var directory = Directory.CreateTempSubdirectory(); + try { + // 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 { + // Act + capturedEvent = VerifyModuleMappings(directory.FullName, loadSameFile, generation, out outerContext, out innerContext); + } finally { + 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); + } + } finally { + directory.Delete(recursive: true); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + 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); + 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, FixtureAssemblyName, outerVersion); + if (!loadSameFile) + WriteThrowingAssembly(innerPath, FixtureAssemblyName, innerVersion); + + return VerifyCapturedModules(outerContext.LoadFromAssemblyPath(outerPath), innerContext.LoadFromAssemblyPath(innerPath), outerVersion, innerVersion); + } finally { + innerContext.Unload(); + outerContext.Unload(); + } + } +#else + [Fact] + public void ToErrorModel_DuplicateAssembliesInAppDomain_MapsTargetMethodsToTheirModules() { + // Arrange + 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); + string json; + try { + var fixture = (ModuleDomainFixture)domain.CreateInstanceAndUnwrap(fixtureType.Assembly.FullName, fixtureType.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 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"); + 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) { + // 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 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); + 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 frameworkFrames = filtered.StackTrace.Where(f => f.DeclaringNamespace == typeof(Enumerable).Namespace).ToList(); + Assert.NotEmpty(frameworkFrames); + Assert.All(frameworkFrames, frame => Assert.Equal(-1, frame.ModuleId)); + Assert.Equal(2, simple.Modules.Where(m => m.Name is FixtureAssemblyName).Select(m => m.ModuleId).Distinct().Count()); + Assert.Empty(withoutModules.Modules); + Assert.Equal(-1, FixtureModuleId(withoutModules.Inner)); + return events[0]; + } + + 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); + 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 + 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); + 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(); +#if NET10_0 + assembly.Save(path); +#else + assembly.Save(Path.GetFileName(path)); +#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); + } + } + + [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 + 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(firstInfo.InformationalVersion, module.Version); + Assert.Equal(firstFile.Version, module.Data["FileVersion"]); + } + + [Fact] + 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); +#else + var dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); +#endif + var dynamicModule = dynamicAssembly.DefineDynamicModule(name.Name); + string memoryName = "Synthetic.InMemory" + Guid.NewGuid().ToString("N"); + 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] public void WillPreserveLineBreaks() { const string message = "Test\r\nLine\r\n\tBreaks";