Merge pull request #4540 from kumpera/android-changes-part1
[mono.git] / mono / metadata / exception.c
1 /**
2  * \file
3  * Exception handling
4  *
5  * Authors:
6  *      Paolo Molaro    (lupus@ximian.com)
7  *      Dietmar Maurer  (dietmar@ximian.com)
8  *      Dick Porter     (dick@ximian.com)
9  *      Miguel de Icaza (miguel@ximian.com)
10  *
11  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
12  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
13  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14  */
15
16 #include <glib.h>
17 #include <config.h>
18 #include <mono/metadata/environment.h>
19 #include <mono/metadata/exception.h>
20 #include <mono/metadata/exception-internals.h>
21
22 #include <mono/metadata/object-internals.h>
23 #include <mono/metadata/metadata-internals.h>
24 #include <mono/metadata/appdomain.h>
25 #include <mono/metadata/mono-debug.h>
26 #include <mono/utils/mono-error-internals.h>
27 #include <mono/utils/mono-logger-internals.h>
28 #include <string.h>
29
30 #ifdef HAVE_EXECINFO_H
31 #include <execinfo.h>
32 #endif
33
34 static MonoUnhandledExceptionFunc unhandled_exception_hook = NULL;
35 static gpointer unhandled_exception_hook_data = NULL;
36
37 /**
38  * mono_exception_from_name:
39  * \param image the Mono image where to look for the class
40  * \param name_space the namespace for the class
41  * \param name class name
42  *
43  * Creates an exception of the given namespace/name class in the
44  * current domain.
45  *
46  * \returns the initialized exception instance.
47  */
48 MonoException *
49 mono_exception_from_name (MonoImage *image, const char *name_space,
50                           const char *name)
51 {
52         return mono_exception_from_name_domain (mono_domain_get (), image, name_space, name);
53 }
54
55 /**
56  * mono_exception_from_name_domain:
57  * \param domain Domain where the return object will be created.
58  * \param image the Mono image where to look for the class
59  * \param name_space the namespace for the class
60  * \param name class name
61  *
62  * Creates an exception object of the given namespace/name class on
63  * the given domain.
64  *
65  * \returns the initialized exception instance.
66  */
67 MonoException *
68 mono_exception_from_name_domain (MonoDomain *domain, MonoImage *image, 
69                                  const char* name_space, const char *name)
70 {
71         MonoError error;
72         MonoClass *klass;
73         MonoObject *o;
74         MonoDomain *caller_domain = mono_domain_get ();
75
76         klass = mono_class_load_from_name (image, name_space, name);
77
78         o = mono_object_new_checked (domain, klass, &error);
79         mono_error_assert_ok (&error);
80
81         if (domain != caller_domain)
82                 mono_domain_set_internal (domain);
83         mono_runtime_object_init_checked (o, &error);
84         mono_error_assert_ok (&error);
85
86         if (domain != caller_domain)
87                 mono_domain_set_internal (caller_domain);
88
89         return (MonoException *)o;
90 }
91
92
93 /**
94  * mono_exception_from_token:
95  * \param image the Mono image where to look for the class
96  * \param token The type token of the class
97  *
98  * Creates an exception of the type given by \p token.
99  *
100  * \returns the initialized exception instance.
101  */
102 MonoException *
103 mono_exception_from_token (MonoImage *image, guint32 token)
104 {
105         MonoError error;
106         MonoClass *klass;
107         MonoObject *o;
108
109         klass = mono_class_get_checked (image, token, &error);
110         mono_error_assert_ok (&error);
111
112         o = mono_object_new_checked (mono_domain_get (), klass, &error);
113         mono_error_assert_ok (&error);
114         
115         mono_runtime_object_init_checked (o, &error);
116         mono_error_assert_ok (&error);
117
118         return (MonoException *)o;
119 }
120
121 static MonoException *
122 create_exception_two_strings (MonoClass *klass, MonoString *a1, MonoString *a2, MonoError *error)
123 {
124         MonoDomain *domain = mono_domain_get ();
125         MonoMethod *method = NULL;
126         MonoObject *o;
127         int count = 1;
128         gpointer args [2];
129         gpointer iter;
130         MonoMethod *m;
131
132         if (a2 != NULL)
133                 count++;
134         
135         o = mono_object_new_checked (domain, klass, error);
136         mono_error_assert_ok (error);
137
138         iter = NULL;
139         while ((m = mono_class_get_methods (klass, &iter))) {
140                 MonoMethodSignature *sig;
141                 
142                 if (strcmp (".ctor", mono_method_get_name (m)))
143                         continue;
144                 sig = mono_method_signature (m);
145                 if (sig->param_count != count)
146                         continue;
147
148                 if (sig->params [0]->type != MONO_TYPE_STRING)
149                         continue;
150                 if (count == 2 && sig->params [1]->type != MONO_TYPE_STRING)
151                         continue;
152                 method = m;
153                 break;
154         }
155
156         args [0] = a1;
157         args [1] = a2;
158
159         mono_runtime_invoke_checked (method, o, args, error);
160         return_val_if_nok (error, NULL);
161
162         return (MonoException *) o;
163 }
164
165 /**
166  * mono_exception_from_name_two_strings:
167  * \param image the Mono image where to look for the class
168  * \param name_space the namespace for the class
169  * \param name class name
170  * \param a1 first string argument to pass
171  * \param a2 second string argument to pass
172  *
173  * Creates an exception from a constructor that takes two string
174  * arguments.
175  *
176  * \returns the initialized exception instance.
177  */
178 MonoException *
179 mono_exception_from_name_two_strings (MonoImage *image, const char *name_space,
180                                       const char *name, MonoString *a1, MonoString *a2)
181 {
182         MonoError error;
183         MonoException *ret;
184
185         ret = mono_exception_from_name_two_strings_checked (image, name_space, name, a1, a2, &error);
186         mono_error_cleanup (&error);
187         return ret;
188 }
189
190 /**
191  * mono_exception_from_name_two_strings_checked:
192  * \param image the Mono image where to look for the class
193  * \param name_space the namespace for the class
194  * \param name class name
195  * \param a1 first string argument to pass
196  * \param a2 second string argument to pass
197  * \param error set on error
198  *
199  * Creates an exception from a constructor that takes two string
200  * arguments.
201  *
202  * \returns the initialized exception instance. On failure returns
203  * NULL and sets \p error.
204  */
205 MonoException *
206 mono_exception_from_name_two_strings_checked (MonoImage *image, const char *name_space,
207                                               const char *name, MonoString *a1, MonoString *a2,
208                                               MonoError *error)
209 {
210         MonoClass *klass;
211
212         error_init (error);
213         klass = mono_class_load_from_name (image, name_space, name);
214
215         return create_exception_two_strings (klass, a1, a2, error);
216 }
217
218 /**
219  * mono_exception_from_name_msg:
220  * \param image the Mono image where to look for the class
221  * \param name_space the namespace for the class
222  * \param name class name
223  * \param msg the message to embed inside the exception
224  *
225  * Creates an exception and initializes its message field.
226  *
227  * \returns the initialized exception instance.
228  */
229 MonoException *
230 mono_exception_from_name_msg (MonoImage *image, const char *name_space,
231                               const char *name, const char *msg)
232 {
233         MonoException *ex;
234
235         ex = mono_exception_from_name (image, name_space, name);
236
237         if (msg)
238                 MONO_OBJECT_SETREF (ex, message, mono_string_new (mono_object_get_domain ((MonoObject*)ex), msg));
239
240         return ex;
241 }
242
243 /**
244  * mono_exception_from_token_two_strings:
245  *
246  *   Same as mono_exception_from_name_two_strings, but lookup the exception class using
247  * IMAGE and TOKEN.
248  */
249 MonoException *
250 mono_exception_from_token_two_strings (MonoImage *image, guint32 token,
251                                                                            MonoString *a1, MonoString *a2)
252 {
253         MonoError error;
254         MonoException *ret;
255         ret = mono_exception_from_token_two_strings_checked (image, token, a1, a2, &error);
256         mono_error_cleanup (&error);
257         return ret;
258 }
259
260 /**
261  * mono_exception_from_token_two_strings_checked:
262  *
263  *   Same as mono_exception_from_name_two_strings, but lookup the exception class using
264  * IMAGE and TOKEN.
265  */
266 MonoException *
267 mono_exception_from_token_two_strings_checked (MonoImage *image, guint32 token,
268                                                MonoString *a1, MonoString *a2,
269                                                MonoError *error)
270 {
271         MonoClass *klass;
272
273         error_init (error);
274
275         klass = mono_class_get_checked (image, token, error);
276         mono_error_assert_ok (error); /* FIXME handle the error. */
277
278         return create_exception_two_strings (klass, a1, a2, error);
279 }
280
281 /**
282  * mono_get_exception_divide_by_zero:
283  * \returns a new instance of the \c System.DivideByZeroException
284  */
285 MonoException *
286 mono_get_exception_divide_by_zero ()
287 {
288         return mono_exception_from_name (mono_get_corlib (), "System",
289                                          "DivideByZeroException");
290 }
291
292 /**
293  * mono_get_exception_security:
294  * \returns a new instance of the \c System.Security.SecurityException
295  */
296 MonoException *
297 mono_get_exception_security ()
298 {
299         return mono_exception_from_name (mono_get_corlib (), "System.Security",
300                                          "SecurityException");
301 }
302
303 /**
304  * mono_get_exception_thread_abort:
305  * \returns a new instance of the \c System.Threading.ThreadAbortException
306  */
307 MonoException *
308 mono_get_exception_thread_abort ()
309 {
310         return mono_exception_from_name (mono_get_corlib (), "System.Threading",
311                                          "ThreadAbortException");
312 }
313
314 /**
315  * mono_get_exception_thread_interrupted:
316  * \returns a new instance of the \c System.Threading.ThreadInterruptedException
317  */
318 MonoException *
319 mono_get_exception_thread_interrupted ()
320 {
321         return mono_exception_from_name (mono_get_corlib (), "System.Threading",
322                                          "ThreadInterruptedException");
323 }
324
325 /**
326  * mono_get_exception_arithmetic:
327  * \returns a new instance of the \c System.ArithmeticException
328  */
329 MonoException *
330 mono_get_exception_arithmetic ()
331 {
332         return mono_exception_from_name (mono_get_corlib (), "System",
333                                          "ArithmeticException");
334 }
335
336 /**
337  * mono_get_exception_overflow:
338  * \returns a new instance of the \c System.OverflowException
339  */
340 MonoException *
341 mono_get_exception_overflow ()
342 {
343         return mono_exception_from_name (mono_get_corlib (), "System",
344                                          "OverflowException");
345 }
346
347 /**
348  * mono_get_exception_null_reference:
349  * \returns a new instance of the \c System.NullReferenceException
350  */
351 MonoException *
352 mono_get_exception_null_reference ()
353 {
354         return mono_exception_from_name (mono_get_corlib (), "System",
355                                          "NullReferenceException");
356 }
357
358 /**
359  * mono_get_exception_execution_engine:
360  * \param msg the message to pass to the user
361  * \returns a new instance of the \c System.ExecutionEngineException
362  */
363 MonoException *
364 mono_get_exception_execution_engine (const char *msg)
365 {
366         return mono_exception_from_name_msg (mono_get_corlib (), "System", "ExecutionEngineException", msg);
367 }
368
369 /**
370  * mono_get_exception_serialization:
371  * \param msg the message to pass to the user
372  * \returns a new instance of the \c System.Runtime.Serialization.SerializationException
373  */
374 MonoException *
375 mono_get_exception_serialization (const char *msg)
376 {
377         return mono_exception_from_name_msg (mono_get_corlib (), "System.Runtime.Serialization", "SerializationException", msg);
378 }
379
380 /**
381  * mono_get_exception_invalid_cast:
382  * \returns a new instance of the \c System.InvalidCastException
383  */
384 MonoException *
385 mono_get_exception_invalid_cast ()
386 {
387         return mono_exception_from_name (mono_get_corlib (), "System", "InvalidCastException");
388 }
389
390 /**
391  * mono_get_exception_invalid_operation:
392  * \param msg the message to pass to the user
393  * \returns a new instance of the \c System.InvalidOperationException
394  */
395 MonoException *
396 mono_get_exception_invalid_operation (const char *msg)
397 {
398         return mono_exception_from_name_msg (mono_get_corlib (), "System",
399                                         "InvalidOperationException", msg);
400 }
401
402 /**
403  * mono_get_exception_index_out_of_range:
404  * \returns a new instance of the \c System.IndexOutOfRangeException
405  */
406 MonoException *
407 mono_get_exception_index_out_of_range ()
408 {
409         return mono_exception_from_name (mono_get_corlib (), "System",
410                                          "IndexOutOfRangeException");
411 }
412
413 /**
414  * mono_get_exception_array_type_mismatch:
415  * \returns a new instance of the \c System.ArrayTypeMismatchException
416  */
417 MonoException *
418 mono_get_exception_array_type_mismatch ()
419 {
420         return mono_exception_from_name (mono_get_corlib (), "System",
421                                          "ArrayTypeMismatchException");
422 }
423
424 /**
425  * mono_get_exception_type_load:
426  * \param class_name the name of the class that could not be loaded
427  * \param assembly_name the assembly where the class was looked up.
428  * \returns a new instance of the \c System.TypeLoadException
429  */
430 MonoException *
431 mono_get_exception_type_load (MonoString *class_name, char *assembly_name)
432 {
433         MonoString *s = assembly_name ? mono_string_new (mono_domain_get (), assembly_name) : mono_string_new (mono_domain_get (), "");
434
435         MonoError error;
436         MonoException *ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System",
437                                                                    "TypeLoadException", class_name, s, &error);
438         mono_error_assert_ok (&error);
439         return ret;
440 }
441
442 /**
443  * mono_get_exception_not_implemented:
444  * \param msg the message to pass to the user
445  * \returns a new instance of the \c System.NotImplementedException
446  */
447 MonoException *
448 mono_get_exception_not_implemented (const char *msg)
449 {
450         return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotImplementedException", msg);
451 }
452
453 /**
454  * mono_get_exception_not_supported:
455  * \param msg the message to pass to the user
456  * \returns a new instance of the \c System.NotSupportedException
457  */
458 MonoException *
459 mono_get_exception_not_supported (const char *msg)
460 {
461         return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotSupportedException", msg);
462 }
463
464 /**
465  * mono_get_exception_missing_method:
466  * \param class_name the class where the lookup was performed.
467  * \param member_name the name of the missing method.
468  * \returns a new instance of the \c System.MissingMethodException
469  */
470 MonoException *
471 mono_get_exception_missing_method (const char *class_name, const char *member_name)
472 {
473         MonoString *s1 = mono_string_new (mono_domain_get (), class_name);
474         MonoString *s2 = mono_string_new (mono_domain_get (), member_name);
475
476         MonoError error;
477         MonoException *ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System",
478                                                                            "MissingMethodException", s1, s2, &error);
479         mono_error_assert_ok (&error);
480         return ret;
481 }
482
483 /**
484  * mono_get_exception_missing_field:
485  * \param class_name the class where the lookup was performed
486  * \param member_name the name of the missing method.
487  * \returns a new instance of the \c System.MissingFieldException
488  */
489 MonoException *
490 mono_get_exception_missing_field (const char *class_name, const char *member_name)
491 {
492         MonoString *s1 = mono_string_new (mono_domain_get (), class_name);
493         MonoString *s2 = mono_string_new (mono_domain_get (), member_name);
494
495         MonoError error;
496         MonoException *ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System",
497                                                                    "MissingFieldException", s1, s2, &error);
498         mono_error_assert_ok (&error);
499         return ret;
500 }
501
502 /**
503  * mono_get_exception_argument_null:
504  * \param arg the name of the argument that is null
505  * \returns a new instance of the \c System.ArgumentNullException
506  */
507 MonoException*
508 mono_get_exception_argument_null (const char *arg)
509 {
510         MonoException *ex;
511
512         ex = mono_exception_from_name ( 
513                 mono_get_corlib (), "System", "ArgumentNullException");
514
515         if (arg) {
516                 MonoArgumentException *argex = (MonoArgumentException *)ex;
517                 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
518         }
519         
520         return ex;
521 }
522
523 /**
524  * mono_get_exception_argument:
525  * \param arg the name of the invalid argument.
526  * \returns a new instance of the \c System.ArgumentException
527  */
528 MonoException *
529 mono_get_exception_argument (const char *arg, const char *msg)
530 {
531         MonoException *ex;
532
533         ex = mono_exception_from_name_msg (
534                 mono_get_corlib (), "System", "ArgumentException", msg);
535
536         if (arg) {
537                 MonoArgumentException *argex = (MonoArgumentException *)ex;
538                 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
539         }
540         
541         return ex;
542 }
543
544 /**
545  * mono_get_exception_argument_out_of_range:
546  * \param arg the name of the out of range argument.
547  * \returns a new instance of the \c System.ArgumentOutOfRangeException
548  */
549 MonoException *
550 mono_get_exception_argument_out_of_range (const char *arg)
551 {
552         MonoException *ex;
553
554         ex = mono_exception_from_name (
555                 mono_get_corlib (), "System", "ArgumentOutOfRangeException");
556
557         if (arg) {
558                 MonoArgumentException *argex = (MonoArgumentException *)ex;
559                 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
560         }
561         
562         return ex;
563 }
564
565 /**
566  * mono_get_exception_thread_state:
567  * \param msg the message to present to the user
568  * \returns a new instance of the \c System.Threading.ThreadStateException
569  */
570 MonoException *
571 mono_get_exception_thread_state (const char *msg)
572 {
573         return mono_exception_from_name_msg (
574                 mono_get_corlib (), "System.Threading", "ThreadStateException", msg);
575 }
576
577 /**
578  * mono_get_exception_io:
579  * \param msg the message to present to the user
580  * \returns a new instance of the \c System.IO.IOException
581  */
582 MonoException *
583 mono_get_exception_io (const char *msg)
584 {
585         return mono_exception_from_name_msg ( 
586                 mono_get_corlib (), "System.IO", "IOException", msg);
587 }
588
589 /**
590  * mono_get_exception_file_not_found:
591  * \param fname the name of the file not found.
592  * \returns a new instance of the \c System.IO.FileNotFoundException
593  */
594 MonoException *
595 mono_get_exception_file_not_found (MonoString *fname)
596 {
597         MonoError error;
598         MonoException *ret = mono_exception_from_name_two_strings_checked (
599                 mono_get_corlib (), "System.IO", "FileNotFoundException", fname, fname, &error);
600         mono_error_assert_ok (&error);
601         return ret;
602 }
603
604 /**
605  * mono_get_exception_file_not_found2:
606  * \param msg an informative message for the user.
607  * \param fname the name of the file not found.
608  * \returns a new instance of the \c System.IO.FileNotFoundException
609  */
610 MonoException *
611 mono_get_exception_file_not_found2 (const char *msg, MonoString *fname)
612 {
613         MonoString *s = msg ? mono_string_new (mono_domain_get (), msg) : NULL;
614
615         MonoError error;
616         MonoException *ret = mono_exception_from_name_two_strings_checked (
617                 mono_get_corlib (), "System.IO", "FileNotFoundException", s, fname, &error);
618         mono_error_assert_ok (&error);
619         return ret;
620 }
621
622 /**
623  * mono_get_exception_type_initialization:
624  * \param type_name the name of the type that failed to initialize.
625  * \param inner the inner exception.
626  * \returns a new instance of the \c System.TypeInitializationException
627  */
628 MonoException *
629 mono_get_exception_type_initialization (const gchar *type_name, MonoException *inner)
630 {
631         MonoError error;
632         MonoException *ret = mono_get_exception_type_initialization_checked (type_name, inner, &error);
633         if (!is_ok (&error)) {
634                 mono_error_cleanup (&error);
635                 return NULL;
636         }
637
638         return ret;
639 }
640
641 MonoException *
642 mono_get_exception_type_initialization_checked (const gchar *type_name, MonoException *inner, MonoError *error)
643 {
644         MonoClass *klass;
645         gpointer args [2];
646         MonoObject *exc;
647         MonoMethod *method;
648         gpointer iter;
649
650         klass = mono_class_load_from_name (mono_get_corlib (), "System", "TypeInitializationException");
651
652         mono_class_init (klass);
653
654         iter = NULL;
655         while ((method = mono_class_get_methods (klass, &iter))) {
656                 if (!strcmp (".ctor", mono_method_get_name (method))) {
657                         MonoMethodSignature *sig = mono_method_signature (method);
658
659                         if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_STRING && mono_class_from_mono_type (sig->params [1]) == mono_defaults.exception_class)
660                                 break;
661                 }
662                 method = NULL;
663         }
664         g_assert (method);
665
666         args [0] = mono_string_new (mono_domain_get (), type_name);
667         args [1] = inner;
668
669         exc = mono_object_new_checked (mono_domain_get (), klass, error);
670         mono_error_assert_ok (error);
671
672         mono_runtime_invoke_checked (method, exc, args, error);
673         return_val_if_nok (error, NULL);
674
675         return (MonoException *) exc;
676 }
677
678 /**
679  * mono_get_exception_synchronization_lock:
680  * \param inner the inner exception.
681  * \returns a new instance of the \c System.SynchronizationLockException
682  */
683 MonoException *
684 mono_get_exception_synchronization_lock (const char *msg)
685 {
686         return mono_exception_from_name_msg (mono_get_corlib (), "System.Threading", "SynchronizationLockException", msg);
687 }
688
689 /**
690  * mono_get_exception_cannot_unload_appdomain:
691  * \param inner the inner exception.
692  * \returns a new instance of the \c System.CannotUnloadAppDomainException
693  */
694 MonoException *
695 mono_get_exception_cannot_unload_appdomain (const char *msg)
696 {
697         return mono_exception_from_name_msg (mono_get_corlib (), "System", "CannotUnloadAppDomainException", msg);
698 }
699
700 /**
701  * mono_get_exception_appdomain_unloaded
702  * \returns a new instance of the \c System.AppDomainUnloadedException
703  */
704 MonoException *
705 mono_get_exception_appdomain_unloaded (void)
706 {
707         return mono_exception_from_name (mono_get_corlib (), "System", "AppDomainUnloadedException");
708 }
709
710 /**
711  * mono_get_exception_bad_image_format:
712  * \param msg an informative message for the user.
713  * \returns a new instance of the \c System.BadImageFormatException
714  */
715 MonoException *
716 mono_get_exception_bad_image_format (const char *msg)
717 {
718         return mono_exception_from_name_msg (mono_get_corlib (), "System", "BadImageFormatException", msg);
719 }       
720
721 /**
722  * mono_get_exception_bad_image_format2:
723  * \param msg an informative message for the user.
724  * \param fname The full name of the file with the invalid image.
725  * \returns a new instance of the \c System.BadImageFormatException
726  */
727 MonoException *
728 mono_get_exception_bad_image_format2 (const char *msg, MonoString *fname)
729 {
730         MonoString *s = msg ? mono_string_new (mono_domain_get (), msg) : NULL;
731
732         MonoError error;
733         MonoException *ret = mono_exception_from_name_two_strings_checked (
734                 mono_get_corlib (), "System", "BadImageFormatException", s, fname, &error);
735         mono_error_assert_ok (&error);
736         return ret;
737 }
738
739 /**
740  * mono_get_exception_stack_overflow:
741  * \returns a new instance of the \c System.StackOverflowException
742  */
743 MonoException *
744 mono_get_exception_stack_overflow (void)
745 {
746         return mono_exception_from_name (mono_get_corlib (), "System", "StackOverflowException");       
747 }
748
749 /**
750  * mono_get_exception_out_of_memory:
751  * \returns a new instance of the \c System.OutOfMemoryException
752  */
753 MonoException *
754 mono_get_exception_out_of_memory (void)
755 {
756         return mono_exception_from_name (mono_get_corlib (), "System", "OutOfMemoryException");
757 }
758
759 /**
760  * mono_get_exception_field_access:
761  * \returns a new instance of the \c System.FieldAccessException
762  */
763 MonoException *
764 mono_get_exception_field_access (void)
765 {
766         return mono_exception_from_name (mono_get_corlib (), "System", "FieldAccessException");
767 }
768
769 /**
770  * mono_get_exception_field_access2:
771  * \param msg an informative message for the user.
772  * \returns a new instance of the \c System.FieldAccessException
773  */
774 MonoException *
775 mono_get_exception_field_access_msg (const char *msg)
776 {
777         return mono_exception_from_name_msg (mono_get_corlib (), "System", "FieldAccessException", msg);
778 }
779
780 /**
781  * mono_get_exception_method_access:
782  * \returns a new instance of the \c System.MethodAccessException
783  */
784 MonoException *
785 mono_get_exception_method_access (void)
786 {
787         return mono_exception_from_name (mono_get_corlib (), "System", "MethodAccessException");
788 }
789
790 /**
791  * mono_get_exception_method_access2:
792  * \param msg an informative message for the user.
793  * \returns a new instance of the \c System.MethodAccessException
794  */
795 MonoException *
796 mono_get_exception_method_access_msg (const char *msg)
797 {
798         return mono_exception_from_name_msg (mono_get_corlib (), "System", "MethodAccessException", msg);
799 }
800
801 /**
802  * mono_get_exception_reflection_type_load:
803  * \param types an array of types that were defined in the moduled loaded.
804  * \param exceptions an array of exceptions that were thrown during the type loading.
805  * \returns a new instance of the \c System.Reflection.ReflectionTypeLoadException
806  */
807 MonoException *
808 mono_get_exception_reflection_type_load (MonoArray *types_raw, MonoArray *exceptions_raw)
809 {
810         HANDLE_FUNCTION_ENTER ();
811         MonoError error;
812         MONO_HANDLE_DCL (MonoArray, types);
813         MONO_HANDLE_DCL (MonoArray, exceptions);
814         MonoExceptionHandle ret = mono_get_exception_reflection_type_load_checked (types, exceptions, &error);
815         if (is_ok (&error)) {
816                 mono_error_cleanup (&error);
817                 ret = MONO_HANDLE_CAST (MonoException, NULL_HANDLE);
818                 goto leave;
819         }
820
821 leave:
822         HANDLE_FUNCTION_RETURN_OBJ (ret);
823
824 }
825
826 MonoExceptionHandle
827 mono_get_exception_reflection_type_load_checked (MonoArrayHandle types, MonoArrayHandle exceptions, MonoError *error)
828 {
829         MonoClass *klass;
830         MonoMethod *method;
831         gpointer iter;
832
833         error_init (error);
834
835         klass = mono_class_load_from_name (mono_get_corlib (), "System.Reflection", "ReflectionTypeLoadException");
836
837         mono_class_init (klass);
838
839         /* Find the Type[], Exception[] ctor */
840         iter = NULL;
841         while ((method = mono_class_get_methods (klass, &iter))) {
842                 if (!strcmp (".ctor", mono_method_get_name (method))) {
843                         MonoMethodSignature *sig = mono_method_signature (method);
844
845                         if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_SZARRAY && sig->params [1]->type == MONO_TYPE_SZARRAY)
846                                 break;
847                 }
848                 method = NULL;
849         }
850         g_assert (method);
851
852         MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, mono_object_new_checked (mono_domain_get (), klass, error));
853         mono_error_assert_ok (error);
854
855         gpointer args [2];
856         args [0] = MONO_HANDLE_RAW (types);
857         args [1] = MONO_HANDLE_RAW (exceptions);
858
859         mono_runtime_invoke_checked (method, MONO_HANDLE_RAW (exc), args, error);
860         return_val_if_nok (error, MONO_HANDLE_CAST (MonoException, NULL_HANDLE));
861
862         return exc;
863 }
864
865 /**
866  * mono_get_exception_runtime_wrapped:
867  */
868 MonoException *
869 mono_get_exception_runtime_wrapped (MonoObject *wrapped_exception)
870 {
871         MonoError error;
872         MonoException *ret = mono_get_exception_runtime_wrapped_checked (wrapped_exception, &error);
873         if (!is_ok (&error)) {
874                 mono_error_cleanup (&error);
875                 return NULL;
876         }
877
878         return ret;
879 }
880
881 MonoException *
882 mono_get_exception_runtime_wrapped_checked (MonoObject *wrapped_exception, MonoError *error)
883 {
884         MonoClass *klass;
885         MonoObject *o;
886         MonoMethod *method;
887         MonoDomain *domain = mono_domain_get ();
888         gpointer params [16];
889
890         klass = mono_class_load_from_name (mono_get_corlib (), "System.Runtime.CompilerServices", "RuntimeWrappedException");
891
892         o = mono_object_new_checked (domain, klass, error);
893         mono_error_assert_ok (error);
894         g_assert (o != NULL);
895
896         method = mono_class_get_method_from_name (klass, ".ctor", 1);
897         g_assert (method);
898
899         params [0] = wrapped_exception;
900
901         mono_runtime_invoke_checked (method, o, params, error);
902         return_val_if_nok (error, NULL);
903
904         return (MonoException *)o;
905 }       
906
907 static gboolean
908 append_frame_and_continue (MonoMethod *method, gpointer ip, size_t native_offset, gboolean managed, gpointer user_data)
909 {
910         MonoDomain *domain = mono_domain_get ();
911         GString *text = (GString*)user_data;
912
913         if (method) {
914                 char *msg = mono_debug_print_stack_frame (method, native_offset, domain);
915                 g_string_append_printf (text, "%s\n", msg);
916                 g_free (msg);
917         } else {
918                 g_string_append_printf (text, "<unknown native frame 0x%x>\n", ip);
919         }
920
921         return FALSE;
922 }
923
924 char *
925 mono_exception_get_managed_backtrace (MonoException *exc)
926 {
927         GString *text;
928
929         text = g_string_new_len (NULL, 20);
930
931         if (!mono_get_eh_callbacks ()->mono_exception_walk_trace (exc, append_frame_and_continue, text))
932                 g_string_append (text, "managed backtrace not available\n");
933
934         return g_string_free (text, FALSE);
935 }
936
937 char *
938 mono_exception_handle_get_native_backtrace (MonoExceptionHandle exc)
939 {
940 #ifdef HAVE_BACKTRACE_SYMBOLS
941         MonoDomain *domain;
942         MonoArrayHandle arr = MONO_HANDLE_NEW(MonoArray, NULL);
943         int i, len;
944         GString *text;
945         char **messages;
946
947         MONO_HANDLE_GET (arr, exc, native_trace_ips);
948
949         if (MONO_HANDLE_IS_NULL(arr))
950                 return g_strdup ("");
951         domain = mono_domain_get ();
952         len = mono_array_handle_length (arr);
953         text = g_string_new_len (NULL, len * 20);
954         uint32_t gchandle;
955         void *addr = MONO_ARRAY_HANDLE_PIN (arr, gpointer, 0, &gchandle);
956         MONO_ENTER_GC_SAFE;
957         messages = backtrace_symbols (addr, len);
958         MONO_EXIT_GC_SAFE;
959         mono_gchandle_free (gchandle);
960
961         for (i = 0; i < len; ++i) {
962                 gpointer ip;
963                 MONO_HANDLE_ARRAY_GETVAL (ip, arr, gpointer, i);
964                 MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), (char *)ip);
965                 if (ji) {
966                         char *msg = mono_debug_print_stack_frame (mono_jit_info_get_method (ji), (char*)ip - (char*)ji->code_start, domain);
967                         g_string_append_printf (text, "%s\n", msg);
968                         g_free (msg);
969                 } else {
970                         g_string_append_printf (text, "%s\n", messages [i]);
971                 }
972         }
973
974         g_free (messages);
975         return g_string_free (text, FALSE);
976 #else
977         return g_strdup ("");
978 #endif
979 }
980
981 MonoStringHandle
982 ves_icall_Mono_Runtime_GetNativeStackTrace (MonoExceptionHandle exc, MonoError *error)
983 {
984         char *trace;
985         MonoStringHandle res;
986         error_init (error);
987
988         if (!exc) {
989                 mono_error_set_argument_null (error, "exception", "");
990                 return NULL_HANDLE_STRING;
991         }
992
993         trace = mono_exception_handle_get_native_backtrace (exc);
994         res = mono_string_new_handle (mono_domain_get (), trace, error);
995         g_free (trace);
996         return res;
997 }
998
999 /**
1000  * mono_error_raise_exception:
1001  * \param target_error the exception to raise
1002  *
1003  * Raises the exception of \p target_error.
1004  * Does nothing if \p target_error has a success error code.
1005  * Aborts in case of a double fault. This happens when it can't recover from an error caused by trying
1006  * to construct the first exception object.
1007  * The error object \p target_error is cleaned up.
1008 */
1009 void
1010 mono_error_raise_exception (MonoError *target_error)
1011 {
1012         MonoException *ex = mono_error_convert_to_exception (target_error);
1013         if (ex)
1014                 mono_raise_exception (ex);
1015 }
1016
1017 /**
1018  * mono_error_set_pending_exception:
1019  * \param error The error
1020  * If \p error is set, convert it to an exception and set the pending exception for the current icall.
1021  * \returns TRUE if \p error was set, or FALSE otherwise, so that you can write:
1022  *    if (mono_error_set_pending_exception (error)) {
1023  *      { ... cleanup code ... }
1024  *      return;
1025  *    }
1026  */
1027 gboolean
1028 mono_error_set_pending_exception (MonoError *error)
1029 {
1030         MonoException *ex = mono_error_convert_to_exception (error);
1031         if (ex) {
1032                 mono_set_pending_exception (ex);
1033                 return TRUE;
1034         } else {
1035                 return FALSE;
1036         }
1037 }
1038
1039 void
1040 mono_install_unhandled_exception_hook (MonoUnhandledExceptionFunc func, void *user_data)
1041 {
1042         unhandled_exception_hook = func;
1043         unhandled_exception_hook_data = user_data;
1044 }
1045
1046 void
1047 mono_invoke_unhandled_exception_hook (MonoObject *exc)
1048 {
1049         if (unhandled_exception_hook) {
1050                 unhandled_exception_hook (exc, unhandled_exception_hook_data);
1051         } else {
1052                 MonoError inner_error;
1053                 MonoObject *other = NULL;
1054                 MonoString *str = mono_object_try_to_string (exc, &other, &inner_error);
1055                 char *msg = NULL;
1056                 
1057                 if (str && is_ok (&inner_error)) {
1058                         msg = mono_string_to_utf8_checked (str, &inner_error);
1059                         if (!is_ok (&inner_error)) {
1060                                 msg = g_strdup_printf ("Nested exception while formatting original exception");
1061                                 mono_error_cleanup (&inner_error);
1062                         }
1063                 } else if (other) {
1064                         char *original_backtrace = mono_exception_get_managed_backtrace ((MonoException*)exc);
1065                         char *nested_backtrace = mono_exception_get_managed_backtrace ((MonoException*)other);
1066
1067                         msg = g_strdup_printf ("Nested exception detected.\nOriginal Exception: %s\nNested exception:%s\n",
1068                                 original_backtrace, nested_backtrace);
1069
1070                         g_free (original_backtrace);
1071                         g_free (nested_backtrace);
1072                 } else {
1073                         msg = g_strdup ("Nested exception trying to figure out what went wrong");
1074                 }
1075                 mono_runtime_printf_err ("[ERROR] FATAL UNHANDLED EXCEPTION: %s", msg);
1076                 g_free (msg);
1077 #if defined(HOST_IOS)
1078                 g_assertion_message ("Terminating runtime due to unhandled exception");
1079 #else
1080                 exit (mono_environment_exitcode_get ());
1081 #endif
1082         }
1083
1084         g_assert_not_reached ();
1085 }