[runtime] Actually clean up context-static data segments.
[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                 public virtual int FrameCount {
153                         get {
154                                 return (frames == null) ? 0 : frames.Length;
155                         }
156                 }
157
158                 public virtual StackFrame GetFrame (int index)
159                 {
160                         if ((index < 0) || (index >= FrameCount)) {
161                                 return null;
162                         }
163
164                         return frames [index];
165                 }
166
167                 [ComVisibleAttribute (false)]
168                 public virtual StackFrame[] GetFrames ()
169                 {
170                         return frames;
171                 }
172
173                 bool AddFrames (StringBuilder sb)
174                 {
175                         bool printOffset;
176                         string debugInfo, indentation;
177                         string unknown = Locale.GetText ("<unknown method>");
178
179                         indentation = "  ";
180                         debugInfo = Locale.GetText (" in {0}:{1} ");
181
182                         var newline = String.Format ("{0}{1}{2} ", Environment.NewLine, indentation,
183                                         Locale.GetText ("at"));
184
185                         int i;
186                         for (i = 0; i < FrameCount; i++) {
187                                 StackFrame frame = GetFrame (i);
188                                 if (i == 0)
189                                         sb.AppendFormat ("{0}{1} ", indentation, Locale.GetText ("at"));
190                                 else
191                                         sb.Append (newline);
192
193                                 if (frame.GetMethod () == null) {
194                                         string internal_name = frame.GetInternalMethodName ();
195                                         if (internal_name != null)
196                                                 sb.Append (internal_name);
197                                         else
198                                                 sb.AppendFormat ("<0x{0:x5} + 0x{1:x5}> {2}", frame.GetMethodAddress (), frame.GetNativeOffset (), unknown);
199                                 } else {
200                                         GetFullNameForStackTrace (sb, frame.GetMethod ());
201
202                                         if (frame.GetILOffset () == -1) {
203                                                 sb.AppendFormat (" <0x{0:x5} + 0x{1:x5}>", frame.GetMethodAddress (), frame.GetNativeOffset ());
204                                                 if (frame.GetMethodIndex () != 0xffffff)
205                                                         sb.AppendFormat (" {0}", frame.GetMethodIndex ());
206                                         } else {
207                                                 sb.AppendFormat (" [0x{0:x5}]", frame.GetILOffset ());
208                                         }
209
210                                         sb.AppendFormat (debugInfo, frame.GetSecureFileName (),
211                                                          frame.GetFileLineNumber ());
212                                 }
213                         }
214
215                         return i != 0;
216                 }
217
218                 // This method is also used with reflection by mono-symbolicate tool.
219                 // mono-symbolicate tool uses this method to check which method matches
220                 // the stack frame method signature.
221                 static void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
222                 {
223                         var declaringType = mi.DeclaringType;
224                         if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
225                                 declaringType = declaringType.GetGenericTypeDefinition ();
226
227                         // Get generic definition
228                         var bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
229                         foreach (var m in declaringType.GetMethods (bindingflags)) {
230                                 if (m.MetadataToken == mi.MetadataToken) {
231                                         mi = m;
232                                         break;
233                                 }
234                         }
235
236                         sb.Append (declaringType.ToString ());
237
238                         sb.Append (".");
239                         sb.Append (mi.Name);
240
241                         if (mi.IsGenericMethod) {
242                                 Type[] gen_params = mi.GetGenericArguments ();
243                                 sb.Append ("[");
244                                 for (int j = 0; j < gen_params.Length; j++) {
245                                         if (j > 0)
246                                                 sb.Append (",");
247                                         sb.Append (gen_params [j].Name);
248                                 }
249                                 sb.Append ("]");
250                         }
251
252                         ParameterInfo[] p = mi.GetParametersInternal ();
253
254                         sb.Append (" (");
255                         for (int i = 0; i < p.Length; ++i) {
256                                 if (i > 0)
257                                         sb.Append (", ");
258
259                                 Type pt = p[i].ParameterType;
260                                 if (pt.IsGenericType && ! pt.IsGenericTypeDefinition)
261                                         pt = pt.GetGenericTypeDefinition ();
262
263                                 if (pt.IsClass && !String.IsNullOrEmpty (pt.Namespace)) {
264                                         sb.Append (pt.Namespace);
265                                         sb.Append (".");
266                                 }
267                                 sb.Append (pt.Name);
268                                 if (p [i].Name != null) {
269                                         sb.Append (" ");
270                                         sb.Append (p [i].Name);
271                                 }
272                         }
273                         sb.Append (")");
274                 }
275
276                 public override string ToString ()
277                 {
278                         StringBuilder sb = new StringBuilder ();
279
280                         //
281                         // Add traces captured using ExceptionDispatchInfo
282                         //
283                         if (captured_traces != null) {
284                                 foreach (var t in captured_traces) {
285                                         if (!t.AddFrames (sb))
286                                                 continue;
287
288                                         sb.Append (Environment.NewLine);
289                                         sb.Append ("--- End of stack trace from previous location where exception was thrown ---");
290                                         sb.Append (Environment.NewLine);
291                                 }
292                         }
293
294                         AddFrames (sb);
295                         return sb.ToString ();
296                 }
297
298                 internal String ToString (TraceFormat traceFormat)
299                 {
300                         // TODO:
301                         return ToString ();
302                 }
303         }
304 }