ec1529e082ee4907281fb85a29652385c57d596d
[mono.git] / mcs / class / corlib / System / Exception.cs
1 //
2 // System.Exception.cs
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Patrik Torstensson
7 //
8 // (C) Ximian, Inc.  http://www.ximian.com
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;
32 using System.Diagnostics;
33 using System.Reflection;
34 using System.Text;
35 using System.Runtime.InteropServices;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.Serialization;
38 using System.Security.Permissions;
39
40 namespace System
41 {
42         [Serializable]
43         [ComVisible(true)]
44         [ComDefaultInterface (typeof (_Exception))]
45         [ClassInterface (ClassInterfaceType.None)]
46         [StructLayout (LayoutKind.Sequential)]
47         public class Exception : ISerializable, _Exception
48         {
49 #pragma warning disable 169, 649
50                 #region Sync with object-internals.h
51                 /* Stores the IPs and the generic sharing infos
52                    (vtable/MRGCTX) of the frames. */
53                 IntPtr [] trace_ips;
54                 Exception inner_exception;
55                 internal string message;
56                 string help_link;
57                 string class_name;
58                 string stack_trace;
59                 // formerly known as remote_stack_trace (see #425512):
60                 string _remoteStackTraceString;
61                 int remote_stack_index;
62                 internal int hresult = -2146233088;
63                 string source;
64                 IDictionary _data;
65                 StackTrace[] captured_traces;
66                 IntPtr[] native_trace_ips;
67                 #endregion
68 #pragma warning restore 169, 649
69
70                 /* Don't add fields here, the runtime depends on the layout of subclasses */
71
72                 public Exception ()
73                 {
74                 }
75
76                 public Exception (string message)
77                 {
78                         this.message = message;
79                 }
80
81                 protected Exception (SerializationInfo info, StreamingContext context)
82                 {
83                         if (info == null)
84                                 throw new ArgumentNullException ("info");
85
86                         class_name          = info.GetString ("ClassName");
87                         message             = info.GetString ("Message");
88                         help_link           = info.GetString ("HelpURL");
89                         stack_trace         = info.GetString ("StackTraceString");
90                         _remoteStackTraceString  = info.GetString ("RemoteStackTraceString");
91                         remote_stack_index  = info.GetInt32  ("RemoteStackIndex");
92                         hresult             = info.GetInt32  ("HResult");
93                         source              = info.GetString ("Source");
94                         inner_exception     = (Exception) info.GetValue ("InnerException", typeof (Exception));
95
96                         try {
97                                 _data = (IDictionary) info.GetValue ("Data", typeof (IDictionary));
98                         } catch (SerializationException) {
99                                 // member did not exist in .NET 1.x
100                         }
101                 }
102
103                 public Exception (string message, Exception innerException)
104                 {
105                         inner_exception = innerException;
106                         this.message = message;
107                 }
108
109                 public Exception InnerException {
110                         get { return inner_exception; }
111                 }
112
113                 public virtual string HelpLink {
114                         get { return help_link; }
115                         set { help_link = value; }
116                 }
117
118 #if NET_4_5
119                 public int HResult {
120                         get { return hresult; }
121                         protected set { hresult = value; }
122                 }
123 #else
124                 protected int HResult {
125                         get { return hresult; }
126                         set { hresult = value; }
127                 }
128 #endif
129                 internal void SetMessage (string s)
130                 {
131                         message = s;
132                 }
133
134                 internal void SetStackTrace (string s)
135                 {
136                         stack_trace = s;
137                 }
138
139                 string ClassName {
140                         get {
141                                 if (class_name == null)
142                                         class_name = GetType ().ToString ();
143                                 return class_name;
144                         }
145                 }
146
147                 public virtual string Message {
148                         get {
149                                 if (message == null)
150                                         message = string.Format (Locale.GetText ("Exception of type '{0}' was thrown."),
151                                                 ClassName);
152
153                                 return message;
154                         }
155                 }
156                 
157 #if NET_4_0
158                 [MonoTODO]
159                 protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState {
160                         add {
161                         }
162                         remove {
163                         }
164                 }
165 #endif
166
167                 public virtual string Source {
168                         get {
169                                 if (source == null) {
170                                         StackTrace st = new StackTrace (this, true);
171                                         if (st.FrameCount > 0) {
172                                                 StackFrame sf = st.GetFrame (0);
173                                                 if (st != null) {
174                                                         MethodBase method = sf.GetMethod ();
175                                                         if (method != null) {
176                                                                 source = method.DeclaringType.Assembly.UnprotectedGetName ().Name;
177                                                         }
178                                                 }
179                                         }
180                                 }
181
182                                 // source can be null
183                                 return source;
184                         }
185
186                         set {
187                                 source = value;
188                         }
189                 }
190
191                 bool AddFrames (StringBuilder sb, string newline, string unknown, StackTrace st)
192                 {
193                         int i;
194                         for (i = 0; i < st.FrameCount; i++) {
195                                 StackFrame frame = st.GetFrame (i);
196                                 if (i == 0)
197                                         sb.AppendFormat ("  {0} ", Locale.GetText ("at"));
198                                 else
199                                         sb.Append (newline);
200
201                                 if (frame.GetMethod () == null) {
202                                         string internal_name = frame.GetInternalMethodName ();
203                                         if (internal_name != null)
204                                                 sb.Append (internal_name);
205                                         else
206                                                 sb.AppendFormat ("<0x{0:x5}> {1}", frame.GetNativeOffset (), unknown);
207                                 } else {
208                                         GetFullNameForStackTrace (sb, frame.GetMethod ());
209
210                                         if (frame.GetILOffset () == -1)
211                                                 sb.AppendFormat (" <0x{0:x5}> ", frame.GetNativeOffset ());
212                                         else
213                                                 sb.AppendFormat (" [0x{0:x5}] ", frame.GetILOffset ());
214
215                                         sb.AppendFormat ("in {0}:{1} ", frame.GetSecureFileName (),
216                                                                          frame.GetFileLineNumber ());
217                                 }
218                         }
219
220                         return i != 0;
221                 }
222
223                 public virtual string StackTrace {
224                         get {
225                                 if (stack_trace != null)
226                                         return stack_trace;
227
228                                 if (trace_ips == null)
229                                         /* Not thrown yet */
230                                         return null;
231
232                                 StringBuilder sb = new StringBuilder ();
233
234                                 string newline = String.Format ("{0}  {1} ", Environment.NewLine, Locale.GetText ("at"));
235                                 string unknown = Locale.GetText ("<unknown method>");
236
237                                 // Add traces captured using ExceptionDispatchInfo
238                                 if (captured_traces != null) {
239                                         foreach (var t in captured_traces) {
240                                                 if (!AddFrames (sb, newline, unknown, t))
241                                                         continue;
242
243                                                 sb.Append (Environment.NewLine);
244                                                 sb.Append ("--- End of stack trace from previous location where exception was thrown ---");
245                                                 sb.Append (Environment.NewLine);
246                                         }
247                                 }
248
249                                 StackTrace st = new StackTrace (this, 0, true, true);
250                                 AddFrames (sb, newline, unknown, st);
251
252                                 stack_trace = sb.ToString ();
253
254                                 return stack_trace;
255                         }
256                 }
257
258                 public MethodBase TargetSite {
259                         get {
260                                 StackTrace st = new StackTrace (this, true);
261                                 if (st.FrameCount > 0)
262                                         return st.GetFrame (0).GetMethod ();
263                                 
264                                 return null;
265                         }
266                 }
267
268                 public virtual IDictionary Data {
269                         get {
270                                 if (_data == null) {
271                                         // default to empty dictionary
272                                         _data = (IDictionary) new Hashtable ();
273                                 }
274                                 return _data;
275                         }
276                 }
277
278                 public virtual Exception GetBaseException ()
279                 {
280                         Exception inner = inner_exception;
281                                 
282                         while (inner != null)
283                         {
284                                 if (inner.InnerException != null)
285                                         inner = inner.InnerException;
286                                 else
287                                         return inner;
288                         }
289
290                         return this;
291                 }
292
293                 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
294                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
295                 {
296                         if (info == null)
297                                 throw new ArgumentNullException ("info");
298
299                         info.AddValue ("ClassName", ClassName);
300                         info.AddValue ("Message", message);
301                         info.AddValue ("InnerException", inner_exception);
302                         info.AddValue ("HelpURL", help_link);
303                         info.AddValue ("StackTraceString", StackTrace);
304                         info.AddValue ("RemoteStackTraceString", _remoteStackTraceString);
305                         info.AddValue ("RemoteStackIndex", remote_stack_index);
306                         info.AddValue ("HResult", hresult);
307 #if !MOONLIGHT
308                         info.AddValue ("Source", Source);
309 #else
310                         info.AddValue ("Source", null);
311 #endif
312                         info.AddValue ("ExceptionMethod", null);
313                         info.AddValue ("Data", _data, typeof (IDictionary));
314                 }
315
316                 public override string ToString ()
317                 {
318                         System.Text.StringBuilder result = new System.Text.StringBuilder (ClassName);
319                         result.Append (": ").Append (Message);
320
321                         if (null != _remoteStackTraceString)
322                                 result.Append (_remoteStackTraceString);
323                                 
324                         if (inner_exception != null) 
325                         {
326                                 result.Append (" ---> ").Append (inner_exception.ToString ());
327                                 result.Append (Environment.NewLine);
328                                 result.Append (Locale.GetText ("  --- End of inner exception stack trace ---"));
329                         }
330
331                         if (StackTrace != null)
332                                 result.Append (Environment.NewLine).Append (StackTrace);
333                         return result.ToString();
334                 }
335
336                 internal Exception FixRemotingException ()
337                 {
338                         string message = (0 == remote_stack_index) ?
339                                 Locale.GetText ("{0}{0}Server stack trace: {0}{1}{0}{0}Exception rethrown at [{2}]: {0}") :
340                                 Locale.GetText ("{1}{0}{0}Exception rethrown at [{2}]: {0}");
341                         string tmp = String.Format (message, Environment.NewLine, StackTrace, remote_stack_index);
342
343                         _remoteStackTraceString = tmp;
344                         remote_stack_index++;
345
346                         stack_trace = null;
347
348                         return this;
349                 }
350
351                 internal void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
352                 {
353                         ParameterInfo[] p = mi.GetParameters ();
354                         sb.Append (mi.DeclaringType.ToString ());
355                         sb.Append (".");
356                         sb.Append (mi.Name);
357
358                         if (mi.IsGenericMethod) {
359                                 Type[] gen_params = mi.GetGenericArguments ();
360                                 sb.Append ("[");
361                                 for (int j = 0; j < gen_params.Length; j++) {
362                                         if (j > 0)
363                                                 sb.Append (",");
364                                         sb.Append (gen_params [j].Name);
365                                 }
366                                 sb.Append ("]");
367                         }
368
369                         sb.Append (" (");
370                         for (int i = 0; i < p.Length; ++i) {
371                                 if (i > 0)
372                                         sb.Append (", ");
373                                 Type pt = p[i].ParameterType;
374                                 if (pt.IsClass && !String.IsNullOrEmpty (pt.Namespace)) {
375                                         sb.Append (pt.Namespace);
376                                         sb.Append (".");
377                                 }
378                                 sb.Append (pt.Name);
379                                 if (p [i].Name != null) {
380                                         sb.Append (" ");
381                                         sb.Append (p [i].Name);
382                                 }
383                         }
384                         sb.Append (")");
385                 }
386
387                 // For ExceptionDispatchInfo
388                 internal void CaptureTrace ()
389                 {
390                         if (captured_traces != null) {
391                                 Array.Resize (ref captured_traces, captured_traces.Length + 1);
392                         } else {
393                                 captured_traces = new StackTrace [1];
394                         }
395                         captured_traces [captured_traces.Length - 1] = new StackTrace (this, 0, true, true);
396
397                         trace_ips = null;
398                 }
399
400                 //
401                 // The documentation states that this is available in 1.x,
402                 // but it was not available (MemberRefing this would fail)
403                 // and it states the signature is `override sealed', but the
404                 // correct value is `newslot' 
405                 //
406                 public new Type GetType ()
407                 {
408                         return base.GetType ();
409                 }
410         }
411 }