[sgen] Evacuate from emptier blocks to fuller ones
[mono.git] / mcs / class / corlib / System.Diagnostics / StackTrace.cs
1 //
2 // System.Diagnostics.StackTrace.cs
3 //
4 // Author:
5 //      Alexander Klyubin (klyubin@aqris.com)
6 //      Dietmar Maurer (dietmar@ximian.com)
7 //
8 // (C) 2001
9 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
10 //
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:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
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.
29 //
30
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;
38 using System.Text;
39 using System.Threading;
40
41 namespace System.Diagnostics {
42
43         [Serializable]
44         [ComVisible (true)]
45         [MonoTODO ("Serialized objects are not compatible with .NET")]
46         public class StackTrace {
47
48         // TraceFormat is Used to specify options for how the 
49         // string-representation of a StackTrace should be generated.
50         internal enum TraceFormat 
51         {
52             Normal,
53             TrailingNewLine,        // include a trailing new line character
54             NoResourceLookup    // to prevent infinite resource recusion
55         }
56
57                 public const int METHODS_TO_SKIP = 0;
58
59                 private StackFrame[] frames;
60                 readonly StackTrace[] captured_traces;
61                 private bool debug_info;
62
63                 public StackTrace ()
64                 {
65                         init_frames (METHODS_TO_SKIP, false);
66                 }
67
68                 public StackTrace (bool fNeedFileInfo)
69                 {
70                         init_frames (METHODS_TO_SKIP, fNeedFileInfo);
71                 }
72
73                 public StackTrace (int skipFrames)
74                 {
75                         init_frames (skipFrames, false);
76                 }
77
78                 public StackTrace (int skipFrames, bool fNeedFileInfo)
79                 {
80                         init_frames (skipFrames, fNeedFileInfo);
81                 }
82
83                 void init_frames (int skipFrames, bool fNeedFileInfo)
84                 {
85                         if (skipFrames < 0)
86                                 throw new ArgumentOutOfRangeException ("< 0", "skipFrames");
87
88                         StackFrame sf;
89                         var l = new List<StackFrame> ();
90
91                         skipFrames += 2;
92                         
93                         while ((sf = new StackFrame (skipFrames, fNeedFileInfo)) != null &&
94                                sf.GetMethod () != null) {
95                                 
96                                 l.Add (sf);
97                                 skipFrames++;
98                         };
99
100                         debug_info = fNeedFileInfo;
101                         frames = l.ToArray ();
102                 }
103                 
104                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
105                 extern static StackFrame [] get_trace (Exception e, int skipFrames, bool fNeedFileInfo);
106
107                 public StackTrace (Exception e)
108                         : this (e, METHODS_TO_SKIP, false)
109                 {
110                 }
111
112                 public StackTrace (Exception e, bool fNeedFileInfo)
113                         : this (e, METHODS_TO_SKIP, fNeedFileInfo)
114                 {
115                 }
116
117                 public StackTrace (Exception e, int skipFrames)
118                         : this (e, skipFrames, false)
119                 {
120                 }
121
122                 public StackTrace (Exception e, int skipFrames, bool fNeedFileInfo)
123                 {
124                         if (e == null)
125                                 throw new ArgumentNullException ("e");
126                         if (skipFrames < 0)
127                                 throw new ArgumentOutOfRangeException ("< 0", "skipFrames");
128
129                         frames = get_trace (e, skipFrames, fNeedFileInfo);
130
131                         captured_traces = e.captured_traces;
132                 }
133
134                 public StackTrace (StackFrame frame)
135                 {
136                         this.frames = new StackFrame [1];
137                         this.frames [0] = frame;
138                 }
139
140                 [MonoLimitation ("Not possible to create StackTraces from other threads")]
141                 [Obsolete]
142                 public StackTrace (Thread targetThread, bool needFileInfo)
143                 {
144                         if (targetThread == Thread.CurrentThread){
145                                 init_frames (METHODS_TO_SKIP, needFileInfo);
146                                 return;
147                         }
148                         
149                         throw new NotImplementedException ();
150                 }
151
152                 internal StackTrace (StackFrame[] frames) {
153                         this.frames = frames;
154                 }
155
156                 public virtual int FrameCount {
157                         get {
158                                 return (frames == null) ? 0 : frames.Length;
159                         }
160                 }
161
162                 public virtual StackFrame GetFrame (int index)
163                 {
164                         if ((index < 0) || (index >= FrameCount)) {
165                                 return null;
166                         }
167
168                         return frames [index];
169                 }
170
171                 [ComVisibleAttribute (false)]
172                 public virtual StackFrame[] GetFrames ()
173                 {
174                         return frames;
175                 }
176
177                 bool AddFrames (StringBuilder sb)
178                 {
179                         bool printOffset;
180                         string debugInfo, indentation;
181                         string unknown = Locale.GetText ("<unknown method>");
182
183                         indentation = "  ";
184                         debugInfo = Locale.GetText (" in {0}:{1} ");
185
186                         var newline = String.Format ("{0}{1}{2} ", Environment.NewLine, indentation,
187                                         Locale.GetText ("at"));
188
189                         int i;
190                         for (i = 0; i < FrameCount; i++) {
191                                 StackFrame frame = GetFrame (i);
192                                 if (i == 0)
193                                         sb.AppendFormat ("{0}{1} ", indentation, Locale.GetText ("at"));
194                                 else
195                                         sb.Append (newline);
196
197                                 if (frame.GetMethod () == null) {
198                                         string internal_name = frame.GetInternalMethodName ();
199                                         if (internal_name != null)
200                                                 sb.Append (internal_name);
201                                         else
202                                                 sb.AppendFormat ("<0x{0:x5} + 0x{1:x5}> {2}", frame.GetMethodAddress (), frame.GetNativeOffset (), unknown);
203                                 } else {
204                                         GetFullNameForStackTrace (sb, frame.GetMethod ());
205
206                                         if (frame.GetILOffset () == -1) {
207                                                 sb.AppendFormat (" <0x{0:x5} + 0x{1:x5}>", frame.GetMethodAddress (), frame.GetNativeOffset ());
208                                                 if (frame.GetMethodIndex () != 0xffffff)
209                                                         sb.AppendFormat (" {0}", frame.GetMethodIndex ());
210                                         } else {
211                                                 sb.AppendFormat (" [0x{0:x5}]", frame.GetILOffset ());
212                                         }
213
214                                         sb.AppendFormat (debugInfo, frame.GetSecureFileName (),
215                                                          frame.GetFileLineNumber ());
216                                 }
217                         }
218
219                         return i != 0;
220                 }
221
222                 // This method is also used with reflection by mono-symbolicate tool.
223                 // mono-symbolicate tool uses this method to check which method matches
224                 // the stack frame method signature.
225                 static void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
226                 {
227                         var declaringType = mi.DeclaringType;
228                         if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
229                                 declaringType = declaringType.GetGenericTypeDefinition ();
230
231                         // Get generic definition
232                         var bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
233                         foreach (var m in declaringType.GetMethods (bindingflags)) {
234                                 if (m.MetadataToken == mi.MetadataToken) {
235                                         mi = m;
236                                         break;
237                                 }
238                         }
239
240                         sb.Append (declaringType.ToString ());
241
242                         sb.Append (".");
243                         sb.Append (mi.Name);
244
245                         if (mi.IsGenericMethod) {
246                                 Type[] gen_params = mi.GetGenericArguments ();
247                                 sb.Append ("[");
248                                 for (int j = 0; j < gen_params.Length; j++) {
249                                         if (j > 0)
250                                                 sb.Append (",");
251                                         sb.Append (gen_params [j].Name);
252                                 }
253                                 sb.Append ("]");
254                         }
255
256                         ParameterInfo[] p = mi.GetParametersInternal ();
257
258                         sb.Append (" (");
259                         for (int i = 0; i < p.Length; ++i) {
260                                 if (i > 0)
261                                         sb.Append (", ");
262
263                                 Type pt = p[i].ParameterType;
264                                 if (pt.IsGenericType && ! pt.IsGenericTypeDefinition)
265                                         pt = pt.GetGenericTypeDefinition ();
266
267                                 if (pt.IsClass && !String.IsNullOrEmpty (pt.Namespace)) {
268                                         sb.Append (pt.Namespace);
269                                         sb.Append (".");
270                                 }
271                                 sb.Append (pt.Name);
272                                 if (p [i].Name != null) {
273                                         sb.Append (" ");
274                                         sb.Append (p [i].Name);
275                                 }
276                         }
277                         sb.Append (")");
278                 }
279
280                 public override string ToString ()
281                 {
282                         StringBuilder sb = new StringBuilder ();
283
284                         //
285                         // Add traces captured using ExceptionDispatchInfo
286                         //
287                         if (captured_traces != null) {
288                                 foreach (var t in captured_traces) {
289                                         if (!t.AddFrames (sb))
290                                                 continue;
291
292                                         sb.Append (Environment.NewLine);
293                                         sb.Append ("--- End of stack trace from previous location where exception was thrown ---");
294                                         sb.Append (Environment.NewLine);
295                                 }
296                         }
297
298                         AddFrames (sb);
299                         return sb.ToString ();
300                 }
301
302                 internal String ToString (TraceFormat traceFormat)
303                 {
304                         // TODO:
305                         return ToString ();
306                 }
307         }
308 }