From 20e77264345d3f39e4987cb2ce59edb6b6adf3e2 Mon Sep 17 00:00:00 2001 From: Jan Vorlicek Date: Fri, 19 Feb 2021 22:17:16 +0100 Subject: [PATCH] Make Exception.StackTrace resilient to missing attribute assemblies A customer has reported a problem when they could not get stack trace from an exception that they needed to log, because one of the methods on the stack or its defining type had an attribute from an assembly that was missing. This change fixes that by ignoring exceptions in attempts to get StackTraceHiddenAttribute, preferring to err on the side of getting a stack frame that was marked as hidden in the stack trace rather than not getting any stack trace at all. --- .../src/System/Diagnostics/StackTrace.cs | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs index 72858d2b4914f7..3c6ba961c79d30 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs @@ -354,19 +354,28 @@ private static bool ShowInStackTrace(MethodBase mb) return false; } - if (mb.IsDefined(typeof(StackTraceHiddenAttribute), inherit: false)) + try { - // Don't show where StackTraceHidden is applied to the method. - return false; - } + if (mb.IsDefined(typeof(StackTraceHiddenAttribute), inherit: false)) + { + // Don't show where StackTraceHidden is applied to the method. + return false; + } - Type? declaringType = mb.DeclaringType; - // Methods don't always have containing types, for example dynamic RefEmit generated methods. - if (declaringType != null && - declaringType.IsDefined(typeof(StackTraceHiddenAttribute), inherit: false)) + Type? declaringType = mb.DeclaringType; + // Methods don't always have containing types, for example dynamic RefEmit generated methods. + if (declaringType != null && + declaringType.IsDefined(typeof(StackTraceHiddenAttribute), inherit: false)) + { + // Don't show where StackTraceHidden is applied to the containing Type of the method. + return false; + } + } + catch { - // Don't show where StackTraceHidden is applied to the containing Type of the method. - return false; + // Getting the StackTraceHiddenAttribute has failed, behave as if it was not present. + // One of the reasons can be that the method mb or its declaring type use attributes + // defined in an assembly that is missing. } return true;