[docs] Enable documentation for metadata.
[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  * @image: the Mono image where to look for the class
40  * @name_space: the namespace for the class
41  * @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  * @domain: Domain where the return object will be created.
58  * @image: the Mono image where to look for the class
59  * @name_space: the namespace for the class
60  * @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  * @image: the Mono image where to look for the class
96  * @token: The type token of the class
97  *
98  * Creates an exception of the type given by @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  * @image: the Mono image where to look for the class
168  * @name_space: the namespace for the class
169  * @name: class name
170  * @a1: first string argument to pass
171  * @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  * @image: the Mono image where to look for the class
193  * @name_space: the namespace for the class
194  * @name: class name
195  * @a1: first string argument to pass
196  * @a2: second string argument to pass
197  * @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 @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  * @image: the Mono image where to look for the class
221  * @name_space: the namespace for the class
222  * @name: class name
223  * @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  *
284  * Returns: a new instance of the `System.DivideByZeroException`
285  */
286 MonoException *
287 mono_get_exception_divide_by_zero ()
288 {
289         return mono_exception_from_name (mono_get_corlib (), "System",
290                                          "DivideByZeroException");
291 }
292
293 /**
294  * mono_get_exception_security:
295  *
296  * Returns: a new instance of the `System.Security.SecurityException`
297  */
298 MonoException *
299 mono_get_exception_security ()
300 {
301         return mono_exception_from_name (mono_get_corlib (), "System.Security",
302                                          "SecurityException");
303 }
304
305 /**
306  * mono_get_exception_thread_abort:
307  *
308  * Returns: a new instance of the `System.Threading.ThreadAbortException`
309  */
310 MonoException *
311 mono_get_exception_thread_abort ()
312 {
313         return mono_exception_from_name (mono_get_corlib (), "System.Threading",
314                                          "ThreadAbortException");
315 }
316
317 /**
318  * mono_get_exception_thread_interrupted:
319  *
320  * Returns: a new instance of the `System.Threading.ThreadInterruptedException`
321  */
322 MonoException *
323 mono_get_exception_thread_interrupted ()
324 {
325         return mono_exception_from_name (mono_get_corlib (), "System.Threading",
326                                          "ThreadInterruptedException");
327 }
328
329 /**
330  * mono_get_exception_arithmetic:
331  *
332  * Returns: a new instance of the `System.ArithmeticException`
333  */
334 MonoException *
335 mono_get_exception_arithmetic ()
336 {
337         return mono_exception_from_name (mono_get_corlib (), "System",
338                                          "ArithmeticException");
339 }
340
341 /**
342  * mono_get_exception_overflow:
343  *
344  * Returns: a new instance of the `System.OverflowException`
345  */
346 MonoException *
347 mono_get_exception_overflow ()
348 {
349         return mono_exception_from_name (mono_get_corlib (), "System",
350                                          "OverflowException");
351 }
352
353 /**
354  * mono_get_exception_null_reference:
355  *
356  * Returns: a new instance of the `System.NullReferenceException`
357  */
358 MonoException *
359 mono_get_exception_null_reference ()
360 {
361         return mono_exception_from_name (mono_get_corlib (), "System",
362                                          "NullReferenceException");
363 }
364
365 /**
366  * mono_get_exception_execution_engine:
367  * @msg: the message to pass to the user
368  *
369  * Returns: a new instance of the `System.ExecutionEngineException`
370  */
371 MonoException *
372 mono_get_exception_execution_engine (const char *msg)
373 {
374         return mono_exception_from_name_msg (mono_get_corlib (), "System", "ExecutionEngineException", msg);
375 }
376
377 /**
378  * mono_get_exception_serialization:
379  * @msg: the message to pass to the user
380  *
381  * Returns: a new instance of the `System.Runtime.Serialization.SerializationException`
382  */
383 MonoException *
384 mono_get_exception_serialization (const char *msg)
385 {
386         return mono_exception_from_name_msg (mono_get_corlib (), "System.Runtime.Serialization", "SerializationException", msg);
387 }
388
389 /**
390  * mono_get_exception_invalid_cast:
391  *
392  * Returns: a new instance of the `System.InvalidCastException`
393  */
394 MonoException *
395 mono_get_exception_invalid_cast ()
396 {
397         return mono_exception_from_name (mono_get_corlib (), "System", "InvalidCastException");
398 }
399
400 /**
401  * mono_get_exception_invalid_operation:
402  * @msg: the message to pass to the user
403  *
404  * Returns: a new instance of the `System.InvalidOperationException`
405  */
406 MonoException *
407 mono_get_exception_invalid_operation (const char *msg)
408 {
409         return mono_exception_from_name_msg (mono_get_corlib (), "System",
410                                         "InvalidOperationException", msg);
411 }
412
413 /**
414  * mono_get_exception_index_out_of_range:
415  *
416  * Returns: a new instance of the `System.IndexOutOfRangeException`
417  */
418 MonoException *
419 mono_get_exception_index_out_of_range ()
420 {
421         return mono_exception_from_name (mono_get_corlib (), "System",
422                                          "IndexOutOfRangeException");
423 }
424
425 /**
426  * mono_get_exception_array_type_mismatch:
427  *
428  * Returns: a new instance of the `System.ArrayTypeMismatchException`
429  */
430 MonoException *
431 mono_get_exception_array_type_mismatch ()
432 {
433         return mono_exception_from_name (mono_get_corlib (), "System",
434                                          "ArrayTypeMismatchException");
435 }
436
437 /**
438  * mono_get_exception_type_load:
439  * @class_name: the name of the class that could not be loaded
440  * @assembly_name: the assembly where the class was looked up.
441  *
442  * Returns: a new instance of the `System.TypeLoadException`
443  */
444 MonoException *
445 mono_get_exception_type_load (MonoString *class_name, char *assembly_name)
446 {
447         MonoString *s = assembly_name ? mono_string_new (mono_domain_get (), assembly_name) : mono_string_new (mono_domain_get (), "");
448
449         MonoError error;
450         MonoException *ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System",
451                                                                    "TypeLoadException", class_name, s, &error);
452         mono_error_assert_ok (&error);
453         return ret;
454 }
455
456 /**
457  * mono_get_exception_not_implemented:
458  * @msg: the message to pass to the user
459  *
460  * Returns: a new instance of the `System.NotImplementedException`
461  */
462 MonoException *
463 mono_get_exception_not_implemented (const char *msg)
464 {
465         return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotImplementedException", msg);
466 }
467
468 /**
469  * mono_get_exception_not_supported:
470  * @msg: the message to pass to the user
471  *
472  * Returns: a new instance of the `System.NotSupportedException`
473  */
474 MonoException *
475 mono_get_exception_not_supported (const char *msg)
476 {
477         return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotSupportedException", msg);
478 }
479
480 /**
481  * mono_get_exception_missing_method:
482  * @class_name: the class where the lookup was performed.
483  * @member_name: the name of the missing method.
484  *
485  * Returns: a new instance of the `System.MissingMethodException`
486  */
487 MonoException *
488 mono_get_exception_missing_method (const char *class_name, const char *member_name)
489 {
490         MonoString *s1 = mono_string_new (mono_domain_get (), class_name);
491         MonoString *s2 = mono_string_new (mono_domain_get (), member_name);
492
493         MonoError error;
494         MonoException *ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System",
495                                                                            "MissingMethodException", s1, s2, &error);
496         mono_error_assert_ok (&error);
497         return ret;
498 }
499
500 /**
501  * mono_get_exception_missing_field:
502  * @class_name: the class where the lookup was performed
503  * @member_name: the name of the missing method.
504  *
505  * Returns: a new instance of the `System.MissingFieldException`
506  */
507 MonoException *
508 mono_get_exception_missing_field (const char *class_name, const char *member_name)
509 {
510         MonoString *s1 = mono_string_new (mono_domain_get (), class_name);
511         MonoString *s2 = mono_string_new (mono_domain_get (), member_name);
512
513         MonoError error;
514         MonoException *ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System",
515                                                                    "MissingFieldException", s1, s2, &error);
516         mono_error_assert_ok (&error);
517         return ret;
518 }
519
520 /**
521  * mono_get_exception_argument_null:
522  * @arg: the name of the argument that is null
523  *
524  * Returns: a new instance of the `System.ArgumentNullException`
525  */
526 MonoException*
527 mono_get_exception_argument_null (const char *arg)
528 {
529         MonoException *ex;
530
531         ex = mono_exception_from_name ( 
532                 mono_get_corlib (), "System", "ArgumentNullException");
533
534         if (arg) {
535                 MonoArgumentException *argex = (MonoArgumentException *)ex;
536                 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
537         }
538         
539         return ex;
540 }
541
542 /**
543  * mono_get_exception_argument:
544  * @arg: the name of the invalid argument.
545  *
546  * Returns: a new instance of the `System.ArgumentException`
547  */
548 MonoException *
549 mono_get_exception_argument (const char *arg, const char *msg)
550 {
551         MonoException *ex;
552
553         ex = mono_exception_from_name_msg (
554                 mono_get_corlib (), "System", "ArgumentException", msg);
555
556         if (arg) {
557                 MonoArgumentException *argex = (MonoArgumentException *)ex;
558                 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
559         }
560         
561         return ex;
562 }
563
564 /**
565  * mono_get_exception_argument_out_of_range:
566  * @arg: the name of the out of range argument.
567  *
568  * Returns: a new instance of the `System.ArgumentOutOfRangeException`
569  */
570 MonoException *
571 mono_get_exception_argument_out_of_range (const char *arg)
572 {
573         MonoException *ex;
574
575         ex = mono_exception_from_name (
576                 mono_get_corlib (), "System", "ArgumentOutOfRangeException");
577
578         if (arg) {
579                 MonoArgumentException *argex = (MonoArgumentException *)ex;
580                 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
581         }
582         
583         return ex;
584 }
585
586 /**
587  * mono_get_exception_thread_state:
588  * @msg: the message to present to the user
589  *
590  * Returns: a new instance of the `System.Threading.ThreadStateException`
591  */
592 MonoException *
593 mono_get_exception_thread_state (const char *msg)
594 {
595         return mono_exception_from_name_msg (
596                 mono_get_corlib (), "System.Threading", "ThreadStateException", msg);
597 }
598
599 /**
600  * mono_get_exception_io:
601  * @msg: the message to present to the user
602  *
603  * Returns: a new instance of the `System.IO.IOException`
604  */
605 MonoException *
606 mono_get_exception_io (const char *msg)
607 {
608         return mono_exception_from_name_msg ( 
609                 mono_get_corlib (), "System.IO", "IOException", msg);
610 }
611
612 /**
613  * mono_get_exception_file_not_found:
614  * @fname: the name of the file not found.
615  *
616  * Returns: a new instance of the `System.IO.FileNotFoundException`
617  */
618 MonoException *
619 mono_get_exception_file_not_found (MonoString *fname)
620 {
621         MonoError error;
622         MonoException *ret = mono_exception_from_name_two_strings_checked (
623                 mono_get_corlib (), "System.IO", "FileNotFoundException", fname, fname, &error);
624         mono_error_assert_ok (&error);
625         return ret;
626 }
627
628 /**
629  * mono_get_exception_file_not_found2:
630  * @msg: an informative message for the user.
631  * @fname: the name of the file not found.
632  *
633  * Returns: a new instance of the `System.IO.FileNotFoundException`
634  */
635 MonoException *
636 mono_get_exception_file_not_found2 (const char *msg, MonoString *fname)
637 {
638         MonoString *s = msg ? mono_string_new (mono_domain_get (), msg) : NULL;
639
640         MonoError error;
641         MonoException *ret = mono_exception_from_name_two_strings_checked (
642                 mono_get_corlib (), "System.IO", "FileNotFoundException", s, fname, &error);
643         mono_error_assert_ok (&error);
644         return ret;
645 }
646
647 /**
648  * mono_get_exception_type_initialization:
649  * @type_name: the name of the type that failed to initialize.
650  * @inner: the inner exception.
651  *
652  * Returns: a new instance of the `System.TypeInitializationException`
653  */
654 MonoException *
655 mono_get_exception_type_initialization (const gchar *type_name, MonoException *inner)
656 {
657         MonoError error;
658         MonoException *ret = mono_get_exception_type_initialization_checked (type_name, inner, &error);
659         if (!is_ok (&error)) {
660                 mono_error_cleanup (&error);
661                 return NULL;
662         }
663
664         return ret;
665 }
666
667 MonoException *
668 mono_get_exception_type_initialization_checked (const gchar *type_name, MonoException *inner, MonoError *error)
669 {
670         MonoClass *klass;
671         gpointer args [2];
672         MonoObject *exc;
673         MonoMethod *method;
674         gpointer iter;
675
676         klass = mono_class_load_from_name (mono_get_corlib (), "System", "TypeInitializationException");
677
678         mono_class_init (klass);
679
680         iter = NULL;
681         while ((method = mono_class_get_methods (klass, &iter))) {
682                 if (!strcmp (".ctor", mono_method_get_name (method))) {
683                         MonoMethodSignature *sig = mono_method_signature (method);
684
685                         if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_STRING && mono_class_from_mono_type (sig->params [1]) == mono_defaults.exception_class)
686                                 break;
687                 }
688                 method = NULL;
689         }
690         g_assert (method);
691
692         args [0] = mono_string_new (mono_domain_get (), type_name);
693         args [1] = inner;
694
695         exc = mono_object_new_checked (mono_domain_get (), klass, error);
696         mono_error_assert_ok (error);
697
698         mono_runtime_invoke_checked (method, exc, args, error);
699         return_val_if_nok (error, NULL);
700
701         return (MonoException *) exc;
702 }
703
704 /**
705  * mono_get_exception_synchronization_lock:
706  * @inner: the inner exception.
707  *
708  * Returns: a new instance of the `System.SynchronizationLockException`
709  */
710 MonoException *
711 mono_get_exception_synchronization_lock (const char *msg)
712 {
713         return mono_exception_from_name_msg (mono_get_corlib (), "System.Threading", "SynchronizationLockException", msg);
714 }
715
716 /**
717  * mono_get_exception_cannot_unload_appdomain:
718  * @inner: the inner exception.
719  *
720  * Returns: a new instance of the `System.CannotUnloadAppDomainException`
721  */
722 MonoException *
723 mono_get_exception_cannot_unload_appdomain (const char *msg)
724 {
725         return mono_exception_from_name_msg (mono_get_corlib (), "System", "CannotUnloadAppDomainException", msg);
726 }
727
728 /**
729  * mono_get_exception_appdomain_unloaded
730  *
731  * Returns: a new instance of the `System.AppDomainUnloadedException`
732  */
733 MonoException *
734 mono_get_exception_appdomain_unloaded (void)
735 {
736         return mono_exception_from_name (mono_get_corlib (), "System", "AppDomainUnloadedException");
737 }
738
739 /**
740  * mono_get_exception_bad_image_format:
741  * @msg: an informative message for the user.
742  *
743  * Returns: a new instance of the `System.BadImageFormatException`
744  */
745 MonoException *
746 mono_get_exception_bad_image_format (const char *msg)
747 {
748         return mono_exception_from_name_msg (mono_get_corlib (), "System", "BadImageFormatException", msg);
749 }       
750
751 /**
752  * mono_get_exception_bad_image_format2:
753  * @msg: an informative message for the user.
754  * @fname: The full name of the file with the invalid image.
755  *
756  * Returns: a new instance of the `System.BadImageFormatException`
757  */
758 MonoException *
759 mono_get_exception_bad_image_format2 (const char *msg, MonoString *fname)
760 {
761         MonoString *s = msg ? mono_string_new (mono_domain_get (), msg) : NULL;
762
763         MonoError error;
764         MonoException *ret = mono_exception_from_name_two_strings_checked (
765                 mono_get_corlib (), "System", "BadImageFormatException", s, fname, &error);
766         mono_error_assert_ok (&error);
767         return ret;
768 }
769
770 /**
771  * mono_get_exception_stack_overflow:
772  *
773  * Returns: a new instance of the `System.StackOverflowException`
774  */
775 MonoException *
776 mono_get_exception_stack_overflow (void)
777 {
778         return mono_exception_from_name (mono_get_corlib (), "System", "StackOverflowException");       
779 }
780
781 /**
782  * mono_get_exception_out_of_memory:
783  *
784  * Returns: a new instance of the `System.OutOfMemoryException`
785  */
786 MonoException *
787 mono_get_exception_out_of_memory (void)
788 {
789         return mono_exception_from_name (mono_get_corlib (), "System", "OutOfMemoryException");
790 }
791
792 /**
793  * mono_get_exception_field_access:
794  *
795  * Returns: a new instance of the `System.FieldAccessException`
796  */
797 MonoException *
798 mono_get_exception_field_access (void)
799 {
800         return mono_exception_from_name (mono_get_corlib (), "System", "FieldAccessException");
801 }
802
803 /**
804  * mono_get_exception_field_access2:
805  * @msg: an informative message for the user.
806  *
807  * Returns: a new instance of the `System.FieldAccessException`
808  */
809 MonoException *
810 mono_get_exception_field_access_msg (const char *msg)
811 {
812         return mono_exception_from_name_msg (mono_get_corlib (), "System", "FieldAccessException", msg);
813 }
814
815 /**
816  * mono_get_exception_method_access:
817  *
818  * Returns: a new instance of the `System.MethodAccessException`
819  */
820 MonoException *
821 mono_get_exception_method_access (void)
822 {
823         return mono_exception_from_name (mono_get_corlib (), "System", "MethodAccessException");
824 }
825
826 /**
827  * mono_get_exception_method_access2:
828  * @msg: an informative message for the user.
829  *
830  * Returns: a new instance of the `System.MethodAccessException`
831  */
832 MonoException *
833 mono_get_exception_method_access_msg (const char *msg)
834 {
835         return mono_exception_from_name_msg (mono_get_corlib (), "System", "MethodAccessException", msg);
836 }
837
838 /**
839  * mono_get_exception_reflection_type_load:
840  * @types: an array of types that were defined in the moduled loaded.
841  * @exceptions: an array of exceptions that were thrown during the type loading.
842  *
843  * Returns: a new instance of the `System.Reflection.ReflectionTypeLoadException`
844  */
845 MonoException *
846 mono_get_exception_reflection_type_load (MonoArray *types_raw, MonoArray *exceptions_raw)
847 {
848         HANDLE_FUNCTION_ENTER ();
849         MonoError error;
850         MONO_HANDLE_DCL (MonoArray, types);
851         MONO_HANDLE_DCL (MonoArray, exceptions);
852         MonoExceptionHandle ret = mono_get_exception_reflection_type_load_checked (types, exceptions, &error);
853         if (is_ok (&error)) {
854                 mono_error_cleanup (&error);
855                 ret = MONO_HANDLE_CAST (MonoException, NULL_HANDLE);
856                 goto leave;
857         }
858
859 leave:
860         HANDLE_FUNCTION_RETURN_OBJ (ret);
861
862 }
863
864 MonoExceptionHandle
865 mono_get_exception_reflection_type_load_checked (MonoArrayHandle types, MonoArrayHandle exceptions, MonoError *error)
866 {
867         MonoClass *klass;
868         MonoMethod *method;
869         gpointer iter;
870
871         error_init (error);
872
873         klass = mono_class_load_from_name (mono_get_corlib (), "System.Reflection", "ReflectionTypeLoadException");
874
875         mono_class_init (klass);
876
877         /* Find the Type[], Exception[] ctor */
878         iter = NULL;
879         while ((method = mono_class_get_methods (klass, &iter))) {
880                 if (!strcmp (".ctor", mono_method_get_name (method))) {
881                         MonoMethodSignature *sig = mono_method_signature (method);
882
883                         if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_SZARRAY && sig->params [1]->type == MONO_TYPE_SZARRAY)
884                                 break;
885                 }
886                 method = NULL;
887         }
888         g_assert (method);
889
890         MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, mono_object_new_checked (mono_domain_get (), klass, error));
891         mono_error_assert_ok (error);
892
893         gpointer args [2];
894         args [0] = MONO_HANDLE_RAW (types);
895         args [1] = MONO_HANDLE_RAW (exceptions);
896
897         mono_runtime_invoke_checked (method, MONO_HANDLE_RAW (exc), args, error);
898         return_val_if_nok (error, MONO_HANDLE_CAST (MonoException, NULL_HANDLE));
899
900         return exc;
901 }
902
903 MonoException *
904 mono_get_exception_runtime_wrapped (MonoObject *wrapped_exception)
905 {
906         MonoError error;
907         MonoException *ret = mono_get_exception_runtime_wrapped_checked (wrapped_exception, &error);
908         if (!is_ok (&error)) {
909                 mono_error_cleanup (&error);
910                 return NULL;
911         }
912
913         return ret;
914 }
915
916 MonoException *
917 mono_get_exception_runtime_wrapped_checked (MonoObject *wrapped_exception, MonoError *error)
918 {
919         MonoClass *klass;
920         MonoObject *o;
921         MonoMethod *method;
922         MonoDomain *domain = mono_domain_get ();
923         gpointer params [16];
924
925         klass = mono_class_load_from_name (mono_get_corlib (), "System.Runtime.CompilerServices", "RuntimeWrappedException");
926
927         o = mono_object_new_checked (domain, klass, error);
928         mono_error_assert_ok (error);
929         g_assert (o != NULL);
930
931         method = mono_class_get_method_from_name (klass, ".ctor", 1);
932         g_assert (method);
933
934         params [0] = wrapped_exception;
935
936         mono_runtime_invoke_checked (method, o, params, error);
937         return_val_if_nok (error, NULL);
938
939         return (MonoException *)o;
940 }       
941
942 static gboolean
943 append_frame_and_continue (MonoMethod *method, gpointer ip, size_t native_offset, gboolean managed, gpointer user_data)
944 {
945         MonoDomain *domain = mono_domain_get ();
946         GString *text = (GString*)user_data;
947
948         if (method) {
949                 char *msg = mono_debug_print_stack_frame (method, native_offset, domain);
950                 g_string_append_printf (text, "%s\n", msg);
951                 g_free (msg);
952         } else {
953                 g_string_append_printf (text, "<unknown native frame 0x%x>\n", ip);
954         }
955
956         return FALSE;
957 }
958
959 char *
960 mono_exception_get_managed_backtrace (MonoException *exc)
961 {
962         GString *text;
963
964         text = g_string_new_len (NULL, 20);
965
966         if (!mono_get_eh_callbacks ()->mono_exception_walk_trace (exc, append_frame_and_continue, text))
967                 g_string_append (text, "managed backtrace not available\n");
968
969         return g_string_free (text, FALSE);
970 }
971
972 char *
973 mono_exception_handle_get_native_backtrace (MonoExceptionHandle exc)
974 {
975 #ifdef HAVE_BACKTRACE_SYMBOLS
976         MonoDomain *domain;
977         MonoArrayHandle arr = MONO_HANDLE_NEW(MonoArray, NULL);
978         int i, len;
979         GString *text;
980         char **messages;
981
982         MONO_HANDLE_GET (arr, exc, native_trace_ips);
983
984         if (MONO_HANDLE_IS_NULL(arr))
985                 return g_strdup ("");
986         domain = mono_domain_get ();
987         len = mono_array_handle_length (arr);
988         text = g_string_new_len (NULL, len * 20);
989         uint32_t gchandle;
990         void *addr = MONO_ARRAY_HANDLE_PIN (arr, gpointer, 0, &gchandle);
991         MONO_ENTER_GC_SAFE;
992         messages = backtrace_symbols (addr, len);
993         MONO_EXIT_GC_SAFE;
994         mono_gchandle_free (gchandle);
995
996         for (i = 0; i < len; ++i) {
997                 gpointer ip;
998                 MONO_HANDLE_ARRAY_GETVAL (ip, arr, gpointer, i);
999                 MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), (char *)ip);
1000                 if (ji) {
1001                         char *msg = mono_debug_print_stack_frame (mono_jit_info_get_method (ji), (char*)ip - (char*)ji->code_start, domain);
1002                         g_string_append_printf (text, "%s\n", msg);
1003                         g_free (msg);
1004                 } else {
1005                         g_string_append_printf (text, "%s\n", messages [i]);
1006                 }
1007         }
1008
1009         g_free (messages);
1010         return g_string_free (text, FALSE);
1011 #else
1012         return g_strdup ("");
1013 #endif
1014 }
1015
1016 MonoStringHandle
1017 ves_icall_Mono_Runtime_GetNativeStackTrace (MonoExceptionHandle exc, MonoError *error)
1018 {
1019         char *trace;
1020         MonoStringHandle res;
1021         error_init (error);
1022
1023         if (!exc) {
1024                 mono_error_set_argument_null (error, "exception", "");
1025                 return NULL_HANDLE_STRING;
1026         }
1027
1028         trace = mono_exception_handle_get_native_backtrace (exc);
1029         res = mono_string_new_handle (mono_domain_get (), trace, error);
1030         g_free (trace);
1031         return res;
1032 }
1033
1034 /**
1035  * mono_error_raise_exception:
1036  * @target_error: the exception to raise
1037  *
1038  * Raises the exception of @target_error.
1039  * Does nothing if @target_error has a success error code.
1040  * Aborts in case of a double fault. This happens when it can't recover from an error caused by trying
1041  * to construct the first exception object.
1042  * The error object @target_error is cleaned up.
1043 */
1044 void
1045 mono_error_raise_exception (MonoError *target_error)
1046 {
1047         MonoException *ex = mono_error_convert_to_exception (target_error);
1048         if (ex)
1049                 mono_raise_exception (ex);
1050 }
1051
1052 /**
1053  * mono_error_set_pending_exception:
1054  * @error: The error
1055  *
1056  *
1057  * If @error is set, convert it to an exception and set the pending exception for the current icall.
1058  * Returns TRUE if @error was set, or FALSE otherwise, so that you can write:
1059  *    if (mono_error_set_pending_exception (error)) {
1060  *      { ... cleanup code ... }
1061  *      return;
1062  *    }
1063  */
1064 gboolean
1065 mono_error_set_pending_exception (MonoError *error)
1066 {
1067         MonoException *ex = mono_error_convert_to_exception (error);
1068         if (ex) {
1069                 mono_set_pending_exception (ex);
1070                 return TRUE;
1071         } else {
1072                 return FALSE;
1073         }
1074 }
1075
1076 void
1077 mono_install_unhandled_exception_hook (MonoUnhandledExceptionFunc func, void *user_data)
1078 {
1079         unhandled_exception_hook = func;
1080         unhandled_exception_hook_data = user_data;
1081 }
1082
1083 void
1084 mono_invoke_unhandled_exception_hook (MonoObject *exc)
1085 {
1086         if (unhandled_exception_hook) {
1087                 unhandled_exception_hook (exc, unhandled_exception_hook_data);
1088         } else {
1089                 MonoError inner_error;
1090                 MonoObject *other = NULL;
1091                 MonoString *str = mono_object_try_to_string (exc, &other, &inner_error);
1092                 char *msg = NULL;
1093                 
1094                 if (str && is_ok (&inner_error)) {
1095                         msg = mono_string_to_utf8_checked (str, &inner_error);
1096                         if (!is_ok (&inner_error)) {
1097                                 msg = g_strdup_printf ("Nested exception while formatting original exception");
1098                                 mono_error_cleanup (&inner_error);
1099                         }
1100                 } else if (other) {
1101                         char *original_backtrace = mono_exception_get_managed_backtrace ((MonoException*)exc);
1102                         char *nested_backtrace = mono_exception_get_managed_backtrace ((MonoException*)other);
1103
1104                         msg = g_strdup_printf ("Nested exception detected.\nOriginal Exception: %s\nNested exception:%s\n",
1105                                 original_backtrace, nested_backtrace);
1106
1107                         g_free (original_backtrace);
1108                         g_free (nested_backtrace);
1109                 } else {
1110                         msg = g_strdup ("Nested exception trying to figure out what went wrong");
1111                 }
1112                 mono_runtime_printf_err ("[ERROR] FATAL UNHANDLED EXCEPTION: %s", msg);
1113                 g_free (msg);
1114 #if defined(HOST_IOS)
1115                 g_assertion_message ("Terminating runtime due to unhandled exception");
1116 #else
1117                 exit (mono_environment_exitcode_get ());
1118 #endif
1119         }
1120
1121         g_assert_not_reached ();
1122 }