2 * loader.c: Image Loader
5 * Paolo Molaro (lupus@ximian.com)
6 * Miguel de Icaza (miguel@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 * This file is used by the interpreter and the JIT engine to locate
14 * assemblies. Used to load AssemblyRef and later to resolve various
18 * This should keep track of the assembly versions that we are loading.
26 #include <mono/metadata/metadata.h>
27 #include <mono/metadata/image.h>
28 #include <mono/metadata/assembly.h>
29 #include <mono/metadata/tokentype.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/metadata-internals.h>
32 #include <mono/metadata/loader.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/debug-helpers.h>
35 #include <mono/metadata/reflection.h>
36 #include <mono/metadata/profiler.h>
37 #include <mono/metadata/profiler-private.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/marshal.h>
40 #include <mono/metadata/lock-tracer.h>
41 #include <mono/metadata/verify-internals.h>
42 #include <mono/utils/mono-logger-internal.h>
43 #include <mono/utils/mono-dl.h>
44 #include <mono/utils/mono-membar.h>
45 #include <mono/utils/mono-counters.h>
46 #include <mono/utils/mono-error-internals.h>
47 #include <mono/utils/mono-tls.h>
49 MonoDefaults mono_defaults;
52 * This lock protects the hash tables inside MonoImage used by the metadata
53 * loading functions in class.c and loader.c.
55 * See domain-internals.h for locking policy in combination with the
58 static mono_mutex_t loader_mutex, global_loader_data_mutex;
59 static gboolean loader_lock_inited;
62 static guint32 inflated_signatures_size;
63 static guint32 memberref_sig_cache_size;
64 static guint32 methods_size;
65 static guint32 signatures_size;
68 * This TLS variable contains the last type load error encountered by the loader.
70 MonoNativeTlsKey loader_error_thread_id;
73 * This TLS variable holds how many times the current thread has acquired the loader
76 MonoNativeTlsKey loader_lock_nest_id;
78 static void dllmap_cleanup (void);
82 global_loader_data_lock (void)
84 mono_locks_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
88 global_loader_data_unlock (void)
90 mono_locks_release (&global_loader_data_mutex, LoaderGlobalDataLock);
96 static gboolean inited;
99 mono_mutex_init_recursive (&loader_mutex);
100 mono_mutex_init_recursive (&global_loader_data_mutex);
101 loader_lock_inited = TRUE;
103 mono_native_tls_alloc (&loader_error_thread_id, NULL);
104 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
106 mono_counters_register ("Inflated signatures size",
107 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
108 mono_counters_register ("Memberref signature cache size",
109 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
110 mono_counters_register ("MonoMethod size",
111 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
112 mono_counters_register ("MonoMethodSignature size",
113 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
120 mono_loader_cleanup (void)
124 mono_native_tls_free (loader_error_thread_id);
125 mono_native_tls_free (loader_lock_nest_id);
127 mono_mutex_destroy (&loader_mutex);
128 mono_mutex_destroy (&global_loader_data_mutex);
129 loader_lock_inited = FALSE;
133 * Handling of type load errors should be done as follows:
135 * If something could not be loaded, the loader should call one of the
136 * mono_loader_set_error_XXX functions ()
137 * with the appropriate arguments, then return NULL to report the failure. The error
138 * should be propagated until it reaches code which can throw managed exceptions. At that
139 * point, an exception should be thrown based on the information returned by
140 * mono_loader_get_last_error (). Then the error should be cleared by calling
141 * mono_loader_clear_error ().
145 set_loader_error (MonoLoaderError *error)
147 mono_loader_clear_error ();
148 mono_native_tls_set_value (loader_error_thread_id, error);
152 * mono_loader_set_error_assembly_load:
154 * Set the loader error for this thread.
157 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
159 MonoLoaderError *error;
161 if (mono_loader_get_last_error ())
164 error = g_new0 (MonoLoaderError, 1);
165 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
166 error->assembly_name = g_strdup (assembly_name);
167 error->ref_only = ref_only;
170 * This is not strictly needed, but some (most) of the loader code still
171 * can't deal with load errors, and this message is more helpful than an
175 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.", assembly_name);
177 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
179 set_loader_error (error);
183 * mono_loader_set_error_type_load:
185 * Set the loader error for this thread.
188 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
190 MonoLoaderError *error;
192 if (mono_loader_get_last_error ())
195 error = g_new0 (MonoLoaderError, 1);
196 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
197 error->class_name = g_strdup (class_name);
198 error->assembly_name = g_strdup (assembly_name);
201 * This is not strictly needed, but some (most) of the loader code still
202 * can't deal with load errors, and this message is more helpful than an
205 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
207 set_loader_error (error);
211 * mono_loader_set_error_method_load:
213 * Set the loader error for this thread. MEMBER_NAME should point to a string
217 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
219 MonoLoaderError *error;
221 /* FIXME: Store the signature as well */
222 if (mono_loader_get_last_error ())
225 error = g_new0 (MonoLoaderError, 1);
226 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
227 error->class_name = g_strdup (class_name);
228 error->member_name = member_name;
230 set_loader_error (error);
234 * mono_loader_set_error_field_load:
236 * Set the loader error for this thread. MEMBER_NAME should point to a string
240 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
242 MonoLoaderError *error;
244 /* FIXME: Store the signature as well */
245 if (mono_loader_get_last_error ())
248 error = g_new0 (MonoLoaderError, 1);
249 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
250 error->klass = klass;
251 error->member_name = member_name;
253 set_loader_error (error);
257 * mono_loader_set_error_bad_image:
259 * Set the loader error for this thread.
262 mono_loader_set_error_bad_image (char *msg)
264 MonoLoaderError *error;
266 if (mono_loader_get_last_error ())
269 error = g_new0 (MonoLoaderError, 1);
270 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
273 set_loader_error (error);
278 * mono_loader_get_last_error:
280 * Returns information about the last type load exception encountered by the loader, or
281 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
284 mono_loader_get_last_error (void)
286 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
290 * mono_loader_clear_error:
292 * Disposes any loader error messages on this thread
295 mono_loader_clear_error (void)
297 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
300 g_free (ex->class_name);
301 g_free (ex->assembly_name);
305 mono_native_tls_set_value (loader_error_thread_id, NULL);
310 * mono_loader_error_prepare_exception:
311 * @error: The MonoLoaderError to turn into an exception
313 * This turns a MonoLoaderError into an exception that can be thrown
314 * and resets the Mono Loader Error state during this process.
318 mono_loader_error_prepare_exception (MonoLoaderError *error)
320 MonoException *ex = NULL;
322 switch (error->exception_type) {
323 case MONO_EXCEPTION_TYPE_LOAD: {
324 char *cname = g_strdup (error->class_name);
325 char *aname = g_strdup (error->assembly_name);
326 MonoString *class_name;
328 mono_loader_clear_error ();
330 class_name = mono_string_new (mono_domain_get (), cname);
332 ex = mono_get_exception_type_load (class_name, aname);
337 case MONO_EXCEPTION_MISSING_METHOD: {
338 char *cname = g_strdup (error->class_name);
339 char *aname = g_strdup (error->member_name);
341 mono_loader_clear_error ();
342 ex = mono_get_exception_missing_method (cname, aname);
348 case MONO_EXCEPTION_MISSING_FIELD: {
350 char *cmembername = g_strdup (error->member_name);
352 class_name = mono_type_get_full_name (error->klass);
354 class_name = g_strdup ("");
356 mono_loader_clear_error ();
358 ex = mono_get_exception_missing_field (class_name, cmembername);
360 g_free (cmembername);
364 case MONO_EXCEPTION_FILE_NOT_FOUND: {
369 msg = g_strdup_printf ("Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.", error->assembly_name);
371 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
372 filename = g_strdup (error->assembly_name);
373 /* Has to call this before calling anything which might call mono_class_init () */
374 mono_loader_clear_error ();
375 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
381 case MONO_EXCEPTION_BAD_IMAGE: {
382 char *msg = g_strdup (error->msg);
383 mono_loader_clear_error ();
384 ex = mono_get_exception_bad_image_format (msg);
390 g_assert_not_reached ();
397 * find_cached_memberref_sig:
399 * Return a cached copy of the memberref signature identified by SIG_IDX.
400 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
401 * A cache is needed since the type/signature parsing routines allocate everything
402 * from a mempool, so without a cache, multiple requests for the same signature would
403 * lead to unbounded memory growth. For normal methods/fields this is not a problem
404 * since the resulting methods/fields are cached, but inflated methods/fields cannot
406 * LOCKING: Acquires the loader lock.
409 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
413 mono_image_lock (image);
414 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
415 mono_image_unlock (image);
421 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
425 mono_image_lock (image);
426 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
428 /* Somebody got in before us */
432 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
433 /* An approximation based on glib 2.18 */
434 memberref_sig_cache_size += sizeof (gpointer) * 4;
436 mono_image_unlock (image);
441 static MonoClassField*
442 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
443 MonoGenericContext *context, MonoError *error)
445 MonoClass *klass = NULL;
446 MonoClassField *field;
447 MonoTableInfo *tables = image->tables;
450 guint32 nindex, class, class_table;
453 guint32 idx = mono_metadata_token_index (token);
455 mono_error_init (error);
457 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
458 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
459 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
461 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
463 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
464 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class, token);
469 case MONO_MEMBERREF_PARENT_TYPEDEF:
470 class_table = MONO_TOKEN_TYPE_DEF;
471 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
473 case MONO_MEMBERREF_PARENT_TYPEREF:
474 class_table = MONO_TOKEN_TYPE_REF;
475 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
477 case MONO_MEMBERREF_PARENT_TYPESPEC:
478 class_table = MONO_TOKEN_TYPE_SPEC;
479 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
482 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class, token);
488 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
489 mono_metadata_decode_blob_size (ptr, &ptr);
490 /* we may want to check the signature here... */
493 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class, fname, token);
497 /* FIXME: This needs a cache, especially for generic instances, since
498 * mono_metadata_parse_type () allocates everything from a mempool.
500 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
502 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
503 if (sig_type == NULL) {
504 mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x", fname, token);
507 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
510 mono_class_init (klass); /*FIXME is this really necessary?*/
513 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
516 g_assert (!mono_loader_get_last_error ());
517 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
524 * mono_field_from_token:
525 * @deprecated use the _checked variant
528 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
531 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
532 g_assert (!mono_loader_get_last_error ());
533 if (!mono_error_ok (&error)) {
534 mono_loader_set_error_from_mono_error (&error);
535 mono_error_cleanup (&error);
541 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
545 MonoClassField *field;
547 mono_error_init (error);
549 if (image_is_dynamic (image)) {
550 MonoClassField *result;
551 MonoClass *handle_class;
554 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
555 // This checks the memberref type as well
556 if (!result || handle_class != mono_defaults.fieldhandle_class) {
557 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
560 *retklass = result->parent;
564 if ((field = mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
565 *retklass = field->parent;
569 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
570 field = field_from_memberref (image, token, retklass, context, error);
571 g_assert (!mono_loader_get_last_error ());
573 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
575 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
578 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
585 field = mono_class_get_field (k, token);
587 if (mono_loader_get_last_error ())
588 mono_error_set_from_loader_error (error);
590 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
594 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
595 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
597 g_assert (!mono_loader_get_last_error ());
602 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
606 if (sig1->hasthis != sig2->hasthis ||
607 sig1->sentinelpos != sig2->sentinelpos)
610 for (i = 0; i < sig1->sentinelpos; i++) {
611 MonoType *p1 = sig1->params[i];
612 MonoType *p2 = sig2->params[i];
614 /*if (p1->attrs != p2->attrs)
617 if (!mono_metadata_type_equal (p1, p2))
621 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
627 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
628 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
632 /* Search directly in the metadata to avoid calling setup_methods () */
633 mono_error_init (error);
635 /* FIXME: !from_class->generic_class condition causes test failures. */
636 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
637 for (i = 0; i < klass->method.count; ++i) {
638 guint32 cols [MONO_METHOD_SIZE];
641 MonoMethodSignature *other_sig;
643 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
645 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
647 if (!((fqname && !strcmp (m_name, fqname)) ||
648 (qname && !strcmp (m_name, qname)) ||
649 (name && !strcmp (m_name, name))))
652 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
653 if (!mono_error_ok (error)) //bail out if we hit a loader error
656 other_sig = mono_method_signature_checked (method, error);
657 if (!mono_error_ok (error)) //bail out if we hit a loader error
659 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
665 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
667 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
668 See mono/tests/generic-type-load-exception.2.il
669 FIXME we should better report this error to the caller
671 if (!klass->methods || klass->exception_type) {
672 mono_error_set_type_load_class (error, klass, "Could not find method due to a type load error"); //FIXME get the error from the class
676 for (i = 0; i < klass->method.count; ++i) {
677 MonoMethod *m = klass->methods [i];
678 MonoMethodSignature *msig;
680 /* We must cope with failing to load some of the types. */
684 if (!((fqname && !strcmp (m->name, fqname)) ||
685 (qname && !strcmp (m->name, qname)) ||
686 (name && !strcmp (m->name, name))))
688 msig = mono_method_signature_checked (m, error);
689 if (!mono_error_ok (error)) //bail out if we hit a loader error
695 if (sig->call_convention == MONO_CALL_VARARG) {
696 if (mono_metadata_signature_vararg_match (sig, msig))
699 if (mono_metadata_signature_equal (sig, msig))
704 if (i < klass->method.count)
705 return mono_class_get_method_by_index (from_class, i);
710 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
713 char *qname, *fqname, *class_name;
714 gboolean is_interface;
715 MonoMethod *result = NULL;
716 MonoClass *initial_class = in_class;
718 mono_error_init (error);
719 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
722 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
724 qname = g_strconcat (class_name, ".", name, NULL);
725 if (ic->name_space && ic->name_space [0])
726 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
730 class_name = qname = fqname = NULL;
733 g_assert (from_class);
734 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
735 if (result || !mono_error_ok (error))
738 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
742 * This happens when we fail to lazily load the interfaces of one of the types.
743 * On such case we can't just bail out since user code depends on us trying harder.
745 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
746 in_class = in_class->parent;
747 from_class = from_class->parent;
751 for (i = 0; i < in_class->interface_offsets_count; i++) {
752 MonoClass *in_ic = in_class->interfaces_packed [i];
753 MonoClass *from_ic = from_class->interfaces_packed [i];
754 char *ic_qname, *ic_fqname, *ic_class_name;
756 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
757 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
758 if (in_ic->name_space && in_ic->name_space [0])
759 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
763 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
764 g_free (ic_class_name);
767 if (result || !mono_error_ok (error))
771 in_class = in_class->parent;
772 from_class = from_class->parent;
774 g_assert (!in_class == !from_class);
777 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
779 //we did not find the method
780 if (!result && mono_error_ok (error)) {
781 char *desc = mono_signature_get_desc (sig, FALSE);
782 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
793 static MonoMethodSignature*
794 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
796 MonoMethodSignature *res;
800 mono_error_init (error);
804 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
805 res->param_count = sig->param_count;
806 res->sentinelpos = -1;
807 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
808 if (!mono_error_ok (error))
810 is_open = mono_class_is_open_constructed_type (res->ret);
811 for (i = 0; i < sig->param_count; ++i) {
812 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
813 if (!mono_error_ok (error))
817 is_open = mono_class_is_open_constructed_type (res->params [i]);
819 res->hasthis = sig->hasthis;
820 res->explicit_this = sig->explicit_this;
821 res->call_convention = sig->call_convention;
822 res->pinvoke = sig->pinvoke;
823 res->generic_param_count = sig->generic_param_count;
824 res->sentinelpos = sig->sentinelpos;
825 res->has_type_parameters = is_open;
826 res->is_inflated = 1;
831 mono_metadata_free_type (res->ret);
832 for (i = 0; i < sig->param_count; ++i) {
834 mono_metadata_free_type (res->params [i]);
841 * mono_inflate_generic_signature:
843 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
846 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
848 MonoMethodSignature *res, *cached;
850 res = inflate_generic_signature_checked (NULL, sig, context, error);
851 if (!mono_error_ok (error))
853 cached = mono_metadata_get_inflated_signature (res, context);
855 mono_metadata_free_inflated_signature (res);
859 static MonoMethodHeader*
860 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
862 MonoMethodHeader *res;
864 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
865 res->code = header->code;
866 res->code_size = header->code_size;
867 res->max_stack = header->max_stack;
868 res->num_clauses = header->num_clauses;
869 res->init_locals = header->init_locals;
870 res->num_locals = header->num_locals;
871 res->clauses = header->clauses;
872 for (i = 0; i < header->num_locals; ++i)
873 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
874 if (res->num_clauses) {
875 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
876 for (i = 0; i < header->num_clauses; ++i) {
877 MonoExceptionClause *clause = &res->clauses [i];
878 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
880 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
887 * token is the method_ref/def/spec token used in a call IL instruction.
890 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
893 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
895 g_assert (!mono_loader_get_last_error ());
898 g_assert (!mono_error_ok (&error));
899 mono_loader_set_error_from_mono_error (&error);
900 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
906 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
908 int table = mono_metadata_token_table (token);
909 int idx = mono_metadata_token_index (token);
911 guint32 cols [MONO_MEMBERREF_SIZE];
912 MonoMethodSignature *sig;
915 mono_error_init (error);
917 /* !table is for wrappers: we should really assign their own token to them */
918 if (!table || table == MONO_TABLE_METHOD)
919 return mono_method_signature_checked (method, error);
921 if (table == MONO_TABLE_METHODSPEC) {
922 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
923 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
926 return mono_method_signature_checked (method, error);
929 if (method->klass->generic_class)
930 return mono_method_signature_checked (method, error);
932 if (image_is_dynamic (image)) {
933 sig = mono_reflection_lookup_signature (image, method, token, error);
937 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
938 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
940 sig = find_cached_memberref_sig (image, sig_idx);
942 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
943 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
944 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
946 //FIXME include the verification error
947 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
951 ptr = mono_metadata_blob_heap (image, sig_idx);
952 mono_metadata_decode_blob_size (ptr, &ptr);
954 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
958 sig = cache_memberref_sig (image, sig_idx, sig);
960 /* FIXME: we probably should verify signature compat in the dynamic case too*/
961 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
962 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
963 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
965 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
971 MonoMethodSignature *cached;
973 /* This signature is not owned by a MonoMethod, so need to cache */
974 sig = inflate_generic_signature_checked (image, sig, context, error);
975 if (!mono_error_ok (error))
978 cached = mono_metadata_get_inflated_signature (sig, context);
980 mono_metadata_free_inflated_signature (sig);
982 inflated_signatures_size += mono_metadata_signature_size (cached);
986 g_assert (mono_error_ok (error));
991 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
994 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
996 g_assert (!mono_loader_get_last_error ());
999 g_assert (!mono_error_ok (&error));
1000 mono_loader_set_error_from_mono_error (&error);
1001 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
1006 /* this is only for the typespec array methods */
1008 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1012 mono_class_setup_methods (klass);
1013 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
1014 for (i = 0; i < klass->method.count; ++i) {
1015 MonoMethod *method = klass->methods [i];
1016 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1023 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1024 gboolean *used_context, MonoError *error)
1026 MonoClass *klass = NULL;
1027 MonoMethod *method = NULL;
1028 MonoTableInfo *tables = image->tables;
1030 guint32 nindex, class, sig_idx;
1032 MonoMethodSignature *sig;
1035 mono_error_init (error);
1037 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1038 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1039 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1040 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1041 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1043 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1046 * Whether we actually used the `typespec_context' or not.
1047 * This is used to tell our caller whether or not it's safe to insert the returned
1048 * method into a cache.
1051 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
1054 case MONO_MEMBERREF_PARENT_TYPEREF:
1055 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1059 case MONO_MEMBERREF_PARENT_TYPESPEC:
1061 * Parse the TYPESPEC in the parent's context.
1063 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1067 case MONO_MEMBERREF_PARENT_TYPEDEF:
1068 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1072 case MONO_MEMBERREF_PARENT_METHODDEF: {
1073 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1079 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class, nindex);
1084 mono_class_init (klass);
1086 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1088 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1089 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1093 ptr = mono_metadata_blob_heap (image, sig_idx);
1094 mono_metadata_decode_blob_size (ptr, &ptr);
1096 sig = find_cached_memberref_sig (image, sig_idx);
1098 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1102 sig = cache_memberref_sig (image, sig_idx, sig);
1106 case MONO_MEMBERREF_PARENT_TYPEREF:
1107 case MONO_MEMBERREF_PARENT_TYPEDEF:
1108 method = find_method (klass, NULL, mname, sig, klass, error);
1111 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1114 type = &klass->byval_arg;
1116 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1117 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1118 method = find_method (in_class, NULL, mname, sig, klass, error);
1122 /* we're an array and we created these methods already in klass in mono_class_init () */
1123 method = mono_method_search_in_array_class (klass, mname, sig);
1127 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class, nindex);
1131 if (!method && mono_error_ok (error)) {
1132 char *msig = mono_signature_get_desc (sig, FALSE);
1133 GString *s = g_string_new (mname);
1134 if (sig->generic_param_count)
1135 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1136 g_string_append_printf (s, "(%s)", msig);
1138 msig = g_string_free (s, FALSE);
1140 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1141 mono_error_set_from_loader_error (error);
1143 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1148 g_assert (!mono_loader_get_last_error ());
1152 g_assert (!mono_loader_get_last_error ());
1153 g_assert (!mono_error_ok (error));
1158 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1162 MonoTableInfo *tables = image->tables;
1163 MonoGenericContext new_context;
1164 MonoGenericInst *inst;
1166 guint32 cols [MONO_METHODSPEC_SIZE];
1167 guint32 token, nindex, param_count;
1169 mono_error_init (error);
1171 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1172 token = cols [MONO_METHODSPEC_METHOD];
1173 nindex = token >> MONO_METHODDEFORREF_BITS;
1175 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1176 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1180 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1182 mono_metadata_decode_value (ptr, &ptr);
1184 param_count = mono_metadata_decode_value (ptr, &ptr);
1186 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1188 g_assert (!mono_loader_get_last_error ());
1189 mono_error_set_bad_image (error, image, "Cannot parse generic instance for methodspec 0x%08x", idx);
1193 if (context && inst->is_open) {
1194 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1195 if (!mono_error_ok (error))
1199 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1200 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1204 method = method_from_memberref (image, nindex, context, NULL, error);
1210 klass = method->klass;
1212 if (klass->generic_class) {
1213 g_assert (method->is_inflated);
1214 method = ((MonoMethodInflated *) method)->declaring;
1217 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1218 new_context.method_inst = inst;
1220 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1221 g_assert (!mono_loader_get_last_error ());
1225 struct _MonoDllMap {
1233 static MonoDllMap *global_dll_map;
1236 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1244 global_loader_data_lock ();
1247 * we use the first entry we find that matches, since entries from
1248 * the config file are prepended to the list and we document that the
1249 * later entries win.
1251 for (; dll_map; dll_map = dll_map->next) {
1252 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1253 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1255 } else if (strcmp (dll_map->dll, dll)) {
1258 if (!found && dll_map->target) {
1259 *rdll = dll_map->target;
1261 /* we don't quit here, because we could find a full
1262 * entry that matches also function and that has priority.
1265 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1266 *rfunc = dll_map->target_func;
1271 global_loader_data_unlock ();
1276 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1279 if (assembly && assembly->dll_map) {
1280 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1284 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1288 * mono_dllmap_insert:
1289 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1290 * @dll: The name of the external library, as it would be found in the DllImport declaration. If prefixed with 'i:' the matching of the library name is done without case sensitivity
1291 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1292 * @tdll: The name of the library to map the specified @dll if it matches.
1293 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1295 * LOCKING: Acquires the loader lock.
1297 * This function is used to programatically add DllImport remapping in either
1298 * a specific assembly, or as a global remapping. This is done by remapping
1299 * references in a DllImport attribute from the @dll library name into the @tdll
1300 * name. If the @dll name contains the prefix "i:", the comparison of the
1301 * library name is done without case sensitivity.
1303 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1304 * or the name of the function as determined by DllImport. If you pass @func, you
1305 * must also pass @tfunc which is the name of the target function to invoke on a match.
1308 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1310 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1311 * the contents of relocated_demo_path for all assemblies in the Mono process.
1313 * NOTE: This can be called before the runtime is initialized, for example from
1314 * mono_config_parse ().
1317 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1321 mono_loader_init ();
1324 entry = g_malloc0 (sizeof (MonoDllMap));
1325 entry->dll = dll? g_strdup (dll): NULL;
1326 entry->target = tdll? g_strdup (tdll): NULL;
1327 entry->func = func? g_strdup (func): NULL;
1328 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1330 global_loader_data_lock ();
1331 entry->next = global_dll_map;
1332 global_dll_map = entry;
1333 global_loader_data_unlock ();
1335 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1336 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1337 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1338 entry->func = func? mono_image_strdup (assembly, func): NULL;
1339 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1341 mono_image_lock (assembly);
1342 entry->next = assembly->dll_map;
1343 assembly->dll_map = entry;
1344 mono_image_unlock (assembly);
1349 free_dllmap (MonoDllMap *map)
1352 MonoDllMap *next = map->next;
1355 g_free (map->target);
1357 g_free (map->target_func);
1364 dllmap_cleanup (void)
1366 free_dllmap (global_dll_map);
1367 global_dll_map = NULL;
1370 static GHashTable *global_module_map;
1373 cached_module_load (const char *name, int flags, char **err)
1379 global_loader_data_lock ();
1380 if (!global_module_map)
1381 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1382 res = g_hash_table_lookup (global_module_map, name);
1384 global_loader_data_unlock ();
1387 res = mono_dl_open (name, flags, err);
1389 g_hash_table_insert (global_module_map, g_strdup (name), res);
1390 global_loader_data_unlock ();
1394 static MonoDl *internal_module;
1397 is_absolute_path (const char *path)
1399 #ifdef PLATFORM_MACOSX
1400 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1401 !strncmp (path, "@rpath/", 7))
1404 return g_path_is_absolute (path);
1408 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1410 MonoImage *image = method->klass->image;
1411 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1412 MonoTableInfo *tables = image->tables;
1413 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1414 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1415 guint32 im_cols [MONO_IMPLMAP_SIZE];
1416 guint32 scope_token;
1417 const char *import = NULL;
1418 const char *orig_scope;
1419 const char *new_scope;
1421 char *full_name, *file_name, *found_name = NULL;
1423 MonoDl *module = NULL;
1424 gboolean cached = FALSE;
1426 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1434 return piinfo->addr;
1436 if (image_is_dynamic (method->klass->image)) {
1437 MonoReflectionMethodAux *method_aux =
1438 g_hash_table_lookup (
1439 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1443 import = method_aux->dllentry;
1444 orig_scope = method_aux->dll;
1447 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1450 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1452 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1455 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1456 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1457 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1458 orig_scope = mono_metadata_string_heap (image, scope_token);
1461 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1464 mono_image_lock (image);
1465 if (!image->pinvoke_scopes) {
1466 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1467 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1469 module = g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1470 found_name = g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1471 mono_image_unlock (image);
1475 found_name = g_strdup (found_name);
1479 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1480 "DllImport attempting to load: '%s'.", new_scope);
1482 /* we allow a special name to dlopen from the running process namespace */
1483 if (strcmp (new_scope, "__Internal") == 0){
1484 if (internal_module == NULL)
1485 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1486 module = internal_module;
1491 * Try loading the module using a variety of names
1493 for (i = 0; i < 4; ++i) {
1494 char *base_name = NULL, *dir_name = NULL;
1495 gboolean is_absolute = is_absolute_path (new_scope);
1499 /* Try the original name */
1500 file_name = g_strdup (new_scope);
1503 /* Try trimming the .dll extension */
1504 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1505 file_name = g_strdup (new_scope);
1506 file_name [strlen (new_scope) - 4] = '\0';
1513 dir_name = g_path_get_dirname (new_scope);
1514 base_name = g_path_get_basename (new_scope);
1515 if (strstr (base_name, "lib") != base_name) {
1516 char *tmp = g_strdup_printf ("lib%s", base_name);
1519 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1522 } else if (strstr (new_scope, "lib") != new_scope) {
1523 file_name = g_strdup_printf ("lib%s", new_scope);
1528 #ifndef TARGET_WIN32
1529 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1530 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1531 !g_ascii_strcasecmp ("user32", new_scope) ||
1532 !g_ascii_strcasecmp ("kernel", new_scope)) {
1533 file_name = g_strdup ("libMonoSupportW.so");
1537 #ifndef TARGET_WIN32
1544 dir_name = g_path_get_dirname (file_name);
1546 base_name = g_path_get_basename (file_name);
1549 if (!module && is_absolute) {
1550 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1552 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1553 "DllImport error loading library '%s': '%s'.",
1554 file_name, error_msg);
1557 found_name = g_strdup (file_name);
1561 if (!module && !is_absolute) {
1563 char *mdirname = g_path_get_dirname (image->name);
1564 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1565 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1567 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1568 "DllImport error loading library '%s': '%s'.",
1569 full_name, error_msg);
1572 found_name = g_strdup (full_name);
1583 char *file_or_base = is_absolute ? base_name : file_name;
1584 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1585 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1587 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1588 "DllImport error loading library '%s': '%s'.",
1589 full_name, error_msg);
1592 found_name = g_strdup (full_name);
1601 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1603 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1604 "DllImport error loading library '%s': '%s'.",
1605 file_name, error_msg);
1607 found_name = g_strdup (file_name);
1622 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1623 "DllImport unable to load library '%s'.",
1628 *exc_class = "DllNotFoundException";
1629 *exc_arg = new_scope;
1635 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1636 "DllImport loaded library '%s'.", found_name);
1637 mono_image_lock (image);
1638 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1639 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1640 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1642 mono_image_unlock (image);
1645 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1646 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1647 g_free (found_name);
1650 if (import && import [0] == '#' && isdigit (import [1])) {
1654 id = strtol (import + 1, &end, 10);
1655 if (id > 0 && *end == '\0')
1659 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1660 "Searching for '%s'.", import);
1662 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1663 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1665 char *mangled_name = NULL, *mangled_name2 = NULL;
1668 int mangle_param_count;
1674 * Search using a variety of mangled names
1676 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1677 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1678 gboolean need_param_count = FALSE;
1680 if (mangle_stdcall > 0)
1681 need_param_count = TRUE;
1683 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1688 mangled_name = (char*)import;
1689 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1690 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1691 /* Try the mangled name first */
1692 if (mangle_charset == 0)
1693 mangled_name = g_strconcat (import, "W", NULL);
1695 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1697 if (mangle_charset == 0)
1698 mangled_name = g_strconcat (import, "W", NULL);
1700 /* Try the mangled name last */
1701 if (mangle_charset == 1)
1702 mangled_name = g_strconcat (import, "A", NULL);
1705 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1707 /* Try the mangled name last */
1708 if (mangle_charset == 1)
1709 mangled_name = g_strconcat (import, "A", NULL);
1714 if (mangle_param_count == 0)
1715 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1717 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1718 param_count = mangle_param_count;
1720 /* Try the stdcall mangled name */
1722 * gcc under windows creates mangled names without the underscore, but MS.NET
1723 * doesn't support it, so we doesn't support it either.
1725 if (mangle_stdcall == 1)
1726 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1728 mangled_name2 = mangled_name;
1730 mangled_name2 = mangled_name;
1733 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1734 "Probing '%s'.", mangled_name2);
1736 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1741 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1742 "Found as '%s'.", mangled_name2);
1744 if (mangled_name != mangled_name2)
1745 g_free (mangled_name2);
1746 if (mangled_name != import)
1747 g_free (mangled_name);
1753 if (!piinfo->addr) {
1756 *exc_class = "EntryPointNotFoundException";
1761 return piinfo->addr;
1765 * LOCKING: assumes the loader lock to be taken.
1768 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1769 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1772 int table = mono_metadata_token_table (token);
1773 int idx = mono_metadata_token_index (token);
1774 MonoTableInfo *tables = image->tables;
1775 MonoGenericContainer *generic_container = NULL, *container = NULL;
1776 const char *sig = NULL;
1778 guint32 cols [MONO_TYPEDEF_SIZE];
1780 mono_error_init (error);
1782 if (image_is_dynamic (image)) {
1783 MonoClass *handle_class;
1785 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1786 g_assert (!mono_loader_get_last_error ());
1788 // This checks the memberref type as well
1789 if (result && handle_class != mono_defaults.methodhandle_class) {
1790 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1796 if (table != MONO_TABLE_METHOD) {
1797 if (table == MONO_TABLE_METHODSPEC) {
1798 if (used_context) *used_context = TRUE;
1799 return method_from_methodspec (image, context, idx, error);
1801 if (table != MONO_TABLE_MEMBERREF) {
1802 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1805 return method_from_memberref (image, idx, context, used_context, error);
1808 if (used_context) *used_context = FALSE;
1810 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1811 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1816 guint32 type = mono_metadata_typedef_from_method (image, token);
1818 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1821 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1826 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1828 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1829 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1830 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1832 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1833 methods_size += sizeof (MonoMethod);
1836 mono_stats.method_count ++;
1839 result->klass = klass;
1840 result->flags = cols [2];
1841 result->iflags = cols [1];
1842 result->token = token;
1843 result->name = mono_metadata_string_heap (image, cols [3]);
1845 if (!sig) /* already taken from the methodref */
1846 sig = mono_metadata_blob_heap (image, cols [4]);
1847 size = mono_metadata_decode_blob_size (sig, &sig);
1849 container = klass->generic_container;
1852 * load_generic_params does a binary search so only call it if the method
1856 generic_container = mono_metadata_load_generic_params (image, token, container);
1857 g_assert (!mono_loader_get_last_error ()); /* FIXME don't swallow this error. */
1859 if (generic_container) {
1860 result->is_generic = TRUE;
1861 generic_container->owner.method = result;
1862 /*FIXME put this before the image alloc*/
1863 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1866 container = generic_container;
1869 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1870 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1871 result->string_ctor = 1;
1872 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1873 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1876 /* IJW is P/Invoke with a predefined function pointer. */
1877 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1878 piinfo->addr = mono_image_rva_map (image, cols [0]);
1879 g_assert (piinfo->addr);
1882 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1883 /* Native methods can have no map. */
1884 if (piinfo->implmap_idx)
1885 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1888 if (generic_container)
1889 mono_method_set_generic_container (result, generic_container);
1891 g_assert (!mono_loader_get_last_error ());
1896 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1898 return mono_get_method_full (image, token, klass, NULL);
1902 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1903 MonoGenericContext *context)
1906 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
1907 g_assert (!mono_loader_get_last_error ());
1908 if (!mono_error_ok (&error)) {
1909 mono_loader_set_error_from_mono_error (&error);
1910 mono_error_cleanup (&error);
1916 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
1918 MonoMethod *result = NULL;
1919 gboolean used_context = FALSE;
1921 /* We do everything inside the lock to prevent creation races */
1923 mono_error_init (error);
1925 mono_image_lock (image);
1927 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1928 if (!image->method_cache)
1929 image->method_cache = g_hash_table_new (NULL, NULL);
1930 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1931 } else if (!image_is_dynamic (image)) {
1932 if (!image->methodref_cache)
1933 image->methodref_cache = g_hash_table_new (NULL, NULL);
1934 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1936 mono_image_unlock (image);
1942 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
1946 mono_image_lock (image);
1947 if (!used_context && !result->is_inflated) {
1948 MonoMethod *result2 = NULL;
1950 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1951 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1952 else if (!image_is_dynamic (image))
1953 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1956 mono_image_unlock (image);
1960 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1961 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1962 else if (!image_is_dynamic (image))
1963 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1966 mono_image_unlock (image);
1972 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
1975 MonoClass *ic = NULL;
1976 MonoGenericContext *method_context = NULL;
1977 MonoMethodSignature *sig, *original_sig;
1979 mono_error_init (error);
1981 mono_class_init (constrained_class);
1982 original_sig = sig = mono_method_signature_checked (method, error);
1987 if (method->is_inflated && sig->generic_param_count) {
1988 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1989 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1992 method_context = mono_method_get_context (method);
1996 * We must inflate the signature with the class instantiation to work on
1997 * cases where a class inherit from a generic type and the override replaces
1998 * any type argument which a concrete type. See #325283.
2000 if (method_context->class_inst) {
2001 MonoGenericContext ctx;
2002 ctx.method_inst = NULL;
2003 ctx.class_inst = method_context->class_inst;
2004 /*Fixme, property propagate this error*/
2005 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2011 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2014 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2015 if (sig != original_sig)
2016 mono_metadata_free_inflated_signature (sig);
2021 if (method_context) {
2022 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2031 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2032 MonoGenericContext *context, MonoError *error)
2036 return get_method_constrained (image, method, constrained_class, context, error);
2040 * mono_get_method_constrained:
2042 * This is used when JITing the `constrained.' opcode.
2044 * This returns two values: the contrained method, which has been inflated
2045 * as the function return value; And the original CIL-stream method as
2046 * declared in cil_method. The later is used for verification.
2049 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2050 MonoGenericContext *context, MonoMethod **cil_method)
2053 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2055 g_assert (!mono_loader_get_last_error ());
2056 if (!mono_error_ok (&error)) {
2057 mono_loader_set_error_from_mono_error (&error);
2058 mono_error_cleanup (&error);
2064 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2066 mono_error_init (error);
2068 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2072 return get_method_constrained (image, *cil_method, constrained_class, context, error);
2076 mono_free_method (MonoMethod *method)
2078 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2079 mono_profiler_method_free (method);
2081 /* FIXME: This hack will go away when the profiler will support freeing methods */
2082 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2085 if (method->signature) {
2087 * FIXME: This causes crashes because the types inside signatures and
2088 * locals are shared.
2090 /* mono_metadata_free_method_signature (method->signature); */
2091 /* g_free (method->signature); */
2094 if (method_is_dynamic (method)) {
2095 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2098 mono_marshal_free_dynamic_wrappers (method);
2100 mono_image_property_remove (method->klass->image, method);
2102 g_free ((char*)method->name);
2104 g_free ((char*)mw->header->code);
2105 for (i = 0; i < mw->header->num_locals; ++i)
2106 g_free (mw->header->locals [i]);
2107 g_free (mw->header->clauses);
2108 g_free (mw->header);
2110 g_free (mw->method_data);
2111 g_free (method->signature);
2117 mono_method_get_param_names (MonoMethod *method, const char **names)
2121 MonoTableInfo *methodt;
2122 MonoTableInfo *paramt;
2123 MonoMethodSignature *signature;
2126 if (method->is_inflated)
2127 method = ((MonoMethodInflated *) method)->declaring;
2129 signature = mono_method_signature (method);
2130 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2131 number of arguments and allocate a properly sized array. */
2132 if (signature == NULL)
2135 if (!signature->param_count)
2138 for (i = 0; i < signature->param_count; ++i)
2141 klass = method->klass;
2145 mono_class_init (klass);
2147 if (image_is_dynamic (klass->image)) {
2148 MonoReflectionMethodAux *method_aux =
2149 g_hash_table_lookup (
2150 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2151 if (method_aux && method_aux->param_names) {
2152 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2153 if (method_aux->param_names [i + 1])
2154 names [i] = method_aux->param_names [i + 1];
2159 if (method->wrapper_type) {
2160 char **pnames = NULL;
2162 mono_image_lock (klass->image);
2163 if (klass->image->wrapper_param_names)
2164 pnames = g_hash_table_lookup (klass->image->wrapper_param_names, method);
2165 mono_image_unlock (klass->image);
2168 for (i = 0; i < signature->param_count; ++i)
2169 names [i] = pnames [i];
2174 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2175 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2176 idx = mono_method_get_index (method);
2178 guint32 cols [MONO_PARAM_SIZE];
2181 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2183 if (idx < methodt->rows)
2184 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2186 lastp = paramt->rows + 1;
2187 for (i = param_index; i < lastp; ++i) {
2188 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2189 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2190 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2196 mono_method_get_param_token (MonoMethod *method, int index)
2198 MonoClass *klass = method->klass;
2199 MonoTableInfo *methodt;
2202 mono_class_init (klass);
2204 if (image_is_dynamic (klass->image))
2205 g_assert_not_reached ();
2207 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2208 idx = mono_method_get_index (method);
2210 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2214 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2216 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2223 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2226 MonoClass *klass = method->klass;
2227 MonoTableInfo *methodt;
2228 MonoTableInfo *paramt;
2229 MonoMethodSignature *signature;
2232 signature = mono_method_signature (method);
2233 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2235 for (i = 0; i < signature->param_count + 1; ++i)
2238 if (image_is_dynamic (method->klass->image)) {
2239 MonoReflectionMethodAux *method_aux =
2240 g_hash_table_lookup (
2241 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2242 if (method_aux && method_aux->param_marshall) {
2243 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2244 for (i = 0; i < signature->param_count + 1; ++i)
2245 if (dyn_specs [i]) {
2246 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2247 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2248 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2249 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2255 mono_class_init (klass);
2257 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2258 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2259 idx = mono_method_get_index (method);
2261 guint32 cols [MONO_PARAM_SIZE];
2262 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2264 if (idx < methodt->rows)
2265 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2267 lastp = paramt->rows + 1;
2269 for (i = param_index; i < lastp; ++i) {
2270 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2272 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2274 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2276 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2285 mono_method_has_marshal_info (MonoMethod *method)
2288 MonoClass *klass = method->klass;
2289 MonoTableInfo *methodt;
2290 MonoTableInfo *paramt;
2293 if (image_is_dynamic (method->klass->image)) {
2294 MonoReflectionMethodAux *method_aux =
2295 g_hash_table_lookup (
2296 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2297 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2299 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2306 mono_class_init (klass);
2308 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2309 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2310 idx = mono_method_get_index (method);
2312 guint32 cols [MONO_PARAM_SIZE];
2313 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2315 if (idx + 1 < methodt->rows)
2316 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2318 lastp = paramt->rows + 1;
2320 for (i = param_index; i < lastp; ++i) {
2321 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2323 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2332 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2335 g_assert (method != NULL);
2336 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2338 if (method->is_inflated)
2339 method = ((MonoMethodInflated *) method)->declaring;
2340 data = ((MonoMethodWrapper *)method)->method_data;
2341 g_assert (data != NULL);
2342 g_assert (id <= GPOINTER_TO_UINT (*data));
2349 } StackWalkUserData;
2352 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2354 StackWalkUserData *d = data;
2356 switch (frame->type) {
2357 case FRAME_TYPE_DEBUGGER_INVOKE:
2358 case FRAME_TYPE_MANAGED_TO_NATIVE:
2360 case FRAME_TYPE_MANAGED:
2361 g_assert (frame->ji);
2362 return d->func (mono_jit_info_get_method (frame->ji), frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2365 g_assert_not_reached ();
2371 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2373 StackWalkUserData ud = { func, user_data };
2374 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2378 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2380 StackWalkUserData ud = { func, user_data };
2381 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2385 MonoStackWalkAsyncSafe func;
2387 } AsyncStackWalkUserData;
2391 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2393 AsyncStackWalkUserData *d = data;
2395 switch (frame->type) {
2396 case FRAME_TYPE_DEBUGGER_INVOKE:
2397 case FRAME_TYPE_MANAGED_TO_NATIVE:
2399 case FRAME_TYPE_MANAGED:
2402 if (frame->ji->async)
2403 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2405 return d->func (mono_jit_info_get_method (frame->ji), frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2408 g_assert_not_reached ();
2415 * mono_stack_walk_async_safe:
2417 * Async safe version callable from signal handlers.
2420 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2423 AsyncStackWalkUserData ud = { func, user_data };
2425 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2426 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2430 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2432 MonoMethod **dest = data;
2434 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2440 mono_method_get_last_managed (void)
2442 MonoMethod *m = NULL;
2443 mono_stack_walk_no_il (last_managed, &m);
2447 static gboolean loader_lock_track_ownership = FALSE;
2452 * See docs/thread-safety.txt for the locking strategy.
2455 mono_loader_lock (void)
2457 mono_locks_acquire (&loader_mutex, LoaderLock);
2458 if (G_UNLIKELY (loader_lock_track_ownership)) {
2459 mono_native_tls_set_value (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) + 1));
2464 mono_loader_unlock (void)
2466 mono_locks_release (&loader_mutex, LoaderLock);
2467 if (G_UNLIKELY (loader_lock_track_ownership)) {
2468 mono_native_tls_set_value (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) - 1));
2473 * mono_loader_lock_track_ownership:
2475 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2476 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2477 * thread owns the loader lock.
2480 mono_loader_lock_track_ownership (gboolean track)
2482 loader_lock_track_ownership = track;
2486 * mono_loader_lock_is_owned_by_self:
2488 * Return whenever the current thread owns the loader lock.
2489 * This is useful to avoid blocking operations while holding the loader lock.
2492 mono_loader_lock_is_owned_by_self (void)
2494 g_assert (loader_lock_track_ownership);
2496 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2500 * mono_loader_lock_if_inited:
2502 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2503 * be used in runtime initialization code which can be executed before mono_loader_init ().
2506 mono_loader_lock_if_inited (void)
2508 if (loader_lock_inited)
2509 mono_loader_lock ();
2513 mono_loader_unlock_if_inited (void)
2515 if (loader_lock_inited)
2516 mono_loader_unlock ();
2520 * mono_method_signature:
2522 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2524 MonoMethodSignature*
2525 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2531 gboolean can_cache_signature;
2532 MonoGenericContainer *container;
2533 MonoMethodSignature *signature = NULL, *sig2;
2536 /* We need memory barriers below because of the double-checked locking pattern */
2538 mono_error_init (error);
2541 return m->signature;
2543 img = m->klass->image;
2545 if (m->is_inflated) {
2546 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2547 /* the lock is recursive */
2548 signature = mono_method_signature (imethod->declaring);
2549 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2550 if (!mono_error_ok (error))
2553 inflated_signatures_size += mono_metadata_signature_size (signature);
2555 mono_image_lock (img);
2557 mono_memory_barrier ();
2559 m->signature = signature;
2561 mono_image_unlock (img);
2563 return m->signature;
2566 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2567 idx = mono_metadata_token_index (m->token);
2569 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2571 g_assert (!m->klass->generic_class);
2572 container = mono_method_get_generic_container (m);
2574 container = m->klass->generic_container;
2576 /* Generic signatures depend on the container so they cannot be cached */
2577 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2578 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2580 /* If the method has parameter attributes, that can modify the signature */
2581 if (mono_metadata_method_has_param_attrs (img, idx))
2582 can_cache_signature = FALSE;
2584 if (can_cache_signature) {
2585 mono_image_lock (img);
2586 signature = g_hash_table_lookup (img->method_signatures, sig);
2587 mono_image_unlock (img);
2591 const char *sig_body;
2592 /*TODO we should cache the failure result somewhere*/
2593 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2596 size = mono_metadata_decode_blob_size (sig, &sig_body);
2598 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2602 if (can_cache_signature) {
2603 mono_image_lock (img);
2604 sig2 = g_hash_table_lookup (img->method_signatures, sig);
2606 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2607 mono_image_unlock (img);
2610 signatures_size += mono_metadata_signature_size (signature);
2613 /* Verify metadata consistency */
2614 if (signature->generic_param_count) {
2615 if (!container || !container->is_method) {
2616 mono_error_set_method_load (error, m->klass, m->name, "Signature claims method has generic parameters, but generic_params table says it doesn't for method 0x%08x from image %s", idx, img->name);
2619 if (container->type_argc != signature->generic_param_count) {
2620 mono_error_set_method_load (error, m->klass, m->name, "Inconsistent generic parameter count. Signature says %d, generic_params table says %d for method 0x%08x from image %s", signature->generic_param_count, container->type_argc, idx, img->name);
2623 } else if (container && container->is_method && container->type_argc) {
2624 mono_error_set_method_load (error, m->klass, m->name, "generic_params table claims method has generic parameters, but signature says it doesn't for method 0x%08x from image %s", idx, img->name);
2627 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2628 signature->pinvoke = 1;
2629 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2630 MonoCallConvention conv = 0;
2631 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2632 signature->pinvoke = 1;
2634 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2635 case 0: /* no call conv, so using default */
2636 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2637 conv = MONO_CALL_DEFAULT;
2639 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2642 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2643 conv = MONO_CALL_STDCALL;
2645 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2646 conv = MONO_CALL_THISCALL;
2648 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2649 conv = MONO_CALL_FASTCALL;
2651 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2652 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2654 mono_error_set_method_load (error, m->klass, m->name, "unsupported calling convention : 0x%04x for method 0x%08x from image %s", piinfo->piflags, idx, img->name);
2657 signature->call_convention = conv;
2660 mono_image_lock (img);
2662 mono_memory_barrier ();
2664 m->signature = signature;
2666 mono_image_unlock (img);
2668 return m->signature;
2672 * mono_method_signature:
2674 * Return the signature of the method M. On failure, returns NULL.
2676 MonoMethodSignature*
2677 mono_method_signature (MonoMethod *m)
2680 MonoMethodSignature *sig;
2682 sig = mono_method_signature_checked (m, &error);
2684 char *type_name = mono_type_get_full_name (m->klass);
2685 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2687 mono_error_cleanup (&error);
2694 mono_method_get_name (MonoMethod *method)
2696 return method->name;
2700 mono_method_get_class (MonoMethod *method)
2702 return method->klass;
2706 mono_method_get_token (MonoMethod *method)
2708 return method->token;
2712 mono_method_get_header (MonoMethod *method)
2718 MonoMethodHeader *header;
2719 MonoGenericContainer *container;
2721 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2724 img = method->klass->image;
2726 if (method->is_inflated) {
2727 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2728 MonoMethodHeader *header, *iheader;
2730 header = mono_method_get_header (imethod->declaring);
2734 iheader = inflate_generic_header (header, mono_method_get_context (method));
2735 mono_metadata_free_mh (header);
2737 mono_image_lock (img);
2739 if (imethod->header) {
2740 mono_metadata_free_mh (iheader);
2741 mono_image_unlock (img);
2742 return imethod->header;
2745 mono_memory_barrier ();
2746 imethod->header = iheader;
2748 mono_image_unlock (img);
2750 return imethod->header;
2753 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2754 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2755 g_assert (mw->header);
2760 * We don't need locks here: the new header is allocated from malloc memory
2761 * and is not stored anywhere in the runtime, the user needs to free it.
2763 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2764 idx = mono_metadata_token_index (method->token);
2765 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2767 if (!mono_verifier_verify_method_header (img, rva, NULL))
2770 loc = mono_image_rva_map (img, rva);
2775 * When parsing the types of local variables, we must pass any container available
2776 * to ensure that both VAR and MVAR will get the right owner.
2778 container = mono_method_get_generic_container (method);
2780 container = method->klass->generic_container;
2781 header = mono_metadata_parse_mh_full (img, container, loc);
2787 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2790 *iflags = method->iflags;
2791 return method->flags;
2795 * Find the method index in the metadata methodDef table.
2798 mono_method_get_index (MonoMethod *method)
2800 MonoClass *klass = method->klass;
2804 /* constructed array methods are not in the MethodDef table */
2808 return mono_metadata_token_index (method->token);
2810 mono_class_setup_methods (klass);
2811 if (klass->exception_type)
2813 for (i = 0; i < klass->method.count; ++i) {
2814 if (method == klass->methods [i]) {
2815 if (klass->image->uncompressed_metadata)
2816 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2818 return klass->method.first + i + 1;