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)
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <mono/metadata/exception.h>
17 #include <mono/metadata/exception-internals.h>
19 #include <mono/metadata/object-internals.h>
20 #include <mono/metadata/metadata-internals.h>
21 #include <mono/metadata/appdomain.h>
22 #include <mono/metadata/mono-debug.h>
23 #include <mono/utils/mono-error-internals.h>
26 #ifdef HAVE_EXECINFO_H
31 * mono_exception_from_name:
32 * @image: the Mono image where to look for the class
33 * @name_space: the namespace for the class
36 * Creates an exception of the given namespace/name class in the
39 * Returns: the initialized exception instance.
42 mono_exception_from_name (MonoImage *image, const char *name_space,
45 return mono_exception_from_name_domain (mono_domain_get (), image, name_space, name);
49 * mono_exception_from_name_domain:
50 * @domain: Domain where the return object will be created.
51 * @image: the Mono image where to look for the class
52 * @name_space: the namespace for the class
55 * Creates an exception object of the given namespace/name class on
58 * Returns: the initialized exception instance.
61 mono_exception_from_name_domain (MonoDomain *domain, MonoImage *image,
62 const char* name_space, const char *name)
67 MonoDomain *caller_domain = mono_domain_get ();
69 klass = mono_class_load_from_name (image, name_space, name);
71 o = mono_object_new_checked (domain, klass, &error);
72 mono_error_assert_ok (&error);
74 if (domain != caller_domain)
75 mono_domain_set_internal (domain);
76 mono_runtime_object_init_checked (o, &error);
77 mono_error_assert_ok (&error);
79 if (domain != caller_domain)
80 mono_domain_set_internal (caller_domain);
82 return (MonoException *)o;
87 * mono_exception_from_token:
88 * @image: the Mono image where to look for the class
89 * @token: The type token of the class
91 * Creates an exception of the type given by @token.
93 * Returns: the initialized exception instance.
96 mono_exception_from_token (MonoImage *image, guint32 token)
102 klass = mono_class_get_checked (image, token, &error);
103 mono_error_assert_ok (&error);
105 o = mono_object_new_checked (mono_domain_get (), klass, &error);
106 mono_error_assert_ok (&error);
108 mono_runtime_object_init_checked (o, &error);
109 mono_error_assert_ok (&error);
111 return (MonoException *)o;
114 static MonoException *
115 create_exception_two_strings (MonoClass *klass, MonoString *a1, MonoString *a2, MonoError *error)
117 MonoDomain *domain = mono_domain_get ();
118 MonoMethod *method = NULL;
128 o = mono_object_new_checked (domain, klass, error);
129 mono_error_assert_ok (error);
132 while ((m = mono_class_get_methods (klass, &iter))) {
133 MonoMethodSignature *sig;
135 if (strcmp (".ctor", mono_method_get_name (m)))
137 sig = mono_method_signature (m);
138 if (sig->param_count != count)
141 if (sig->params [0]->type != MONO_TYPE_STRING)
143 if (count == 2 && sig->params [1]->type != MONO_TYPE_STRING)
152 mono_runtime_invoke_checked (method, o, args, error);
153 return_val_if_nok (error, NULL);
155 return (MonoException *) o;
159 * mono_exception_from_name_two_strings:
160 * @image: the Mono image where to look for the class
161 * @name_space: the namespace for the class
163 * @a1: first string argument to pass
164 * @a2: second string argument to pass
166 * Creates an exception from a constructor that takes two string
169 * Returns: the initialized exception instance.
172 mono_exception_from_name_two_strings (MonoImage *image, const char *name_space,
173 const char *name, MonoString *a1, MonoString *a2)
179 klass = mono_class_load_from_name (image, name_space, name);
181 ret = create_exception_two_strings (klass, a1, a2, &error);
182 mono_error_raise_exception (&error); /* FIXME don't raise here */
188 * mono_exception_from_name_msg:
189 * @image: the Mono image where to look for the class
190 * @name_space: the namespace for the class
192 * @msg: the message to embed inside the exception
194 * Creates an exception and initializes its message field.
196 * Returns: the initialized exception instance.
199 mono_exception_from_name_msg (MonoImage *image, const char *name_space,
200 const char *name, const char *msg)
204 ex = mono_exception_from_name (image, name_space, name);
207 MONO_OBJECT_SETREF (ex, message, mono_string_new (mono_object_get_domain ((MonoObject*)ex), msg));
213 * mono_exception_from_token_two_strings:
215 * Same as mono_exception_from_name_two_strings, but lookup the exception class using
219 mono_exception_from_token_two_strings (MonoImage *image, guint32 token,
220 MonoString *a1, MonoString *a2)
226 klass = mono_class_get_checked (image, token, &error);
227 mono_error_assert_ok (&error); /* FIXME handle the error. */
229 ret = create_exception_two_strings (klass, a1, a2, &error);
230 mono_error_raise_exception (&error); /* FIXME don't raise here */
236 * mono_get_exception_divide_by_zero:
238 * Returns: a new instance of the `System.DivideByZeroException`
241 mono_get_exception_divide_by_zero ()
243 return mono_exception_from_name (mono_get_corlib (), "System",
244 "DivideByZeroException");
248 * mono_get_exception_security:
250 * Returns: a new instance of the `System.Security.SecurityException`
253 mono_get_exception_security ()
255 return mono_exception_from_name (mono_get_corlib (), "System.Security",
256 "SecurityException");
260 * mono_get_exception_thread_abort:
262 * Returns: a new instance of the `System.Threading.ThreadAbortException`
265 mono_get_exception_thread_abort ()
267 return mono_exception_from_name (mono_get_corlib (), "System.Threading",
268 "ThreadAbortException");
272 * mono_get_exception_thread_interrupted:
274 * Returns: a new instance of the `System.Threading.ThreadInterruptedException`
277 mono_get_exception_thread_interrupted ()
279 return mono_exception_from_name (mono_get_corlib (), "System.Threading",
280 "ThreadInterruptedException");
284 * mono_get_exception_arithmetic:
286 * Returns: a new instance of the `System.ArithmeticException`
289 mono_get_exception_arithmetic ()
291 return mono_exception_from_name (mono_get_corlib (), "System",
292 "ArithmeticException");
296 * mono_get_exception_overflow:
298 * Returns: a new instance of the `System.OverflowException`
301 mono_get_exception_overflow ()
303 return mono_exception_from_name (mono_get_corlib (), "System",
304 "OverflowException");
308 * mono_get_exception_null_reference:
310 * Returns: a new instance of the `System.NullReferenceException`
313 mono_get_exception_null_reference ()
315 return mono_exception_from_name (mono_get_corlib (), "System",
316 "NullReferenceException");
320 * mono_get_exception_execution_engine:
321 * @msg: the message to pass to the user
323 * Returns: a new instance of the `System.ExecutionEngineException`
326 mono_get_exception_execution_engine (const char *msg)
328 return mono_exception_from_name_msg (mono_get_corlib (), "System", "ExecutionEngineException", msg);
332 * mono_get_exception_serialization:
333 * @msg: the message to pass to the user
335 * Returns: a new instance of the `System.Runtime.Serialization.SerializationException`
338 mono_get_exception_serialization (const char *msg)
340 return mono_exception_from_name_msg (mono_get_corlib (), "System.Runtime.Serialization", "SerializationException", msg);
344 * mono_get_exception_invalid_cast:
346 * Returns: a new instance of the `System.InvalidCastException`
349 mono_get_exception_invalid_cast ()
351 return mono_exception_from_name (mono_get_corlib (), "System", "InvalidCastException");
355 * mono_get_exception_invalid_operation:
356 * @msg: the message to pass to the user
358 * Returns: a new instance of the `System.InvalidOperationException`
361 mono_get_exception_invalid_operation (const char *msg)
363 return mono_exception_from_name_msg (mono_get_corlib (), "System",
364 "InvalidOperationException", msg);
368 * mono_get_exception_index_out_of_range:
370 * Returns: a new instance of the `System.IndexOutOfRangeException`
373 mono_get_exception_index_out_of_range ()
375 return mono_exception_from_name (mono_get_corlib (), "System",
376 "IndexOutOfRangeException");
380 * mono_get_exception_array_type_mismatch:
382 * Returns: a new instance of the `System.ArrayTypeMismatchException`
385 mono_get_exception_array_type_mismatch ()
387 return mono_exception_from_name (mono_get_corlib (), "System",
388 "ArrayTypeMismatchException");
392 * mono_get_exception_type_load:
393 * @class_name: the name of the class that could not be loaded
394 * @assembly_name: the assembly where the class was looked up.
396 * Returns: a new instance of the `System.TypeLoadException`
399 mono_get_exception_type_load (MonoString *class_name, char *assembly_name)
401 MonoString *s = assembly_name ? mono_string_new (mono_domain_get (), assembly_name) : mono_string_new (mono_domain_get (), "");
403 return mono_exception_from_name_two_strings (mono_get_corlib (), "System",
404 "TypeLoadException", class_name, s);
408 * mono_get_exception_not_implemented:
409 * @msg: the message to pass to the user
411 * Returns: a new instance of the `System.NotImplementedException`
414 mono_get_exception_not_implemented (const char *msg)
416 return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotImplementedException", msg);
420 * mono_get_exception_not_supported:
421 * @msg: the message to pass to the user
423 * Returns: a new instance of the `System.NotSupportedException`
426 mono_get_exception_not_supported (const char *msg)
428 return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotSupportedException", msg);
432 * mono_get_exception_missing_method:
433 * @class_name: the class where the lookup was performed.
434 * @member_name: the name of the missing method.
436 * Returns: a new instance of the `System.MissingMethodException`
439 mono_get_exception_missing_method (const char *class_name, const char *member_name)
441 MonoString *s1 = mono_string_new (mono_domain_get (), class_name);
442 MonoString *s2 = mono_string_new (mono_domain_get (), member_name);
444 return mono_exception_from_name_two_strings (mono_get_corlib (), "System",
445 "MissingMethodException", s1, s2);
449 * mono_get_exception_missing_field:
450 * @class_name: the class where the lookup was performed
451 * @member_name: the name of the missing method.
453 * Returns: a new instance of the `System.MissingFieldException`
456 mono_get_exception_missing_field (const char *class_name, const char *member_name)
458 MonoString *s1 = mono_string_new (mono_domain_get (), class_name);
459 MonoString *s2 = mono_string_new (mono_domain_get (), member_name);
461 return mono_exception_from_name_two_strings (mono_get_corlib (), "System",
462 "MissingFieldException", s1, s2);
466 * mono_get_exception_argument_null:
467 * @arg: the name of the argument that is null
469 * Returns: a new instance of the `System.ArgumentNullException`
472 mono_get_exception_argument_null (const char *arg)
476 ex = mono_exception_from_name (
477 mono_get_corlib (), "System", "ArgumentNullException");
480 MonoArgumentException *argex = (MonoArgumentException *)ex;
481 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
488 * mono_get_exception_argument:
489 * @arg: the name of the invalid argument.
491 * Returns: a new instance of the `System.ArgumentException`
494 mono_get_exception_argument (const char *arg, const char *msg)
498 ex = mono_exception_from_name_msg (
499 mono_get_corlib (), "System", "ArgumentException", msg);
502 MonoArgumentException *argex = (MonoArgumentException *)ex;
503 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
510 * mono_get_exception_argument_out_of_range:
511 * @arg: the name of the out of range argument.
513 * Returns: a new instance of the `System.ArgumentOutOfRangeException`
516 mono_get_exception_argument_out_of_range (const char *arg)
520 ex = mono_exception_from_name (
521 mono_get_corlib (), "System", "ArgumentOutOfRangeException");
524 MonoArgumentException *argex = (MonoArgumentException *)ex;
525 MONO_OBJECT_SETREF (argex, param_name, mono_string_new (mono_object_get_domain ((MonoObject*)ex), arg));
532 * mono_get_exception_thread_state:
533 * @msg: the message to present to the user
535 * Returns: a new instance of the `System.Threading.ThreadStateException`
538 mono_get_exception_thread_state (const char *msg)
540 return mono_exception_from_name_msg (
541 mono_get_corlib (), "System.Threading", "ThreadStateException", msg);
545 * mono_get_exception_io:
546 * @msg: the message to present to the user
548 * Returns: a new instance of the `System.IO.IOException`
551 mono_get_exception_io (const char *msg)
553 return mono_exception_from_name_msg (
554 mono_get_corlib (), "System.IO", "IOException", msg);
558 * mono_get_exception_file_not_found:
559 * @fname: the name of the file not found.
561 * Returns: a new instance of the `System.IO.FileNotFoundException`
564 mono_get_exception_file_not_found (MonoString *fname)
566 return mono_exception_from_name_two_strings (
567 mono_get_corlib (), "System.IO", "FileNotFoundException", fname, fname);
571 * mono_get_exception_file_not_found2:
572 * @msg: an informative message for the user.
573 * @fname: the name of the file not found.
575 * Returns: a new instance of the `System.IO.FileNotFoundException`
578 mono_get_exception_file_not_found2 (const char *msg, MonoString *fname)
580 MonoString *s = msg ? mono_string_new (mono_domain_get (), msg) : NULL;
582 return mono_exception_from_name_two_strings (
583 mono_get_corlib (), "System.IO", "FileNotFoundException", s, fname);
587 * mono_get_exception_type_initialization:
588 * @type_name: the name of the type that failed to initialize.
589 * @inner: the inner exception.
591 * Returns: a new instance of the `System.TypeInitializationException`
594 mono_get_exception_type_initialization (const gchar *type_name, MonoException *inner)
597 MonoException *ret = mono_get_exception_type_initialization_checked (type_name, inner, &error);
598 if (!is_ok (&error)) {
599 mono_error_cleanup (&error);
607 mono_get_exception_type_initialization_checked (const gchar *type_name, MonoException *inner, MonoError *error)
615 klass = mono_class_load_from_name (mono_get_corlib (), "System", "TypeInitializationException");
617 mono_class_init (klass);
620 while ((method = mono_class_get_methods (klass, &iter))) {
621 if (!strcmp (".ctor", mono_method_get_name (method))) {
622 MonoMethodSignature *sig = mono_method_signature (method);
624 if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_STRING && mono_class_from_mono_type (sig->params [1]) == mono_defaults.exception_class)
631 args [0] = mono_string_new (mono_domain_get (), type_name);
634 exc = mono_object_new_checked (mono_domain_get (), klass, error);
635 mono_error_assert_ok (error);
637 mono_runtime_invoke_checked (method, exc, args, error);
638 return_val_if_nok (error, NULL);
640 return (MonoException *) exc;
644 * mono_get_exception_synchronization_lock:
645 * @inner: the inner exception.
647 * Returns: a new instance of the `System.SynchronizationLockException`
650 mono_get_exception_synchronization_lock (const char *msg)
652 return mono_exception_from_name_msg (mono_get_corlib (), "System.Threading", "SynchronizationLockException", msg);
656 * mono_get_exception_cannot_unload_appdomain:
657 * @inner: the inner exception.
659 * Returns: a new instance of the `System.CannotUnloadAppDomainException`
662 mono_get_exception_cannot_unload_appdomain (const char *msg)
664 return mono_exception_from_name_msg (mono_get_corlib (), "System", "CannotUnloadAppDomainException", msg);
668 * mono_get_exception_appdomain_unloaded
670 * Returns: a new instance of the `System.AppDomainUnloadedException`
673 mono_get_exception_appdomain_unloaded (void)
675 return mono_exception_from_name (mono_get_corlib (), "System", "AppDomainUnloadedException");
679 * mono_get_exception_bad_image_format:
680 * @msg: an informative message for the user.
682 * Returns: a new instance of the `System.BadImageFormatException`
685 mono_get_exception_bad_image_format (const char *msg)
687 return mono_exception_from_name_msg (mono_get_corlib (), "System", "BadImageFormatException", msg);
691 * mono_get_exception_bad_image_format2:
692 * @msg: an informative message for the user.
693 * @fname: The full name of the file with the invalid image.
695 * Returns: a new instance of the `System.BadImageFormatException`
698 mono_get_exception_bad_image_format2 (const char *msg, MonoString *fname)
700 MonoString *s = msg ? mono_string_new (mono_domain_get (), msg) : NULL;
702 return mono_exception_from_name_two_strings (
703 mono_get_corlib (), "System", "BadImageFormatException", s, fname);
707 * mono_get_exception_stack_overflow:
709 * Returns: a new instance of the `System.StackOverflowException`
712 mono_get_exception_stack_overflow (void)
714 return mono_exception_from_name (mono_get_corlib (), "System", "StackOverflowException");
718 * mono_get_exception_out_of_memory:
720 * Returns: a new instance of the `System.OutOfMemoryException`
723 mono_get_exception_out_of_memory (void)
725 return mono_exception_from_name (mono_get_corlib (), "System", "OutOfMemoryException");
729 * mono_get_exception_field_access:
731 * Returns: a new instance of the `System.FieldAccessException`
734 mono_get_exception_field_access (void)
736 return mono_exception_from_name (mono_get_corlib (), "System", "FieldAccessException");
740 * mono_get_exception_field_access2:
741 * @msg: an informative message for the user.
743 * Returns: a new instance of the `System.FieldAccessException`
746 mono_get_exception_field_access_msg (const char *msg)
748 return mono_exception_from_name_msg (mono_get_corlib (), "System", "FieldAccessException", msg);
752 * mono_get_exception_method_access:
754 * Returns: a new instance of the `System.MethodAccessException`
757 mono_get_exception_method_access (void)
759 return mono_exception_from_name (mono_get_corlib (), "System", "MethodAccessException");
763 * mono_get_exception_method_access2:
764 * @msg: an informative message for the user.
766 * Returns: a new instance of the `System.MethodAccessException`
769 mono_get_exception_method_access_msg (const char *msg)
771 return mono_exception_from_name_msg (mono_get_corlib (), "System", "MethodAccessException", msg);
775 * mono_get_exception_reflection_type_load:
776 * @types: an array of types that were defined in the moduled loaded.
777 * @exceptions: an array of exceptions that were thrown during the type loading.
779 * Returns: a new instance of the `System.Reflection.ReflectionTypeLoadException`
782 mono_get_exception_reflection_type_load (MonoArray *types, MonoArray *exceptions)
785 MonoException *ret = mono_get_exception_reflection_type_load_checked (types, exceptions, &error);
786 if (is_ok (&error)) {
787 mono_error_cleanup (&error);
795 mono_get_exception_reflection_type_load_checked (MonoArray *types, MonoArray *exceptions, MonoError *error)
803 klass = mono_class_load_from_name (mono_get_corlib (), "System.Reflection", "ReflectionTypeLoadException");
805 mono_class_init (klass);
807 /* Find the Type[], Exception[] ctor */
809 while ((method = mono_class_get_methods (klass, &iter))) {
810 if (!strcmp (".ctor", mono_method_get_name (method))) {
811 MonoMethodSignature *sig = mono_method_signature (method);
813 if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_SZARRAY && sig->params [1]->type == MONO_TYPE_SZARRAY)
821 args [1] = exceptions;
823 exc = mono_object_new_checked (mono_domain_get (), klass, error);
824 mono_error_assert_ok (error);
826 mono_runtime_invoke_checked (method, exc, args, error);
827 return_val_if_nok (error, NULL);
829 return (MonoException *) exc;
833 mono_get_exception_runtime_wrapped (MonoObject *wrapped_exception)
836 MonoException *ret = mono_get_exception_runtime_wrapped_checked (wrapped_exception, &error);
837 if (!is_ok (&error)) {
838 mono_error_cleanup (&error);
846 mono_get_exception_runtime_wrapped_checked (MonoObject *wrapped_exception, MonoError *error)
851 MonoDomain *domain = mono_domain_get ();
852 gpointer params [16];
854 klass = mono_class_load_from_name (mono_get_corlib (), "System.Runtime.CompilerServices", "RuntimeWrappedException");
856 o = mono_object_new_checked (domain, klass, error);
857 mono_error_assert_ok (error);
858 g_assert (o != NULL);
860 method = mono_class_get_method_from_name (klass, ".ctor", 1);
863 params [0] = wrapped_exception;
865 mono_runtime_invoke_checked (method, o, params, error);
866 return_val_if_nok (error, NULL);
868 return (MonoException *)o;
872 append_frame_and_continue (MonoMethod *method, gpointer ip, size_t native_offset, gboolean managed, gpointer user_data)
874 MonoDomain *domain = mono_domain_get ();
875 GString *text = (GString*)user_data;
878 char *msg = mono_debug_print_stack_frame (method, native_offset, domain);
879 g_string_append_printf (text, "%s\n", msg);
882 g_string_append_printf (text, "<unknown native frame 0x%x>\n", ip);
889 mono_exception_get_managed_backtrace (MonoException *exc)
893 text = g_string_new_len (NULL, 20);
895 if (!mono_get_eh_callbacks ()->mono_exception_walk_trace (exc, append_frame_and_continue, text))
896 g_string_append (text, "managed backtrace not available\n");
898 return g_string_free (text, FALSE);
902 mono_exception_get_native_backtrace (MonoException *exc)
904 #ifdef HAVE_BACKTRACE_SYMBOLS
906 MonoArray *arr = exc->native_trace_ips;
912 return g_strdup ("");
913 domain = mono_domain_get ();
914 len = mono_array_length (arr);
915 text = g_string_new_len (NULL, len * 20);
916 messages = backtrace_symbols (mono_array_addr (arr, gpointer, 0), len);
919 for (i = 0; i < len; ++i) {
920 gpointer ip = mono_array_get (arr, gpointer, i);
921 MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), (char *)ip);
923 char *msg = mono_debug_print_stack_frame (mono_jit_info_get_method (ji), (char*)ip - (char*)ji->code_start, domain);
924 g_string_append_printf (text, "%s\n", msg);
927 g_string_append_printf (text, "%s\n", messages [i]);
932 return g_string_free (text, FALSE);
934 return g_strdup ("");
939 ves_icall_Mono_Runtime_GetNativeStackTrace (MonoException *exc)
944 mono_raise_exception (mono_get_exception_argument_null ("exception"));
946 trace = mono_exception_get_native_backtrace (exc);
947 res = mono_string_new (mono_domain_get (), trace);
953 * mono_error_raise_exception:
954 * @target_error: the exception to raise
956 * Raises the exception of @target_error.
957 * Does nothing if @target_error has a success error code.
958 * Aborts in case of a double fault. This happens when it can't recover from an error caused by trying
959 * to construct the first exception object.
960 * The error object @target_error is cleaned up.
963 mono_error_raise_exception (MonoError *target_error)
965 MonoException *ex = mono_error_convert_to_exception (target_error);
967 mono_raise_exception (ex);
971 * mono_error_set_pending_exception:
975 * If @error is set, convert it to an exception and set the pending exception for the current icall.
976 * Returns TRUE if @error was set, or FALSE otherwise, so that you can write:
977 * if (mono_error_set_pending_exception (error)) {
978 * { ... cleanup code ... }
983 mono_error_set_pending_exception (MonoError *error)
985 MonoException *ex = mono_error_convert_to_exception (error);
987 mono_set_pending_exception (ex);