Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/Exceptionless/Extensions/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Exceptionless {
Expand Down Expand Up @@ -36,19 +37,18 @@ 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<AssemblyFileVersionAttribute>().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<AssemblyInformationalVersionAttribute>().FirstOrDefault()?.InformationalVersion;
}

public static string GetCompany(this Assembly assembly) {
var attr = assembly.GetCustomAttribute(typeof(AssemblyCompanyAttribute)) as AssemblyCompanyAttribute;
return attr != null ? attr.Company : null;
}
}
}
}
150 changes: 58 additions & 92 deletions src/Exceptionless/Extensions/ToErrorModelExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
Expand All @@ -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<string, Module> _moduleCache = new ConcurrentDictionary<string, Module>();
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",
Expand All @@ -32,13 +32,13 @@ internal static class ToErrorModelExtensions {
/// ExceptionlessClient.Default.
/// </param>
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<Assembly> moduleAssemblies = null, bool isInner = false) {
var log = client.Configuration.Resolver.GetLog();
Type type = exception.GetType();
string typeName = type.GetTypeDisplayName();
Expand All @@ -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<Assembly>();
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);
Expand All @@ -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);
Expand Down Expand Up @@ -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;
}
Expand All @@ -133,53 +137,26 @@ private static bool ValueIsEmpty(object value) {
return false;
}

private static readonly List<string> _msPublicKeyTokens = new List<string> {
"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<Assembly> 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);
Expand All @@ -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<Assembly> moduleAssemblies, Exception exception, IExceptionlessLog log) {
StackFrame[] frames = null;
try {
var st = new EnhancedStackTrace(exception);
Expand Down Expand Up @@ -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);
}
Expand All @@ -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<Assembly> moduleAssemblies, MethodBase methodBase) {
if (methodBase is null)
return;

method.Name = methodBase.Name;
Expand Down Expand Up @@ -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<Assembly> 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;
Expand All @@ -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;
}
}
}
}
}
73 changes: 73 additions & 0 deletions src/Exceptionless/Utility/ModuleMetadata.cs
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
Loading
Loading