5 // Miguel de Icaza (miguel@ximian.com)
8 // (C) Ximian, Inc. http://www.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;
32 using System.Diagnostics;
33 using System.Reflection;
35 using System.Runtime.InteropServices;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.Serialization;
38 using System.Security.Permissions;
44 [ComDefaultInterface (typeof (_Exception))]
45 [ClassInterface (ClassInterfaceType.None)]
46 [StructLayout (LayoutKind.Sequential)]
47 public class Exception : ISerializable, _Exception
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. */
54 Exception inner_exception;
55 internal string message;
59 // formerly known as remote_stack_trace (see #425512):
60 string _remoteStackTraceString;
61 int remote_stack_index;
62 internal int hresult = -2146233088;
65 StackTrace[] captured_traces;
66 IntPtr[] native_trace_ips;
68 #pragma warning restore 169, 649
70 /* Don't add fields here, the runtime depends on the layout of subclasses */
76 public Exception (string message)
78 this.message = message;
81 protected Exception (SerializationInfo info, StreamingContext context)
84 throw new ArgumentNullException ("info");
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));
97 _data = (IDictionary) info.GetValue ("Data", typeof (IDictionary));
98 } catch (SerializationException) {
99 // member did not exist in .NET 1.x
103 public Exception (string message, Exception innerException)
105 inner_exception = innerException;
106 this.message = message;
109 public Exception InnerException {
110 get { return inner_exception; }
113 public virtual string HelpLink {
114 get { return help_link; }
115 set { help_link = value; }
120 get { return hresult; }
121 protected set { hresult = value; }
124 protected int HResult {
125 get { return hresult; }
126 set { hresult = value; }
129 internal void SetMessage (string s)
134 internal void SetStackTrace (string s)
141 if (class_name == null)
142 class_name = GetType ().ToString ();
147 public virtual string Message {
150 message = string.Format (Locale.GetText ("Exception of type '{0}' was thrown."),
159 protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState {
167 public virtual string Source {
169 if (source == null) {
170 StackTrace st = new StackTrace (this, true);
171 if (st.FrameCount > 0) {
172 StackFrame sf = st.GetFrame (0);
174 MethodBase method = sf.GetMethod ();
175 if (method != null) {
176 source = method.DeclaringType.Assembly.UnprotectedGetName ().Name;
182 // source can be null
191 bool AddFrames (StringBuilder sb, string newline, string unknown, StackTrace st)
194 for (i = 0; i < st.FrameCount; i++) {
195 StackFrame frame = st.GetFrame (i);
197 sb.AppendFormat (" {0} ", Locale.GetText ("at"));
201 if (frame.GetMethod () == null) {
202 string internal_name = frame.GetInternalMethodName ();
203 if (internal_name != null)
204 sb.Append (internal_name);
206 sb.AppendFormat ("<0x{0:x5}> {1}", frame.GetNativeOffset (), unknown);
208 GetFullNameForStackTrace (sb, frame.GetMethod ());
210 if (frame.GetILOffset () == -1)
211 sb.AppendFormat (" <0x{0:x5}> ", frame.GetNativeOffset ());
213 sb.AppendFormat (" [0x{0:x5}] ", frame.GetILOffset ());
215 sb.AppendFormat ("in {0}:{1} ", frame.GetSecureFileName (),
216 frame.GetFileLineNumber ());
223 public virtual string StackTrace {
225 if (stack_trace != null)
228 if (trace_ips == null)
232 StringBuilder sb = new StringBuilder ();
234 string newline = String.Format ("{0} {1} ", Environment.NewLine, Locale.GetText ("at"));
235 string unknown = Locale.GetText ("<unknown method>");
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))
243 sb.Append (Environment.NewLine);
244 sb.Append ("--- End of stack trace from previous location where exception was thrown ---");
245 sb.Append (Environment.NewLine);
249 StackTrace st = new StackTrace (this, 0, true, true);
250 AddFrames (sb, newline, unknown, st);
252 stack_trace = sb.ToString ();
258 public MethodBase TargetSite {
260 StackTrace st = new StackTrace (this, true);
261 if (st.FrameCount > 0)
262 return st.GetFrame (0).GetMethod ();
268 public virtual IDictionary Data {
271 // default to empty dictionary
272 _data = (IDictionary) new Hashtable ();
278 public virtual Exception GetBaseException ()
280 Exception inner = inner_exception;
282 while (inner != null)
284 if (inner.InnerException != null)
285 inner = inner.InnerException;
293 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
294 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
297 throw new ArgumentNullException ("info");
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);
308 info.AddValue ("Source", Source);
310 info.AddValue ("Source", null);
312 info.AddValue ("ExceptionMethod", null);
313 info.AddValue ("Data", _data, typeof (IDictionary));
316 public override string ToString ()
318 System.Text.StringBuilder result = new System.Text.StringBuilder (ClassName);
319 result.Append (": ").Append (Message);
321 if (null != _remoteStackTraceString)
322 result.Append (_remoteStackTraceString);
324 if (inner_exception != null)
326 result.Append (" ---> ").Append (inner_exception.ToString ());
327 result.Append (Environment.NewLine);
328 result.Append (Locale.GetText (" --- End of inner exception stack trace ---"));
331 if (StackTrace != null)
332 result.Append (Environment.NewLine).Append (StackTrace);
333 return result.ToString();
336 internal Exception FixRemotingException ()
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);
343 _remoteStackTraceString = tmp;
344 remote_stack_index++;
351 internal void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
353 ParameterInfo[] p = mi.GetParameters ();
354 sb.Append (mi.DeclaringType.ToString ());
358 if (mi.IsGenericMethod) {
359 Type[] gen_params = mi.GetGenericArguments ();
361 for (int j = 0; j < gen_params.Length; j++) {
364 sb.Append (gen_params [j].Name);
370 for (int i = 0; i < p.Length; ++i) {
373 Type pt = p[i].ParameterType;
374 if (pt.IsClass && !String.IsNullOrEmpty (pt.Namespace)) {
375 sb.Append (pt.Namespace);
379 if (p [i].Name != null) {
381 sb.Append (p [i].Name);
387 // For ExceptionDispatchInfo
388 internal void CaptureTrace ()
390 if (captured_traces != null) {
391 Array.Resize (ref captured_traces, captured_traces.Length + 1);
393 captured_traces = new StackTrace [1];
395 captured_traces [captured_traces.Length - 1] = new StackTrace (this, 0, true, true);
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'
406 public new Type GetType ()
408 return base.GetType ();