Merge pull request #1967 from D-POWER/master
[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                         : this (e, skipFrames, fNeedFileInfo, false)
124                 {
125                 }
126
127                 internal StackTrace (Exception e, int skipFrames, bool fNeedFileInfo, bool returnNativeFrames)
128                 {
129                         if (e == null)
130                                 throw new ArgumentNullException ("e");
131                         if (skipFrames < 0)
132                                 throw new ArgumentOutOfRangeException ("< 0", "skipFrames");
133
134                         frames = get_trace (e, skipFrames, fNeedFileInfo);
135
136                         if (!returnNativeFrames) {
137                                 bool resize = false;
138                                 for (int i = 0; i < frames.Length; ++i)
139                                         if (frames [i].GetMethod () == null)
140                                                 resize = true;
141
142                                 if (resize) {
143                                         var l = new List<StackFrame> ();
144
145                                         for (int i = 0; i < frames.Length; ++i)
146                                                 if (frames [i].GetMethod () != null)
147                                                         l.Add (frames [i]);
148
149                                         frames = l.ToArray ();
150                                 }
151                         }
152
153                         captured_traces = e.captured_traces;
154                 }
155
156                 public StackTrace (StackFrame frame)
157                 {
158                         this.frames = new StackFrame [1];
159                         this.frames [0] = frame;
160                 }
161
162                 [MonoLimitation ("Not possible to create StackTraces from other threads")]
163                 [Obsolete]
164                 public StackTrace (Thread targetThread, bool needFileInfo)
165                 {
166                         if (targetThread == Thread.CurrentThread){
167                                 init_frames (METHODS_TO_SKIP, needFileInfo);
168                                 return;
169                         }
170                         
171                         throw new NotImplementedException ();
172                 }
173
174                 public virtual int FrameCount {
175                         get {
176                                 return (frames == null) ? 0 : frames.Length;
177                         }
178                 }
179
180                 public virtual StackFrame GetFrame (int index)
181                 {
182                         if ((index < 0) || (index >= FrameCount)) {
183                                 return null;
184                         }
185
186                         return frames [index];
187                 }
188
189                 [ComVisibleAttribute (false)]
190                 public virtual StackFrame[] GetFrames ()
191                 {
192                         return frames;
193                 }
194
195                 bool AddFrames (StringBuilder sb, bool isException = false)
196                 {
197                         bool printOffset;
198                         string debugInfo, indentation;
199                         string unknown = Locale.GetText ("<unknown method>");
200
201                         if (isException) {
202                                 printOffset = true;
203                                 indentation = "  ";
204                                 debugInfo = Locale.GetText (" in {0}:{1} ");
205                         } else {
206                                 printOffset = false;
207                                 indentation = "   ";
208                                 debugInfo = Locale.GetText (" in {0}:line {1}");
209                         }
210
211                         var newline = String.Format ("{0}{1}{2} ", Environment.NewLine, indentation,
212                                         Locale.GetText ("at"));
213
214                         int i;
215                         for (i = 0; i < FrameCount; i++) {
216                                 StackFrame frame = GetFrame (i);
217                                 if (i == 0)
218                                         sb.AppendFormat ("{0}{1} ", indentation, Locale.GetText ("at"));
219                                 else
220                                         sb.Append (newline);
221
222                                 if (frame.GetMethod () == null) {
223                                         string internal_name = frame.GetInternalMethodName ();
224                                         if (internal_name != null)
225                                                 sb.Append (internal_name);
226                                         else if (printOffset)
227                                                 sb.AppendFormat ("<0x{0:x5} + 0x{1:x5}> {2}", frame.GetMethodAddress (), frame.GetNativeOffset (), unknown);
228                                         else
229                                                 sb.AppendFormat (unknown);
230                                 } else {
231                                         GetFullNameForStackTrace (sb, frame.GetMethod ());
232
233                                         if (printOffset) {
234                                                 if (frame.GetILOffset () == -1) {
235                                                         sb.AppendFormat (" <0x{0:x5} + 0x{1:x5}>", frame.GetMethodAddress (), frame.GetNativeOffset ());
236                                                         if (frame.GetMethodIndex () != 0xffffff)
237                                                                 sb.AppendFormat (" {0}", frame.GetMethodIndex ());
238                                                 } else {
239                                                         sb.AppendFormat (" [0x{0:x5}]", frame.GetILOffset ());
240                                                 }
241                                         }
242
243                                         sb.AppendFormat (debugInfo, frame.GetSecureFileName (),
244                                                          frame.GetFileLineNumber ());
245                                 }
246                         }
247
248                         return i != 0;
249                 }
250
251                 // This method is also used with reflection by mono-symbolicate tool.
252                 // mono-symbolicate tool uses this method to check which method matches
253                 // the stack frame method signature.
254                 static void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
255                 {
256                         var declaringType = mi.DeclaringType;
257                         if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
258                                 declaringType = declaringType.GetGenericTypeDefinition ();
259
260                         // Get generic definition
261                         var bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
262                         foreach (var m in declaringType.GetMethods (bindingflags)) {
263                                 if (m.MetadataToken == mi.MetadataToken) {
264                                         mi = m;
265                                         break;
266                                 }
267                         }
268
269                         sb.Append (declaringType.ToString ());
270
271                         sb.Append (".");
272                         sb.Append (mi.Name);
273
274                         if (mi.IsGenericMethod) {
275                                 Type[] gen_params = mi.GetGenericArguments ();
276                                 sb.Append ("[");
277                                 for (int j = 0; j < gen_params.Length; j++) {
278                                         if (j > 0)
279                                                 sb.Append (",");
280                                         sb.Append (gen_params [j].Name);
281                                 }
282                                 sb.Append ("]");
283                         }
284
285                         ParameterInfo[] p = mi.GetParametersInternal ();
286
287                         sb.Append (" (");
288                         for (int i = 0; i < p.Length; ++i) {
289                                 if (i > 0)
290                                         sb.Append (", ");
291
292                                 Type pt = p[i].ParameterType;
293                                 if (pt.IsGenericType && ! pt.IsGenericTypeDefinition)
294                                         pt = pt.GetGenericTypeDefinition ();
295
296                                 if (pt.IsClass && !String.IsNullOrEmpty (pt.Namespace)) {
297                                         sb.Append (pt.Namespace);
298                                         sb.Append (".");
299                                 }
300                                 sb.Append (pt.Name);
301                                 if (p [i].Name != null) {
302                                         sb.Append (" ");
303                                         sb.Append (p [i].Name);
304                                 }
305                         }
306                         sb.Append (")");
307                 }
308
309                 public override string ToString ()
310                 {
311                         StringBuilder sb = new StringBuilder ();
312
313                         //
314                         // Add traces captured using ExceptionDispatchInfo
315                         //
316                         if (captured_traces != null) {
317                                 foreach (var t in captured_traces) {
318                                         if (!t.AddFrames (sb, true))
319                                                 continue;
320
321                                         sb.Append (Environment.NewLine);
322                                         sb.Append ("--- End of stack trace from previous location where exception was thrown ---");
323                                         sb.Append (Environment.NewLine);
324                                 }
325                         }
326
327                         AddFrames (sb);
328                         return sb.ToString ();
329                 }
330
331                 internal String ToString (TraceFormat traceFormat)
332                 {
333                         // TODO:
334                         return ToString ();
335                 }
336         }
337 }