2 // System.Diagnostics.StackTrace.cs
5 // Alexander Klyubin (klyubin@aqris.com)
6 // Dietmar Maurer (dietmar@ximian.com)
9 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Collections.Generic;
32 using System.Globalization;
33 using System.Reflection;
34 using System.Runtime.CompilerServices;
35 using System.Runtime.InteropServices;
36 using System.Security;
37 using System.Security.Permissions;
39 using System.Threading;
42 namespace System.Diagnostics {
46 [MonoTODO ("Serialized objects are not compatible with .NET")]
47 public class StackTrace {
49 // TraceFormat is Used to specify options for how the
50 // string-representation of a StackTrace should be generated.
51 internal enum TraceFormat
54 TrailingNewLine, // include a trailing new line character
55 NoResourceLookup // to prevent infinite resource recusion
58 public const int METHODS_TO_SKIP = 0;
60 private StackFrame[] frames;
61 readonly StackTrace[] captured_traces;
62 private bool debug_info;
64 private static Dictionary<string, Func<StackTrace, string>> metadataHandlers;
66 [MethodImplAttribute (MethodImplOptions.NoInlining)]
69 init_frames (METHODS_TO_SKIP, false);
72 [MethodImplAttribute (MethodImplOptions.NoInlining)]
73 public StackTrace (bool fNeedFileInfo)
75 init_frames (METHODS_TO_SKIP, fNeedFileInfo);
78 [MethodImplAttribute (MethodImplOptions.NoInlining)]
79 public StackTrace (int skipFrames)
81 init_frames (skipFrames, false);
84 [MethodImplAttribute (MethodImplOptions.NoInlining)]
85 public StackTrace (int skipFrames, bool fNeedFileInfo)
87 init_frames (skipFrames, fNeedFileInfo);
90 [MethodImplAttribute (MethodImplOptions.NoInlining)]
91 void init_frames (int skipFrames, bool fNeedFileInfo)
94 throw new ArgumentOutOfRangeException ("< 0", "skipFrames");
97 var l = new List<StackFrame> ();
101 while ((sf = new StackFrame (skipFrames, fNeedFileInfo)) != null &&
102 sf.GetMethod () != null) {
108 debug_info = fNeedFileInfo;
109 frames = l.ToArray ();
112 [MethodImplAttribute(MethodImplOptions.InternalCall)]
113 extern static StackFrame [] get_trace (Exception e, int skipFrames, bool fNeedFileInfo);
115 public StackTrace (Exception e)
116 : this (e, METHODS_TO_SKIP, false)
120 public StackTrace (Exception e, bool fNeedFileInfo)
121 : this (e, METHODS_TO_SKIP, fNeedFileInfo)
125 public StackTrace (Exception e, int skipFrames)
126 : this (e, skipFrames, false)
130 public StackTrace (Exception e, int skipFrames, bool fNeedFileInfo)
133 throw new ArgumentNullException ("e");
135 throw new ArgumentOutOfRangeException ("< 0", "skipFrames");
137 frames = get_trace (e, skipFrames, fNeedFileInfo);
139 captured_traces = e.captured_traces;
142 public StackTrace (StackFrame frame)
144 this.frames = new StackFrame [1];
145 this.frames [0] = frame;
148 [MonoLimitation ("Not possible to create StackTraces from other threads")]
150 public StackTrace (Thread targetThread, bool needFileInfo)
152 if (targetThread == Thread.CurrentThread){
153 init_frames (METHODS_TO_SKIP, needFileInfo);
157 throw new NotImplementedException ();
160 internal StackTrace (StackFrame[] frames) {
161 this.frames = frames;
164 public virtual int FrameCount {
166 return (frames == null) ? 0 : frames.Length;
170 public virtual StackFrame GetFrame (int index)
172 if ((index < 0) || (index >= FrameCount)) {
176 return frames [index];
179 [ComVisibleAttribute (false)]
180 public virtual StackFrame[] GetFrames ()
185 static bool isAotidSet;
187 static string GetAotId ()
190 aotid = Assembly.GetAotId ();
192 aotid = new Guid (aotid).ToString ("N");
199 bool AddFrames (StringBuilder sb)
202 string debugInfo, indentation;
203 string unknown = Locale.GetText ("<unknown method>");
206 debugInfo = Locale.GetText (" in {0}:{1} ");
208 var newline = String.Format ("{0}{1}{2} ", Environment.NewLine, indentation,
209 Locale.GetText ("at"));
212 for (i = 0; i < FrameCount; i++) {
213 StackFrame frame = GetFrame (i);
215 sb.AppendFormat ("{0}{1} ", indentation, Locale.GetText ("at"));
219 if (frame.GetMethod () == null) {
220 string internal_name = frame.GetInternalMethodName ();
221 if (internal_name != null)
222 sb.Append (internal_name);
224 sb.AppendFormat ("<0x{0:x5} + 0x{1:x5}> {2}", frame.GetMethodAddress (), frame.GetNativeOffset (), unknown);
226 GetFullNameForStackTrace (sb, frame.GetMethod ());
228 if (frame.GetILOffset () == -1) {
229 sb.AppendFormat (" <0x{0:x5} + 0x{1:x5}>", frame.GetMethodAddress (), frame.GetNativeOffset ());
230 if (frame.GetMethodIndex () != 0xffffff)
231 sb.AppendFormat (" {0}", frame.GetMethodIndex ());
233 sb.AppendFormat (" [0x{0:x5}]", frame.GetILOffset ());
236 var filename = frame.GetSecureFileName ();
237 if (filename[0] == '<') {
238 var mvid = frame.GetMethod ().Module.ModuleVersionId.ToString ("N");
239 var aotid = GetAotId ();
240 if (frame.GetILOffset () != -1 || aotid == null) {
241 filename = string.Format ("<{0}>", mvid);
243 filename = string.Format ("<{0}#{1}>", mvid, aotid);
247 sb.AppendFormat (debugInfo, filename, frame.GetFileLineNumber ());
254 public static void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
256 var declaringType = mi.DeclaringType;
257 if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
258 declaringType = declaringType.GetGenericTypeDefinition ();
260 // Get generic definition
261 const BindingFlags bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
262 foreach (var m in declaringType.GetMethods (bindingflags)) {
263 if (m.MetadataToken == mi.MetadataToken) {
269 sb.Append (declaringType.ToString ());
274 if (mi.IsGenericMethod) {
275 Type[] gen_params = mi.GetGenericArguments ();
277 for (int j = 0; j < gen_params.Length; j++) {
280 sb.Append (gen_params [j].Name);
285 ParameterInfo[] p = mi.GetParameters ();
288 for (int i = 0; i < p.Length; ++i) {
292 Type pt = p[i].ParameterType;
293 if (pt.IsGenericType && ! pt.IsGenericTypeDefinition)
294 pt = pt.GetGenericTypeDefinition ();
296 sb.Append (pt.ToString());
298 if (p [i].Name != null) {
300 sb.Append (p [i].Name);
306 public override string ToString ()
308 StringBuilder sb = new StringBuilder ();
311 // Add traces captured using ExceptionDispatchInfo
313 if (captured_traces != null) {
314 foreach (var t in captured_traces) {
315 if (!t.AddFrames (sb))
318 sb.Append (Environment.NewLine);
319 sb.Append ("--- End of stack trace from previous location where exception was thrown ---");
320 sb.Append (Environment.NewLine);
326 return sb.ToString ();
329 internal String ToString (TraceFormat traceFormat)