2 * exception.c: Exception handling
5 * Paolo Molaro (lupus@ximian.com)
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Dick Porter (dick@ximian.com)
8 * Miguel de Icaza (miguel@ximian.com)
10 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
15 #include <mono/metadata/exception.h>
16 #include <mono/metadata/exception-internals.h>
18 #include <mono/metadata/object-internals.h>
19 #include <mono/metadata/metadata-internals.h>
20 #include <mono/metadata/appdomain.h>
21 #include <mono/metadata/mono-debug.h>
22 #include <mono/utils/mono-error-internals.h>
25 #ifdef HAVE_EXECINFO_H
30 * mono_exception_from_name:
31 * @image: the Mono image where to look for the class
32 * @name_space: the namespace for the class
35 * Creates an exception of the given namespace/name class in the
38 * Returns: the initialized exception instance.
41 mono_exception_from_name (MonoImage *image, const char *name_space,
44 return mono_exception_from_name_domain (mono_domain_get (), image, name_space, name);
48 * mono_exception_from_name_domain:
49 * @domain: Domain where the return object will be created.
50 * @image: the Mono image where to look for the class
51 * @name_space: the namespace for the class
54 * Creates an exception object of the given namespace/name class on
57 * Returns: the initialized exception instance.
60 mono_exception_from_name_domain (MonoDomain *domain, MonoImage *image,
61 const char* name_space, const char *name)
66 MonoDomain *caller_domain = mono_domain_get ();
68 klass = mono_class_load_from_name (image, name_space, name);
70 o = mono_object_new_checked (domain, klass, &error);
71 g_assert (o != NULL && mono_error_ok (&error)); /* FIXME don't swallow the error */
73 if (domain != caller_domain)
74 mono_domain_set_internal (domain);
75 mono_runtime_object_init (o);
76 if (domain != caller_domain)
77 mono_domain_set_internal (caller_domain);
79 return (MonoException *)o;
84 * mono_exception_from_token:
85 * @image: the Mono image where to look for the class
86 * @token: The type token of the class
88 * Creates an exception of the type given by @token.
90 * Returns: the initialized exception instance.
93 mono_exception_from_token (MonoImage *image, guint32 token)
99 klass = mono_class_get_checked (image, token, &error);
100 g_assert (mono_error_ok (&error)); /* FIXME handle the error. */
102 o = mono_object_new_checked (mono_domain_get (), klass, &error);
103 g_assert (o != NULL && mono_error_ok (&error)); /* FIXME don't swallow the error */
105 mono_runtime_object_init (o);
107 return (MonoException *)o;
110 static MonoException *
111 create_exception_two_strings (MonoClass *klass, MonoString *a1, MonoString *a2, MonoError *error)
113 MonoDomain *domain = mono_domain_get ();
114 MonoMethod *method = NULL;
124 o = mono_object_new_checked (domain, klass, error);
125 mono_error_assert_ok (error);
128 while ((m = mono_class_get_methods (klass, &iter))) {
129 MonoMethodSignature *sig;
131 if (strcmp (".ctor", mono_method_get_name (m)))
133 sig = mono_method_signature (m);
134 if (sig->param_count != count)
137 if (sig->params [0]->type != MONO_TYPE_STRING)
139 if (count == 2 && sig->params [1]->type != MONO_TYPE_STRING)
148 mono_runtime_invoke_checked (method, o, args, error);
149 return_val_if_nok (error, NULL);
151 return (MonoException *) o;
155 * mono_exception_from_name_two_strings:
156 * @image: the Mono image where to look for the class
157 * @name_space: the namespace for the class
159 * @a1: first string argument to pass
160 * @a2: second string argument to pass
162 * Creates an exception from a constructor that takes two string
165 * Returns: the initialized exception instance.
168 mono_exception_from_name_two_strings (MonoImage *image, const char *name_space,
169 const char *name, MonoString *a1, MonoString *a2)
175 klass = mono_class_load_from_name (image, name_space, name);
177 ret = create_exception_two_strings (klass, a1, a2, &error);
178 mono_error_raise_exception (&error); /* FIXME don't raise here */
184 * mono_exception_from_name_msg:
185 * @image: the Mono image where to look for the class
186 * @name_space: the namespace for the class
188 * @msg: the message to embed inside the exception
190 * Creates an exception and initializes its message field.
192 * Returns: the initialized exception instance.
195 mono_exception_from_name_msg (MonoImage *image, const char *name_space,
196 const char *name, const char *msg)
200 ex = mono_exception_from_name (image, name_space, name);
203 MONO_OBJECT_SETREF (ex, message, mono_string_new (mono_object_get_domain ((MonoObject*)ex), msg));
209 * mono_exception_from_token_two_strings:
211 * Same as mono_exception_from_name_two_strings, but lookup the exception class using
215 mono_exception_from_token_two_strings (MonoImage *image, guint32 token,
216 MonoString *a1, MonoString *a2)
222 klass = mono_class_get_checked (image, token, &error);
223 mono_error_assert_ok (&error); /* FIXME handle the error. */
225 ret = create_exception_two_strings (klass, a1, a2, &error);
226 mono_error_raise_exception (&error); /* FIXME don't raise here */
232 * mono_get_exception_divide_by_zero:
234 * Returns: a new instance of the `System.DivideByZeroException`
237 mono_get_exception_divide_by_zero ()
239 return mono_exception_from_name (mono_get_corlib (), "System",
240 "DivideByZeroException");
244 * mono_get_exception_security:
246 * Returns: a new instance of the `System.Security.SecurityException`
249 mono_get_exception_security ()
251 return mono_exception_from_name (mono_get_corlib (), "System.Security",
252 "SecurityException");
256 * mono_get_exception_thread_abort:
258 * Returns: a new instance of the `System.Threading.ThreadAbortException`
261 mono_get_exception_thread_abort ()
263 return mono_exception_from_name (mono_get_corlib (), "System.Threading",
264 "ThreadAbortException");
268 * mono_get_exception_thread_interrupted:
270 * Returns: a new instance of the `System.Threading.ThreadInterruptedException`
273 mono_get_exception_thread_interrupted ()
275 return mono_exception_from_name (mono_get_corlib (), "System.Threading",
276 "ThreadInterruptedException");
280 * mono_get_exception_arithmetic:
282 * Returns: a new instance of the `System.ArithmeticException`
285 mono_get_exception_arithmetic ()
287 return mono_exception_from_name (mono_get_corlib (), "System",
288 "ArithmeticException");
292 * mono_get_exception_overflow:
294 * Returns: a new instance of the `System.OverflowException`
297 mono_get_exception_overflow ()
299 return mono_exception_from_name (mono_get_corlib (), "System",
300 "OverflowException");
304 * mono_get_exception_null_reference:
306 * Returns: a new instance of the `System.NullReferenceException`
309 mono_get_exception_null_reference ()
311 return mono_exception_from_name (mono_get_corlib (), "System",
312 "NullReferenceException");
316 * mono_get_exception_execution_engine:
317 * @msg: the message to pass to the user
319 * Returns: a new instance of the `System.ExecutionEngineException`
322 mono_get_exception_execution_engine (const char *msg)
324 return mono_exception_from_name_msg (mono_get_corlib (), "System", "ExecutionEngineException", msg);
328 * mono_get_exception_serialization:
329 * @msg: the message to pass to the user
331 * Returns: a new instance of the `System.Runtime.Serialization.SerializationException`
334 mono_get_exception_serialization (const char *msg)
336 return mono_exception_from_name_msg (mono_get_corlib (), "System.Runtime.Serialization", "SerializationException", msg);
340 * mono_get_exception_invalid_cast:
342 * Returns: a new instance of the `System.InvalidCastException`
345 mono_get_exception_invalid_cast ()
347 return mono_exception_from_name (mono_get_corlib (), "System", "InvalidCastException");
351 * mono_get_exception_invalid_operation:
352 * @msg: the message to pass to the user
354 * Returns: a new instance of the `System.InvalidOperationException`
357 mono_get_exception_invalid_operation (const char *msg)
359 return mono_exception_from_name_msg (mono_get_corlib (), "System",
360 "InvalidOperationException", msg);
364 * mono_get_exception_index_out_of_range:
366 * Returns: a new instance of the `System.IndexOutOfRangeException`
369 mono_get_exception_index_out_of_range ()
371 return mono_exception_from_name (mono_get_corlib (), "System",
372 "IndexOutOfRangeException");
376 * mono_get_exception_array_type_mismatch:
378 * Returns: a new instance of the `System.ArrayTypeMismatchException`
381 mono_get_exception_array_type_mismatch ()
383 return mono_exception_from_name (mono_get_corlib (), "System",
384 "ArrayTypeMismatchException");
388 * mono_get_exception_type_load:
389 * @class_name: the name of the class that could not be loaded
390 * @assembly_name: the assembly where the class was looked up.
392 * Returns: a new instance of the `System.TypeLoadException`
395 mono_get_exception_type_load (MonoString *class_name, char *assembly_name)
397 MonoString *s = assembly_name ? mono_string_new (mono_domain_get (), assembly_name) : mono_string_new (mono_domain_get (), "");
399 return mono_exception_from_name_two_strings (mono_get_corlib (), "System",
400 "TypeLoadException", class_name, s);
404 * mono_get_exception_not_implemented:
405 * @msg: the message to pass to the user
407 * Returns: a new instance of the `System.NotImplementedException`
410 mono_get_exception_not_implemented (const char *msg)
412 return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotImplementedException", msg);
416 * mono_get_exception_not_supported:
417 * @msg: the message to pass to the user
419 * Returns: a new instance of the `System.NotSupportedException`
422 mono_get_exception_not_supported (const char *msg)
424 return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotSupportedException", msg);
428 * mono_get_exception_missing_method:
429 * @class_name: the class where the lookup was performed.
430 * @member_name: the name of the missing method.
432 * Returns: a new instance of the `System.MissingMethodException`
435 mono_get_exception_missing_method (const char *class_name, const char *member_name)
437 MonoString *s1 = mono_string_new (mono_domain_get (), class_name);
438 MonoString *s2 = mono_string_new (mono_domain_get (), member_name);
440 return mono_exception_from_name_two_strings (mono_get_corlib (), "System",
441 "MissingMethodException", s1, s2);
445 * mono_get_exception_missing_field:
446 * @class_name: the class where the lookup was performed
447 * @member_name: the name of the missing method.
449 * Returns: a new instance of the `System.MissingFieldException`
452 mono_get_exception_missing_field (const char *class_name, const char *member_name)
454 MonoString *s1 = mono_string_new (mono_domain_get (), class_name);
455 MonoString *s2 = mono_string_new (mono_domain_get (), member_name);
457 return mono_exception_from_name_two_strings (mono_get_corlib (), "System",
458 "MissingFieldException", s1, s2);
462 * mono_get_exception_argument_null:
463 * @arg: the name of the argument that is null
465 * Returns: a new instance of the `System.ArgumentNullException`
468 mono_get_exception_argument_null (const char *arg)
472 ex = mono_exception_from_name (
473 mono_get_corlib (), "System", "ArgumentNullException");
476 MonoArgumentException *argex = (MonoArgumentException *)ex;
477 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
484 * mono_get_exception_argument:
485 * @arg: the name of the invalid argument.
487 * Returns: a new instance of the `System.ArgumentException`
490 mono_get_exception_argument (const char *arg, const char *msg)
494 ex = mono_exception_from_name_msg (
495 mono_get_corlib (), "System", "ArgumentException", msg);
498 MonoArgumentException *argex = (MonoArgumentException *)ex;
499 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
506 * mono_get_exception_argument_out_of_range:
507 * @arg: the name of the out of range argument.
509 * Returns: a new instance of the `System.ArgumentOutOfRangeException`
512 mono_get_exception_argument_out_of_range (const char *arg)
516 ex = mono_exception_from_name (
517 mono_get_corlib (), "System", "ArgumentOutOfRangeException");
520 MonoArgumentException *argex = (MonoArgumentException *)ex;
521 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
528 * mono_get_exception_thread_state:
529 * @msg: the message to present to the user
531 * Returns: a new instance of the `System.Threading.ThreadStateException`
534 mono_get_exception_thread_state (const char *msg)
536 return mono_exception_from_name_msg (
537 mono_get_corlib (), "System.Threading", "ThreadStateException", msg);
541 * mono_get_exception_io:
542 * @msg: the message to present to the user
544 * Returns: a new instance of the `System.IO.IOException`
547 mono_get_exception_io (const char *msg)
549 return mono_exception_from_name_msg (
550 mono_get_corlib (), "System.IO", "IOException", msg);
554 * mono_get_exception_file_not_found:
555 * @fname: the name of the file not found.
557 * Returns: a new instance of the `System.IO.FileNotFoundException`
560 mono_get_exception_file_not_found (MonoString *fname)
562 return mono_exception_from_name_two_strings (
563 mono_get_corlib (), "System.IO", "FileNotFoundException", fname, fname);
567 * mono_get_exception_file_not_found2:
568 * @msg: an informative message for the user.
569 * @fname: the name of the file not found.
571 * Returns: a new instance of the `System.IO.FileNotFoundException`
574 mono_get_exception_file_not_found2 (const char *msg, MonoString *fname)
576 MonoString *s = msg ? mono_string_new (mono_domain_get (), msg) : NULL;
578 return mono_exception_from_name_two_strings (
579 mono_get_corlib (), "System.IO", "FileNotFoundException", s, fname);
583 * mono_get_exception_type_initialization:
584 * @type_name: the name of the type that failed to initialize.
585 * @inner: the inner exception.
587 * Returns: a new instance of the `System.TypeInitializationException`
590 mono_get_exception_type_initialization (const gchar *type_name, MonoException *inner)
593 MonoException *ret = mono_get_exception_type_initialization_checked (type_name, inner, &error);
594 if (!is_ok (&error)) {
595 mono_error_cleanup (&error);
603 mono_get_exception_type_initialization_checked (const gchar *type_name, MonoException *inner, MonoError *error)
611 klass = mono_class_load_from_name (mono_get_corlib (), "System", "TypeInitializationException");
613 mono_class_init (klass);
616 while ((method = mono_class_get_methods (klass, &iter))) {
617 if (!strcmp (".ctor", mono_method_get_name (method))) {
618 MonoMethodSignature *sig = mono_method_signature (method);
620 if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_STRING && mono_class_from_mono_type (sig->params [1]) == mono_defaults.exception_class)
627 args [0] = mono_string_new (mono_domain_get (), type_name);
630 exc = mono_object_new_checked (mono_domain_get (), klass, error);
631 mono_error_assert_ok (error);
633 mono_runtime_invoke_checked (method, exc, args, error);
634 return_val_if_nok (error, NULL);
636 return (MonoException *) exc;
640 * mono_get_exception_synchronization_lock:
641 * @inner: the inner exception.
643 * Returns: a new instance of the `System.SynchronizationLockException`
646 mono_get_exception_synchronization_lock (const char *msg)
648 return mono_exception_from_name_msg (mono_get_corlib (), "System.Threading", "SynchronizationLockException", msg);
652 * mono_get_exception_cannot_unload_appdomain:
653 * @inner: the inner exception.
655 * Returns: a new instance of the `System.CannotUnloadAppDomainException`
658 mono_get_exception_cannot_unload_appdomain (const char *msg)
660 return mono_exception_from_name_msg (mono_get_corlib (), "System", "CannotUnloadAppDomainException", msg);
664 * mono_get_exception_appdomain_unloaded
666 * Returns: a new instance of the `System.AppDomainUnloadedException`
669 mono_get_exception_appdomain_unloaded (void)
671 return mono_exception_from_name (mono_get_corlib (), "System", "AppDomainUnloadedException");
675 * mono_get_exception_bad_image_format:
676 * @msg: an informative message for the user.
678 * Returns: a new instance of the `System.BadImageFormatException`
681 mono_get_exception_bad_image_format (const char *msg)
683 return mono_exception_from_name_msg (mono_get_corlib (), "System", "BadImageFormatException", msg);
687 * mono_get_exception_bad_image_format2:
688 * @msg: an informative message for the user.
689 * @fname: The full name of the file with the invalid image.
691 * Returns: a new instance of the `System.BadImageFormatException`
694 mono_get_exception_bad_image_format2 (const char *msg, MonoString *fname)
696 MonoString *s = msg ? mono_string_new (mono_domain_get (), msg) : NULL;
698 return mono_exception_from_name_two_strings (
699 mono_get_corlib (), "System", "BadImageFormatException", s, fname);
703 * mono_get_exception_stack_overflow:
705 * Returns: a new instance of the `System.StackOverflowException`
708 mono_get_exception_stack_overflow (void)
710 return mono_exception_from_name (mono_get_corlib (), "System", "StackOverflowException");
714 * mono_get_exception_out_of_memory:
716 * Returns: a new instance of the `System.OutOfMemoryException`
719 mono_get_exception_out_of_memory (void)
721 return mono_exception_from_name (mono_get_corlib (), "System", "OutOfMemoryException");
725 * mono_get_exception_field_access:
727 * Returns: a new instance of the `System.FieldAccessException`
730 mono_get_exception_field_access (void)
732 return mono_exception_from_name (mono_get_corlib (), "System", "FieldAccessException");
736 * mono_get_exception_field_access2:
737 * @msg: an informative message for the user.
739 * Returns: a new instance of the `System.FieldAccessException`
742 mono_get_exception_field_access_msg (const char *msg)
744 return mono_exception_from_name_msg (mono_get_corlib (), "System", "FieldAccessException", msg);
748 * mono_get_exception_method_access:
750 * Returns: a new instance of the `System.MethodAccessException`
753 mono_get_exception_method_access (void)
755 return mono_exception_from_name (mono_get_corlib (), "System", "MethodAccessException");
759 * mono_get_exception_method_access2:
760 * @msg: an informative message for the user.
762 * Returns: a new instance of the `System.MethodAccessException`
765 mono_get_exception_method_access_msg (const char *msg)
767 return mono_exception_from_name_msg (mono_get_corlib (), "System", "MethodAccessException", msg);
771 * mono_get_exception_reflection_type_load:
772 * @types: an array of types that were defined in the moduled loaded.
773 * @exceptions: an array of exceptions that were thrown during the type loading.
775 * Returns: a new instance of the `System.Reflection.ReflectionTypeLoadException`
778 mono_get_exception_reflection_type_load (MonoArray *types, MonoArray *exceptions)
781 MonoException *ret = mono_get_exception_reflection_type_load_checked (types, exceptions, &error);
782 if (is_ok (&error)) {
783 mono_error_cleanup (&error);
791 mono_get_exception_reflection_type_load_checked (MonoArray *types, MonoArray *exceptions, MonoError *error)
799 klass = mono_class_load_from_name (mono_get_corlib (), "System.Reflection", "ReflectionTypeLoadException");
801 mono_class_init (klass);
803 /* Find the Type[], Exception[] ctor */
805 while ((method = mono_class_get_methods (klass, &iter))) {
806 if (!strcmp (".ctor", mono_method_get_name (method))) {
807 MonoMethodSignature *sig = mono_method_signature (method);
809 if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_SZARRAY && sig->params [1]->type == MONO_TYPE_SZARRAY)
817 args [1] = exceptions;
819 exc = mono_object_new_checked (mono_domain_get (), klass, error);
820 mono_error_assert_ok (error);
822 mono_runtime_invoke_checked (method, exc, args, error);
823 return_val_if_nok (error, NULL);
825 return (MonoException *) exc;
829 mono_get_exception_runtime_wrapped (MonoObject *wrapped_exception)
832 MonoException *ret = mono_get_exception_runtime_wrapped_checked (wrapped_exception, &error);
833 if (!is_ok (&error)) {
834 mono_error_cleanup (&error);
842 mono_get_exception_runtime_wrapped_checked (MonoObject *wrapped_exception, MonoError *error)
847 MonoDomain *domain = mono_domain_get ();
848 gpointer params [16];
850 klass = mono_class_load_from_name (mono_get_corlib (), "System.Runtime.CompilerServices", "RuntimeWrappedException");
852 o = mono_object_new_checked (domain, klass, error);
853 mono_error_assert_ok (error);
854 g_assert (o != NULL);
856 method = mono_class_get_method_from_name (klass, ".ctor", 1);
859 params [0] = wrapped_exception;
861 mono_runtime_invoke_checked (method, o, params, error);
862 return_val_if_nok (error, NULL);
864 return (MonoException *)o;
868 append_frame_and_continue (MonoMethod *method, gpointer ip, size_t native_offset, gboolean managed, gpointer user_data)
870 MonoDomain *domain = mono_domain_get ();
871 GString *text = (GString*)user_data;
874 char *msg = mono_debug_print_stack_frame (method, native_offset, domain);
875 g_string_append_printf (text, "%s\n", msg);
878 g_string_append_printf (text, "<unknown native frame 0x%x>\n", ip);
885 mono_exception_get_managed_backtrace (MonoException *exc)
889 text = g_string_new_len (NULL, 20);
891 if (!mono_get_eh_callbacks ()->mono_exception_walk_trace (exc, append_frame_and_continue, text))
892 g_string_append (text, "managed backtrace not available\n");
894 return g_string_free (text, FALSE);
898 mono_exception_get_native_backtrace (MonoException *exc)
900 #ifdef HAVE_BACKTRACE_SYMBOLS
902 MonoArray *arr = exc->native_trace_ips;
908 return g_strdup ("");
909 domain = mono_domain_get ();
910 len = mono_array_length (arr);
911 text = g_string_new_len (NULL, len * 20);
912 messages = backtrace_symbols (mono_array_addr (arr, gpointer, 0), len);
915 for (i = 0; i < len; ++i) {
916 gpointer ip = mono_array_get (arr, gpointer, i);
917 MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), (char *)ip);
919 char *msg = mono_debug_print_stack_frame (mono_jit_info_get_method (ji), (char*)ip - (char*)ji->code_start, domain);
920 g_string_append_printf (text, "%s\n", msg);
923 g_string_append_printf (text, "%s\n", messages [i]);
928 return g_string_free (text, FALSE);
930 return g_strdup ("");
935 ves_icall_Mono_Runtime_GetNativeStackTrace (MonoException *exc)
940 mono_raise_exception (mono_get_exception_argument_null ("exception"));
942 trace = mono_exception_get_native_backtrace (exc);
943 res = mono_string_new (mono_domain_get (), trace);
949 * mono_error_raise_exception:
950 * @target_error: the exception to raise
952 * Raises the exception of @target_error.
953 * Does nothing if @target_error has a success error code.
954 * Aborts in case of a double fault. This happens when it can't recover from an error caused by trying
955 * to construct the first exception object.
956 * The error object @target_error is cleaned up.
959 mono_error_raise_exception (MonoError *target_error)
961 MonoException *ex = mono_error_convert_to_exception (target_error);
963 mono_raise_exception (ex);
967 mono_error_set_pending_exception (MonoError *error)
969 MonoException *ex = mono_error_convert_to_exception (error);
971 mono_set_pending_exception (ex);