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 void AddFrames (StringBuilder sb, string newline, string unknown, StackTrace st) {
192 for (int i = 0; i < st.FrameCount; i++) {
193 StackFrame frame = st.GetFrame (i);
195 sb.AppendFormat (" {0} ", Locale.GetText ("at"));
199 if (frame.GetMethod () == null) {
200 string internal_name = frame.GetInternalMethodName ();
201 if (internal_name != null)
202 sb.Append (internal_name);
204 sb.AppendFormat ("<0x{0:x5}> {1}", frame.GetNativeOffset (), unknown);
206 GetFullNameForStackTrace (sb, frame.GetMethod ());
208 if (frame.GetILOffset () == -1)
209 sb.AppendFormat (" <0x{0:x5}> ", frame.GetNativeOffset ());
211 sb.AppendFormat (" [0x{0:x5}] ", frame.GetILOffset ());
213 sb.AppendFormat ("in {0}:{1} ", frame.GetSecureFileName (),
214 frame.GetFileLineNumber ());
219 public virtual string StackTrace {
221 if (stack_trace != null)
224 if (trace_ips == null)
228 StringBuilder sb = new StringBuilder ();
230 string newline = String.Format ("{0} {1} ", Environment.NewLine, Locale.GetText ("at"));
231 string unknown = Locale.GetText ("<unknown method>");
233 // Add traces captured using ExceptionDispatchInfo
234 if (captured_traces != null) {
235 foreach (var t in captured_traces) {
236 AddFrames (sb, newline, unknown, t);
237 sb.Append (Environment.NewLine);
238 sb.Append ("--- End of stack trace from previous location where exception was thrown ---");
239 sb.Append (Environment.NewLine);
243 StackTrace st = new StackTrace (this, 0, true, true);
244 AddFrames (sb, newline, unknown, st);
246 stack_trace = sb.ToString ();
252 public MethodBase TargetSite {
254 StackTrace st = new StackTrace (this, true);
255 if (st.FrameCount > 0)
256 return st.GetFrame (0).GetMethod ();
262 public virtual IDictionary Data {
265 // default to empty dictionary
266 _data = (IDictionary) new Hashtable ();
272 public virtual Exception GetBaseException ()
274 Exception inner = inner_exception;
276 while (inner != null)
278 if (inner.InnerException != null)
279 inner = inner.InnerException;
287 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
288 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
291 throw new ArgumentNullException ("info");
293 info.AddValue ("ClassName", ClassName);
294 info.AddValue ("Message", message);
295 info.AddValue ("InnerException", inner_exception);
296 info.AddValue ("HelpURL", help_link);
297 info.AddValue ("StackTraceString", StackTrace);
298 info.AddValue ("RemoteStackTraceString", _remoteStackTraceString);
299 info.AddValue ("RemoteStackIndex", remote_stack_index);
300 info.AddValue ("HResult", hresult);
302 info.AddValue ("Source", Source);
304 info.AddValue ("Source", null);
306 info.AddValue ("ExceptionMethod", null);
307 info.AddValue ("Data", _data, typeof (IDictionary));
310 public override string ToString ()
312 System.Text.StringBuilder result = new System.Text.StringBuilder (ClassName);
313 result.Append (": ").Append (Message);
315 if (null != _remoteStackTraceString)
316 result.Append (_remoteStackTraceString);
318 if (inner_exception != null)
320 result.Append (" ---> ").Append (inner_exception.ToString ());
321 result.Append (Environment.NewLine);
322 result.Append (Locale.GetText (" --- End of inner exception stack trace ---"));
325 if (StackTrace != null)
326 result.Append (Environment.NewLine).Append (StackTrace);
327 return result.ToString();
330 internal Exception FixRemotingException ()
332 string message = (0 == remote_stack_index) ?
333 Locale.GetText ("{0}{0}Server stack trace: {0}{1}{0}{0}Exception rethrown at [{2}]: {0}") :
334 Locale.GetText ("{1}{0}{0}Exception rethrown at [{2}]: {0}");
335 string tmp = String.Format (message, Environment.NewLine, StackTrace, remote_stack_index);
337 _remoteStackTraceString = tmp;
338 remote_stack_index++;
345 internal void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
347 ParameterInfo[] p = mi.GetParameters ();
348 sb.Append (mi.DeclaringType.ToString ());
352 if (mi.IsGenericMethod) {
353 Type[] gen_params = mi.GetGenericArguments ();
355 for (int j = 0; j < gen_params.Length; j++) {
358 sb.Append (gen_params [j].Name);
364 for (int i = 0; i < p.Length; ++i) {
367 Type pt = p[i].ParameterType;
368 if (pt.IsClass && !String.IsNullOrEmpty (pt.Namespace)) {
369 sb.Append (pt.Namespace);
373 if (p [i].Name != null) {
375 sb.Append (p [i].Name);
381 // For ExceptionDispatchInfo
382 internal void CaptureTrace () {
383 if (captured_traces != null) {
384 StackTrace[] new_traces = new StackTrace [captured_traces.Length + 1];
385 Array.Copy (captured_traces, new_traces, captured_traces.Length);
386 captured_traces = new_traces;
388 captured_traces = new StackTrace [1];
390 captured_traces [captured_traces.Length - 1] = new StackTrace (this, 0, true, true);
396 // The documentation states that this is available in 1.x,
397 // but it was not available (MemberRefing this would fail)
398 // and it states the signature is `override sealed', but the
399 // correct value is `newslot'
401 public new Type GetType ()
403 return base.GetType ();