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_init ();
107 mono_counters_register ("Inflated signatures size",
108 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
109 mono_counters_register ("Memberref signature cache size",
110 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
111 mono_counters_register ("MonoMethod size",
112 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
113 mono_counters_register ("MonoMethodSignature size",
114 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
121 mono_loader_cleanup (void)
125 mono_native_tls_free (loader_error_thread_id);
126 mono_native_tls_free (loader_lock_nest_id);
128 mono_mutex_destroy (&loader_mutex);
129 mono_mutex_destroy (&global_loader_data_mutex);
130 loader_lock_inited = FALSE;
134 * Handling of type load errors should be done as follows:
136 * If something could not be loaded, the loader should call one of the
137 * mono_loader_set_error_XXX functions ()
138 * with the appropriate arguments, then return NULL to report the failure. The error
139 * should be propagated until it reaches code which can throw managed exceptions. At that
140 * point, an exception should be thrown based on the information returned by
141 * mono_loader_get_last_error (). Then the error should be cleared by calling
142 * mono_loader_clear_error ().
146 set_loader_error (MonoLoaderError *error)
148 mono_loader_clear_error ();
149 mono_native_tls_set_value (loader_error_thread_id, error);
153 * mono_loader_set_error_assembly_load:
155 * Set the loader error for this thread.
158 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
160 MonoLoaderError *error;
162 if (mono_loader_get_last_error ())
165 error = g_new0 (MonoLoaderError, 1);
166 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
167 error->assembly_name = g_strdup (assembly_name);
168 error->ref_only = ref_only;
171 * This is not strictly needed, but some (most) of the loader code still
172 * can't deal with load errors, and this message is more helpful than an
176 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);
178 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
180 set_loader_error (error);
184 * mono_loader_set_error_type_load:
186 * Set the loader error for this thread.
189 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
191 MonoLoaderError *error;
193 if (mono_loader_get_last_error ())
196 error = g_new0 (MonoLoaderError, 1);
197 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
198 error->class_name = g_strdup (class_name);
199 error->assembly_name = g_strdup (assembly_name);
202 * This is not strictly needed, but some (most) of the loader code still
203 * can't deal with load errors, and this message is more helpful than an
206 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
208 set_loader_error (error);
212 * mono_loader_set_error_method_load:
214 * Set the loader error for this thread. MEMBER_NAME should point to a string
218 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
220 MonoLoaderError *error;
222 /* FIXME: Store the signature as well */
223 if (mono_loader_get_last_error ())
226 error = g_new0 (MonoLoaderError, 1);
227 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
228 error->class_name = g_strdup (class_name);
229 error->member_name = member_name;
231 set_loader_error (error);
235 * mono_loader_set_error_field_load:
237 * Set the loader error for this thread. MEMBER_NAME should point to a string
241 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
243 MonoLoaderError *error;
245 /* FIXME: Store the signature as well */
246 if (mono_loader_get_last_error ())
249 error = g_new0 (MonoLoaderError, 1);
250 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
251 error->klass = klass;
252 error->member_name = member_name;
254 set_loader_error (error);
258 * mono_loader_set_error_bad_image:
260 * Set the loader error for this thread.
263 mono_loader_set_error_bad_image (char *msg)
265 MonoLoaderError *error;
267 if (mono_loader_get_last_error ())
270 error = g_new0 (MonoLoaderError, 1);
271 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
274 set_loader_error (error);
279 * mono_loader_get_last_error:
281 * Returns information about the last type load exception encountered by the loader, or
282 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
285 mono_loader_get_last_error (void)
287 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
291 mono_loader_assert_no_error (void)
293 MonoLoaderError *error = mono_loader_get_last_error ();
296 g_print ("Unhandled loader error: %x, %s %s %s\n", error->exception_type, error->msg, error->assembly_name, error->class_name);
297 g_assert_not_reached ();
302 * mono_loader_clear_error:
304 * Disposes any loader error messages on this thread
307 mono_loader_clear_error (void)
309 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
312 g_free (ex->class_name);
313 g_free (ex->assembly_name);
317 mono_native_tls_set_value (loader_error_thread_id, NULL);
322 * mono_loader_error_prepare_exception:
323 * @error: The MonoLoaderError to turn into an exception
325 * This turns a MonoLoaderError into an exception that can be thrown
326 * and resets the Mono Loader Error state during this process.
330 mono_loader_error_prepare_exception (MonoLoaderError *error)
332 MonoException *ex = NULL;
334 switch (error->exception_type) {
335 case MONO_EXCEPTION_TYPE_LOAD: {
336 char *cname = g_strdup (error->class_name);
337 char *aname = g_strdup (error->assembly_name);
338 MonoString *class_name;
340 mono_loader_clear_error ();
342 class_name = mono_string_new (mono_domain_get (), cname);
344 ex = mono_get_exception_type_load (class_name, aname);
349 case MONO_EXCEPTION_MISSING_METHOD: {
350 char *cname = g_strdup (error->class_name);
351 char *aname = g_strdup (error->member_name);
353 mono_loader_clear_error ();
354 ex = mono_get_exception_missing_method (cname, aname);
360 case MONO_EXCEPTION_MISSING_FIELD: {
362 char *cmembername = g_strdup (error->member_name);
364 class_name = mono_type_get_full_name (error->klass);
366 class_name = g_strdup ("");
368 mono_loader_clear_error ();
370 ex = mono_get_exception_missing_field (class_name, cmembername);
372 g_free (cmembername);
376 case MONO_EXCEPTION_FILE_NOT_FOUND: {
381 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);
383 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
384 filename = g_strdup (error->assembly_name);
385 /* Has to call this before calling anything which might call mono_class_init () */
386 mono_loader_clear_error ();
387 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
393 case MONO_EXCEPTION_BAD_IMAGE: {
394 char *msg = g_strdup (error->msg);
395 mono_loader_clear_error ();
396 ex = mono_get_exception_bad_image_format (msg);
402 g_assert_not_reached ();
409 * find_cached_memberref_sig:
411 * Return a cached copy of the memberref signature identified by SIG_IDX.
412 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
413 * A cache is needed since the type/signature parsing routines allocate everything
414 * from a mempool, so without a cache, multiple requests for the same signature would
415 * lead to unbounded memory growth. For normal methods/fields this is not a problem
416 * since the resulting methods/fields are cached, but inflated methods/fields cannot
418 * LOCKING: Acquires the loader lock.
421 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
425 mono_image_lock (image);
426 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
427 mono_image_unlock (image);
433 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
437 mono_image_lock (image);
438 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
440 /* Somebody got in before us */
444 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
445 /* An approximation based on glib 2.18 */
446 memberref_sig_cache_size += sizeof (gpointer) * 4;
448 mono_image_unlock (image);
453 static MonoClassField*
454 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
455 MonoGenericContext *context, MonoError *error)
457 MonoClass *klass = NULL;
458 MonoClassField *field;
459 MonoTableInfo *tables = image->tables;
462 guint32 nindex, class;
465 guint32 idx = mono_metadata_token_index (token);
467 mono_error_init (error);
469 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
470 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
471 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
473 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
475 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
476 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class, token);
481 case MONO_MEMBERREF_PARENT_TYPEDEF:
482 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
484 case MONO_MEMBERREF_PARENT_TYPEREF:
485 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
487 case MONO_MEMBERREF_PARENT_TYPESPEC:
488 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
491 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class, token);
497 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
498 mono_metadata_decode_blob_size (ptr, &ptr);
499 /* we may want to check the signature here... */
502 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class, fname, token);
506 /* FIXME: This needs a cache, especially for generic instances, since
507 * mono_metadata_parse_type () allocates everything from a mempool.
509 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
511 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
512 if (sig_type == NULL) {
513 mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x", fname, token);
516 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
519 mono_class_init (klass); /*FIXME is this really necessary?*/
522 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
525 mono_loader_assert_no_error ();
526 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
533 * mono_field_from_token:
534 * @deprecated use the _checked variant
537 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
540 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
541 mono_loader_assert_no_error ();
542 if (!mono_error_ok (&error)) {
543 mono_loader_set_error_from_mono_error (&error);
544 mono_error_cleanup (&error);
550 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
554 MonoClassField *field;
556 mono_error_init (error);
558 if (image_is_dynamic (image)) {
559 MonoClassField *result;
560 MonoClass *handle_class;
563 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
564 // This checks the memberref type as well
565 if (!result || handle_class != mono_defaults.fieldhandle_class) {
566 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
569 *retklass = result->parent;
573 if ((field = mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
574 *retklass = field->parent;
578 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
579 field = field_from_memberref (image, token, retklass, context, error);
580 mono_loader_assert_no_error ();
582 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
584 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
587 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
594 field = mono_class_get_field (k, token);
596 if (mono_loader_get_last_error ())
597 mono_error_set_from_loader_error (error);
599 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
603 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
604 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
606 mono_loader_assert_no_error ();
611 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
615 if (sig1->hasthis != sig2->hasthis ||
616 sig1->sentinelpos != sig2->sentinelpos)
619 for (i = 0; i < sig1->sentinelpos; i++) {
620 MonoType *p1 = sig1->params[i];
621 MonoType *p2 = sig2->params[i];
623 /*if (p1->attrs != p2->attrs)
626 if (!mono_metadata_type_equal (p1, p2))
630 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
636 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
637 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
641 /* Search directly in the metadata to avoid calling setup_methods () */
642 mono_error_init (error);
644 /* FIXME: !from_class->generic_class condition causes test failures. */
645 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
646 for (i = 0; i < klass->method.count; ++i) {
647 guint32 cols [MONO_METHOD_SIZE];
650 MonoMethodSignature *other_sig;
652 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
654 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
656 if (!((fqname && !strcmp (m_name, fqname)) ||
657 (qname && !strcmp (m_name, qname)) ||
658 (name && !strcmp (m_name, name))))
661 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
662 if (!mono_error_ok (error)) //bail out if we hit a loader error
665 other_sig = mono_method_signature_checked (method, error);
666 if (!mono_error_ok (error)) //bail out if we hit a loader error
668 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
674 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
676 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
677 See mono/tests/generic-type-load-exception.2.il
678 FIXME we should better report this error to the caller
680 if (!klass->methods || klass->exception_type) {
681 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
685 for (i = 0; i < klass->method.count; ++i) {
686 MonoMethod *m = klass->methods [i];
687 MonoMethodSignature *msig;
689 /* We must cope with failing to load some of the types. */
693 if (!((fqname && !strcmp (m->name, fqname)) ||
694 (qname && !strcmp (m->name, qname)) ||
695 (name && !strcmp (m->name, name))))
697 msig = mono_method_signature_checked (m, error);
698 if (!mono_error_ok (error)) //bail out if we hit a loader error
704 if (sig->call_convention == MONO_CALL_VARARG) {
705 if (mono_metadata_signature_vararg_match (sig, msig))
708 if (mono_metadata_signature_equal (sig, msig))
713 if (i < klass->method.count)
714 return mono_class_get_method_by_index (from_class, i);
719 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
722 char *qname, *fqname, *class_name;
723 gboolean is_interface;
724 MonoMethod *result = NULL;
725 MonoClass *initial_class = in_class;
727 mono_error_init (error);
728 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
731 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
733 qname = g_strconcat (class_name, ".", name, NULL);
734 if (ic->name_space && ic->name_space [0])
735 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
739 class_name = qname = fqname = NULL;
742 g_assert (from_class);
743 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
744 if (result || !mono_error_ok (error))
747 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
751 * This happens when we fail to lazily load the interfaces of one of the types.
752 * On such case we can't just bail out since user code depends on us trying harder.
754 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
755 in_class = in_class->parent;
756 from_class = from_class->parent;
760 for (i = 0; i < in_class->interface_offsets_count; i++) {
761 MonoClass *in_ic = in_class->interfaces_packed [i];
762 MonoClass *from_ic = from_class->interfaces_packed [i];
763 char *ic_qname, *ic_fqname, *ic_class_name;
765 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
766 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
767 if (in_ic->name_space && in_ic->name_space [0])
768 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
772 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
773 g_free (ic_class_name);
776 if (result || !mono_error_ok (error))
780 in_class = in_class->parent;
781 from_class = from_class->parent;
783 g_assert (!in_class == !from_class);
786 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
788 //we did not find the method
789 if (!result && mono_error_ok (error)) {
790 char *desc = mono_signature_get_desc (sig, FALSE);
791 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
802 static MonoMethodSignature*
803 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
805 MonoMethodSignature *res;
809 mono_error_init (error);
813 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
814 res->param_count = sig->param_count;
815 res->sentinelpos = -1;
816 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
817 if (!mono_error_ok (error))
819 is_open = mono_class_is_open_constructed_type (res->ret);
820 for (i = 0; i < sig->param_count; ++i) {
821 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
822 if (!mono_error_ok (error))
826 is_open = mono_class_is_open_constructed_type (res->params [i]);
828 res->hasthis = sig->hasthis;
829 res->explicit_this = sig->explicit_this;
830 res->call_convention = sig->call_convention;
831 res->pinvoke = sig->pinvoke;
832 res->generic_param_count = sig->generic_param_count;
833 res->sentinelpos = sig->sentinelpos;
834 res->has_type_parameters = is_open;
835 res->is_inflated = 1;
840 mono_metadata_free_type (res->ret);
841 for (i = 0; i < sig->param_count; ++i) {
843 mono_metadata_free_type (res->params [i]);
850 * mono_inflate_generic_signature:
852 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
855 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
857 MonoMethodSignature *res, *cached;
859 res = inflate_generic_signature_checked (NULL, sig, context, error);
860 if (!mono_error_ok (error))
862 cached = mono_metadata_get_inflated_signature (res, context);
864 mono_metadata_free_inflated_signature (res);
868 static MonoMethodHeader*
869 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
871 MonoMethodHeader *res;
873 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
874 res->code = header->code;
875 res->code_size = header->code_size;
876 res->max_stack = header->max_stack;
877 res->num_clauses = header->num_clauses;
878 res->init_locals = header->init_locals;
879 res->num_locals = header->num_locals;
880 res->clauses = header->clauses;
881 for (i = 0; i < header->num_locals; ++i)
882 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
883 if (res->num_clauses) {
884 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
885 for (i = 0; i < header->num_clauses; ++i) {
886 MonoExceptionClause *clause = &res->clauses [i];
887 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
889 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
896 * token is the method_ref/def/spec token used in a call IL instruction.
899 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
902 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
904 mono_loader_assert_no_error ();
907 g_assert (!mono_error_ok (&error));
908 mono_loader_set_error_from_mono_error (&error);
909 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
915 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
917 int table = mono_metadata_token_table (token);
918 int idx = mono_metadata_token_index (token);
920 guint32 cols [MONO_MEMBERREF_SIZE];
921 MonoMethodSignature *sig;
924 mono_error_init (error);
926 /* !table is for wrappers: we should really assign their own token to them */
927 if (!table || table == MONO_TABLE_METHOD)
928 return mono_method_signature_checked (method, error);
930 if (table == MONO_TABLE_METHODSPEC) {
931 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
932 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
935 return mono_method_signature_checked (method, error);
938 if (method->klass->generic_class)
939 return mono_method_signature_checked (method, error);
941 if (image_is_dynamic (image)) {
942 sig = mono_reflection_lookup_signature (image, method, token, error);
946 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
947 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
949 sig = find_cached_memberref_sig (image, sig_idx);
951 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
952 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
953 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
955 //FIXME include the verification error
956 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
960 ptr = mono_metadata_blob_heap (image, sig_idx);
961 mono_metadata_decode_blob_size (ptr, &ptr);
963 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
967 sig = cache_memberref_sig (image, sig_idx, sig);
969 /* FIXME: we probably should verify signature compat in the dynamic case too*/
970 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
971 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
972 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
974 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
980 MonoMethodSignature *cached;
982 /* This signature is not owned by a MonoMethod, so need to cache */
983 sig = inflate_generic_signature_checked (image, sig, context, error);
984 if (!mono_error_ok (error))
987 cached = mono_metadata_get_inflated_signature (sig, context);
989 mono_metadata_free_inflated_signature (sig);
991 inflated_signatures_size += mono_metadata_signature_size (cached);
995 g_assert (mono_error_ok (error));
1000 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
1003 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
1005 mono_loader_assert_no_error ();
1008 g_assert (!mono_error_ok (&error));
1009 mono_loader_set_error_from_mono_error (&error);
1010 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
1015 /* this is only for the typespec array methods */
1017 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1021 mono_class_setup_methods (klass);
1022 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
1023 for (i = 0; i < klass->method.count; ++i) {
1024 MonoMethod *method = klass->methods [i];
1025 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1032 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1033 gboolean *used_context, MonoError *error)
1035 MonoClass *klass = NULL;
1036 MonoMethod *method = NULL;
1037 MonoTableInfo *tables = image->tables;
1039 guint32 nindex, class, sig_idx;
1041 MonoMethodSignature *sig;
1044 mono_error_init (error);
1046 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1047 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1048 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1049 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1050 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1052 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1055 * Whether we actually used the `typespec_context' or not.
1056 * This is used to tell our caller whether or not it's safe to insert the returned
1057 * method into a cache.
1060 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
1063 case MONO_MEMBERREF_PARENT_TYPEREF:
1064 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1068 case MONO_MEMBERREF_PARENT_TYPESPEC:
1070 * Parse the TYPESPEC in the parent's context.
1072 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1076 case MONO_MEMBERREF_PARENT_TYPEDEF:
1077 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1081 case MONO_MEMBERREF_PARENT_METHODDEF: {
1082 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1088 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class, nindex);
1093 mono_class_init (klass);
1095 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1097 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1098 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1102 ptr = mono_metadata_blob_heap (image, sig_idx);
1103 mono_metadata_decode_blob_size (ptr, &ptr);
1105 sig = find_cached_memberref_sig (image, sig_idx);
1107 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1111 sig = cache_memberref_sig (image, sig_idx, sig);
1115 case MONO_MEMBERREF_PARENT_TYPEREF:
1116 case MONO_MEMBERREF_PARENT_TYPEDEF:
1117 method = find_method (klass, NULL, mname, sig, klass, error);
1120 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1123 type = &klass->byval_arg;
1125 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1126 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1127 method = find_method (in_class, NULL, mname, sig, klass, error);
1131 /* we're an array and we created these methods already in klass in mono_class_init () */
1132 method = mono_method_search_in_array_class (klass, mname, sig);
1136 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class, nindex);
1140 if (!method && mono_error_ok (error)) {
1141 char *msig = mono_signature_get_desc (sig, FALSE);
1142 GString *s = g_string_new (mname);
1143 if (sig->generic_param_count)
1144 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1145 g_string_append_printf (s, "(%s)", msig);
1147 msig = g_string_free (s, FALSE);
1149 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1150 mono_error_set_from_loader_error (error);
1152 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1157 mono_loader_assert_no_error ();
1161 mono_loader_assert_no_error ();
1162 g_assert (!mono_error_ok (error));
1167 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1171 MonoTableInfo *tables = image->tables;
1172 MonoGenericContext new_context;
1173 MonoGenericInst *inst;
1175 guint32 cols [MONO_METHODSPEC_SIZE];
1176 guint32 token, nindex, param_count;
1178 mono_error_init (error);
1180 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1181 token = cols [MONO_METHODSPEC_METHOD];
1182 nindex = token >> MONO_METHODDEFORREF_BITS;
1184 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1185 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1189 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1191 mono_metadata_decode_value (ptr, &ptr);
1193 param_count = mono_metadata_decode_value (ptr, &ptr);
1195 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1197 mono_loader_assert_no_error ();
1198 mono_error_set_bad_image (error, image, "Cannot parse generic instance for methodspec 0x%08x", idx);
1202 if (context && inst->is_open) {
1203 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1204 if (!mono_error_ok (error))
1208 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1209 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1213 method = method_from_memberref (image, nindex, context, NULL, error);
1219 klass = method->klass;
1221 if (klass->generic_class) {
1222 g_assert (method->is_inflated);
1223 method = ((MonoMethodInflated *) method)->declaring;
1226 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1227 new_context.method_inst = inst;
1229 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1230 mono_loader_assert_no_error ();
1234 struct _MonoDllMap {
1242 static MonoDllMap *global_dll_map;
1245 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1253 global_loader_data_lock ();
1256 * we use the first entry we find that matches, since entries from
1257 * the config file are prepended to the list and we document that the
1258 * later entries win.
1260 for (; dll_map; dll_map = dll_map->next) {
1261 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1262 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1264 } else if (strcmp (dll_map->dll, dll)) {
1267 if (!found && dll_map->target) {
1268 *rdll = dll_map->target;
1270 /* we don't quit here, because we could find a full
1271 * entry that matches also function and that has priority.
1274 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1275 *rfunc = dll_map->target_func;
1280 global_loader_data_unlock ();
1285 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1288 if (assembly && assembly->dll_map) {
1289 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1293 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1297 * mono_dllmap_insert:
1298 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1299 * @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
1300 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1301 * @tdll: The name of the library to map the specified @dll if it matches.
1302 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1304 * LOCKING: Acquires the loader lock.
1306 * This function is used to programatically add DllImport remapping in either
1307 * a specific assembly, or as a global remapping. This is done by remapping
1308 * references in a DllImport attribute from the @dll library name into the @tdll
1309 * name. If the @dll name contains the prefix "i:", the comparison of the
1310 * library name is done without case sensitivity.
1312 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1313 * or the name of the function as determined by DllImport. If you pass @func, you
1314 * must also pass @tfunc which is the name of the target function to invoke on a match.
1317 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1319 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1320 * the contents of relocated_demo_path for all assemblies in the Mono process.
1322 * NOTE: This can be called before the runtime is initialized, for example from
1323 * mono_config_parse ().
1326 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1330 mono_loader_init ();
1333 entry = g_malloc0 (sizeof (MonoDllMap));
1334 entry->dll = dll? g_strdup (dll): NULL;
1335 entry->target = tdll? g_strdup (tdll): NULL;
1336 entry->func = func? g_strdup (func): NULL;
1337 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1339 global_loader_data_lock ();
1340 entry->next = global_dll_map;
1341 global_dll_map = entry;
1342 global_loader_data_unlock ();
1344 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1345 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1346 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1347 entry->func = func? mono_image_strdup (assembly, func): NULL;
1348 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1350 mono_image_lock (assembly);
1351 entry->next = assembly->dll_map;
1352 assembly->dll_map = entry;
1353 mono_image_unlock (assembly);
1358 free_dllmap (MonoDllMap *map)
1361 MonoDllMap *next = map->next;
1364 g_free (map->target);
1366 g_free (map->target_func);
1373 dllmap_cleanup (void)
1375 free_dllmap (global_dll_map);
1376 global_dll_map = NULL;
1379 static GHashTable *global_module_map;
1382 cached_module_load (const char *name, int flags, char **err)
1388 global_loader_data_lock ();
1389 if (!global_module_map)
1390 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1391 res = g_hash_table_lookup (global_module_map, name);
1393 global_loader_data_unlock ();
1396 res = mono_dl_open (name, flags, err);
1398 g_hash_table_insert (global_module_map, g_strdup (name), res);
1399 global_loader_data_unlock ();
1403 static MonoDl *internal_module;
1406 is_absolute_path (const char *path)
1408 #ifdef PLATFORM_MACOSX
1409 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1410 !strncmp (path, "@rpath/", 7))
1413 return g_path_is_absolute (path);
1417 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1419 MonoImage *image = method->klass->image;
1420 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1421 MonoTableInfo *tables = image->tables;
1422 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1423 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1424 guint32 im_cols [MONO_IMPLMAP_SIZE];
1425 guint32 scope_token;
1426 const char *import = NULL;
1427 const char *orig_scope;
1428 const char *new_scope;
1430 char *full_name, *file_name, *found_name = NULL;
1432 MonoDl *module = NULL;
1433 gboolean cached = FALSE;
1435 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1443 return piinfo->addr;
1445 if (image_is_dynamic (method->klass->image)) {
1446 MonoReflectionMethodAux *method_aux =
1447 g_hash_table_lookup (
1448 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1452 import = method_aux->dllentry;
1453 orig_scope = method_aux->dll;
1456 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1459 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1461 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1464 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1465 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1466 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1467 orig_scope = mono_metadata_string_heap (image, scope_token);
1470 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1473 mono_image_lock (image);
1474 if (!image->pinvoke_scopes) {
1475 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1476 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1478 module = g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1479 found_name = g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1480 mono_image_unlock (image);
1484 found_name = g_strdup (found_name);
1488 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1489 "DllImport attempting to load: '%s'.", new_scope);
1491 /* we allow a special name to dlopen from the running process namespace */
1492 if (strcmp (new_scope, "__Internal") == 0){
1493 if (internal_module == NULL)
1494 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1495 module = internal_module;
1500 * Try loading the module using a variety of names
1502 for (i = 0; i < 4; ++i) {
1503 char *base_name = NULL, *dir_name = NULL;
1504 gboolean is_absolute = is_absolute_path (new_scope);
1508 /* Try the original name */
1509 file_name = g_strdup (new_scope);
1512 /* Try trimming the .dll extension */
1513 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1514 file_name = g_strdup (new_scope);
1515 file_name [strlen (new_scope) - 4] = '\0';
1522 dir_name = g_path_get_dirname (new_scope);
1523 base_name = g_path_get_basename (new_scope);
1524 if (strstr (base_name, "lib") != base_name) {
1525 char *tmp = g_strdup_printf ("lib%s", base_name);
1528 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1531 } else if (strstr (new_scope, "lib") != new_scope) {
1532 file_name = g_strdup_printf ("lib%s", new_scope);
1537 #ifndef TARGET_WIN32
1538 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1539 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1540 !g_ascii_strcasecmp ("user32", new_scope) ||
1541 !g_ascii_strcasecmp ("kernel", new_scope)) {
1542 file_name = g_strdup ("libMonoSupportW.so");
1546 #ifndef TARGET_WIN32
1553 dir_name = g_path_get_dirname (file_name);
1555 base_name = g_path_get_basename (file_name);
1558 if (!module && is_absolute) {
1559 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1561 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1562 "DllImport error loading library '%s': '%s'.",
1563 file_name, error_msg);
1566 found_name = g_strdup (file_name);
1570 if (!module && !is_absolute) {
1572 char *mdirname = g_path_get_dirname (image->name);
1573 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1574 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1576 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1577 "DllImport error loading library '%s': '%s'.",
1578 full_name, error_msg);
1581 found_name = g_strdup (full_name);
1592 char *file_or_base = is_absolute ? base_name : file_name;
1593 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1594 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1596 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1597 "DllImport error loading library '%s': '%s'.",
1598 full_name, error_msg);
1601 found_name = g_strdup (full_name);
1610 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1612 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1613 "DllImport error loading library '%s': '%s'.",
1614 file_name, error_msg);
1616 found_name = g_strdup (file_name);
1631 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1632 "DllImport unable to load library '%s'.",
1637 *exc_class = "DllNotFoundException";
1638 *exc_arg = new_scope;
1644 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1645 "DllImport loaded library '%s'.", found_name);
1646 mono_image_lock (image);
1647 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1648 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1649 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1651 mono_image_unlock (image);
1654 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1655 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1656 g_free (found_name);
1659 if (import && import [0] == '#' && isdigit (import [1])) {
1663 id = strtol (import + 1, &end, 10);
1664 if (id > 0 && *end == '\0')
1668 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1669 "Searching for '%s'.", import);
1671 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1672 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1674 char *mangled_name = NULL, *mangled_name2 = NULL;
1677 int mangle_param_count;
1683 * Search using a variety of mangled names
1685 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1686 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1687 gboolean need_param_count = FALSE;
1689 if (mangle_stdcall > 0)
1690 need_param_count = TRUE;
1692 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1697 mangled_name = (char*)import;
1698 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1699 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1700 /* Try the mangled name first */
1701 if (mangle_charset == 0)
1702 mangled_name = g_strconcat (import, "W", NULL);
1704 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1706 if (mangle_charset == 0)
1707 mangled_name = g_strconcat (import, "W", NULL);
1709 /* Try the mangled name last */
1710 if (mangle_charset == 1)
1711 mangled_name = g_strconcat (import, "A", NULL);
1714 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1716 /* Try the mangled name last */
1717 if (mangle_charset == 1)
1718 mangled_name = g_strconcat (import, "A", NULL);
1723 if (mangle_param_count == 0)
1724 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1726 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1727 param_count = mangle_param_count;
1729 /* Try the stdcall mangled name */
1731 * gcc under windows creates mangled names without the underscore, but MS.NET
1732 * doesn't support it, so we doesn't support it either.
1734 if (mangle_stdcall == 1)
1735 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1737 mangled_name2 = mangled_name;
1739 mangled_name2 = mangled_name;
1742 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1743 "Probing '%s'.", mangled_name2);
1745 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1748 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1749 "Found as '%s'.", mangled_name2);
1751 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1752 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1757 if (mangled_name != mangled_name2)
1758 g_free (mangled_name2);
1759 if (mangled_name != import)
1760 g_free (mangled_name);
1766 if (!piinfo->addr) {
1769 *exc_class = "EntryPointNotFoundException";
1774 return piinfo->addr;
1778 * LOCKING: assumes the loader lock to be taken.
1781 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1782 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1785 int table = mono_metadata_token_table (token);
1786 int idx = mono_metadata_token_index (token);
1787 MonoTableInfo *tables = image->tables;
1788 MonoGenericContainer *generic_container = NULL, *container = NULL;
1789 const char *sig = NULL;
1790 guint32 cols [MONO_TYPEDEF_SIZE];
1792 mono_error_init (error);
1794 if (image_is_dynamic (image)) {
1795 MonoClass *handle_class;
1797 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1798 mono_loader_assert_no_error ();
1800 // This checks the memberref type as well
1801 if (result && handle_class != mono_defaults.methodhandle_class) {
1802 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1808 if (table != MONO_TABLE_METHOD) {
1809 if (table == MONO_TABLE_METHODSPEC) {
1810 if (used_context) *used_context = TRUE;
1811 return method_from_methodspec (image, context, idx, error);
1813 if (table != MONO_TABLE_MEMBERREF) {
1814 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1817 return method_from_memberref (image, idx, context, used_context, error);
1820 if (used_context) *used_context = FALSE;
1822 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1823 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1828 guint32 type = mono_metadata_typedef_from_method (image, token);
1830 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1833 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1838 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1840 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1841 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1842 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1844 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1845 methods_size += sizeof (MonoMethod);
1848 mono_stats.method_count ++;
1851 result->klass = klass;
1852 result->flags = cols [2];
1853 result->iflags = cols [1];
1854 result->token = token;
1855 result->name = mono_metadata_string_heap (image, cols [3]);
1857 if (!sig) /* already taken from the methodref */
1858 sig = mono_metadata_blob_heap (image, cols [4]);
1859 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1861 container = klass->generic_container;
1864 * load_generic_params does a binary search so only call it if the method
1868 generic_container = mono_metadata_load_generic_params (image, token, container);
1869 mono_loader_assert_no_error (); /* FIXME don't swallow this error. */
1871 if (generic_container) {
1872 result->is_generic = TRUE;
1873 generic_container->owner.method = result;
1874 /*FIXME put this before the image alloc*/
1875 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1878 container = generic_container;
1881 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1882 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1883 result->string_ctor = 1;
1884 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1885 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1888 /* IJW is P/Invoke with a predefined function pointer. */
1889 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1890 piinfo->addr = mono_image_rva_map (image, cols [0]);
1891 g_assert (piinfo->addr);
1894 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1895 /* Native methods can have no map. */
1896 if (piinfo->implmap_idx)
1897 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1900 if (generic_container)
1901 mono_method_set_generic_container (result, generic_container);
1903 mono_loader_assert_no_error ();
1908 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1910 return mono_get_method_full (image, token, klass, NULL);
1914 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1915 MonoGenericContext *context)
1918 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
1919 mono_loader_assert_no_error ();
1920 if (!mono_error_ok (&error)) {
1921 mono_loader_set_error_from_mono_error (&error);
1922 mono_error_cleanup (&error);
1928 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
1930 MonoMethod *result = NULL;
1931 gboolean used_context = FALSE;
1933 /* We do everything inside the lock to prevent creation races */
1935 mono_error_init (error);
1937 mono_image_lock (image);
1939 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1940 if (!image->method_cache)
1941 image->method_cache = g_hash_table_new (NULL, NULL);
1942 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1943 } else if (!image_is_dynamic (image)) {
1944 if (!image->methodref_cache)
1945 image->methodref_cache = g_hash_table_new (NULL, NULL);
1946 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1948 mono_image_unlock (image);
1954 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
1958 mono_image_lock (image);
1959 if (!used_context && !result->is_inflated) {
1960 MonoMethod *result2 = NULL;
1962 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1963 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1964 else if (!image_is_dynamic (image))
1965 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1968 mono_image_unlock (image);
1972 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1973 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1974 else if (!image_is_dynamic (image))
1975 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1978 mono_image_unlock (image);
1984 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
1987 MonoClass *ic = NULL;
1988 MonoGenericContext *method_context = NULL;
1989 MonoMethodSignature *sig, *original_sig;
1991 mono_error_init (error);
1993 mono_class_init (constrained_class);
1994 original_sig = sig = mono_method_signature_checked (method, error);
1999 if (method->is_inflated && sig->generic_param_count) {
2000 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2001 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
2004 method_context = mono_method_get_context (method);
2008 * We must inflate the signature with the class instantiation to work on
2009 * cases where a class inherit from a generic type and the override replaces
2010 * any type argument which a concrete type. See #325283.
2012 if (method_context->class_inst) {
2013 MonoGenericContext ctx;
2014 ctx.method_inst = NULL;
2015 ctx.class_inst = method_context->class_inst;
2016 /*Fixme, property propagate this error*/
2017 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2023 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2026 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2027 if (sig != original_sig)
2028 mono_metadata_free_inflated_signature (sig);
2033 if (method_context) {
2034 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2043 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2044 MonoGenericContext *context, MonoError *error)
2048 return get_method_constrained (image, method, constrained_class, context, error);
2052 * mono_get_method_constrained:
2054 * This is used when JITing the `constrained.' opcode.
2056 * This returns two values: the contrained method, which has been inflated
2057 * as the function return value; And the original CIL-stream method as
2058 * declared in cil_method. The later is used for verification.
2061 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2062 MonoGenericContext *context, MonoMethod **cil_method)
2065 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2067 mono_loader_assert_no_error ();
2068 if (!mono_error_ok (&error)) {
2069 mono_loader_set_error_from_mono_error (&error);
2070 mono_error_cleanup (&error);
2076 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2078 mono_error_init (error);
2080 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2084 return get_method_constrained (image, *cil_method, constrained_class, context, error);
2088 mono_free_method (MonoMethod *method)
2090 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2091 mono_profiler_method_free (method);
2093 /* FIXME: This hack will go away when the profiler will support freeing methods */
2094 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2097 if (method->signature) {
2099 * FIXME: This causes crashes because the types inside signatures and
2100 * locals are shared.
2102 /* mono_metadata_free_method_signature (method->signature); */
2103 /* g_free (method->signature); */
2106 if (method_is_dynamic (method)) {
2107 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2110 mono_marshal_free_dynamic_wrappers (method);
2112 mono_image_property_remove (method->klass->image, method);
2114 g_free ((char*)method->name);
2116 g_free ((char*)mw->header->code);
2117 for (i = 0; i < mw->header->num_locals; ++i)
2118 g_free (mw->header->locals [i]);
2119 g_free (mw->header->clauses);
2120 g_free (mw->header);
2122 g_free (mw->method_data);
2123 g_free (method->signature);
2129 mono_method_get_param_names (MonoMethod *method, const char **names)
2133 MonoTableInfo *methodt;
2134 MonoTableInfo *paramt;
2135 MonoMethodSignature *signature;
2138 if (method->is_inflated)
2139 method = ((MonoMethodInflated *) method)->declaring;
2141 signature = mono_method_signature (method);
2142 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2143 number of arguments and allocate a properly sized array. */
2144 if (signature == NULL)
2147 if (!signature->param_count)
2150 for (i = 0; i < signature->param_count; ++i)
2153 klass = method->klass;
2157 mono_class_init (klass);
2159 if (image_is_dynamic (klass->image)) {
2160 MonoReflectionMethodAux *method_aux =
2161 g_hash_table_lookup (
2162 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2163 if (method_aux && method_aux->param_names) {
2164 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2165 if (method_aux->param_names [i + 1])
2166 names [i] = method_aux->param_names [i + 1];
2171 if (method->wrapper_type) {
2172 char **pnames = NULL;
2174 mono_image_lock (klass->image);
2175 if (klass->image->wrapper_param_names)
2176 pnames = g_hash_table_lookup (klass->image->wrapper_param_names, method);
2177 mono_image_unlock (klass->image);
2180 for (i = 0; i < signature->param_count; ++i)
2181 names [i] = pnames [i];
2186 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2187 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2188 idx = mono_method_get_index (method);
2190 guint32 cols [MONO_PARAM_SIZE];
2193 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2195 if (idx < methodt->rows)
2196 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2198 lastp = paramt->rows + 1;
2199 for (i = param_index; i < lastp; ++i) {
2200 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2201 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2202 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2208 mono_method_get_param_token (MonoMethod *method, int index)
2210 MonoClass *klass = method->klass;
2211 MonoTableInfo *methodt;
2214 mono_class_init (klass);
2216 if (image_is_dynamic (klass->image))
2217 g_assert_not_reached ();
2219 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2220 idx = mono_method_get_index (method);
2222 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2226 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2228 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2235 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2238 MonoClass *klass = method->klass;
2239 MonoTableInfo *methodt;
2240 MonoTableInfo *paramt;
2241 MonoMethodSignature *signature;
2244 signature = mono_method_signature (method);
2245 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2247 for (i = 0; i < signature->param_count + 1; ++i)
2250 if (image_is_dynamic (method->klass->image)) {
2251 MonoReflectionMethodAux *method_aux =
2252 g_hash_table_lookup (
2253 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2254 if (method_aux && method_aux->param_marshall) {
2255 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2256 for (i = 0; i < signature->param_count + 1; ++i)
2257 if (dyn_specs [i]) {
2258 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2259 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2260 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2261 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2267 mono_class_init (klass);
2269 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2270 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2271 idx = mono_method_get_index (method);
2273 guint32 cols [MONO_PARAM_SIZE];
2274 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2276 if (idx < methodt->rows)
2277 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2279 lastp = paramt->rows + 1;
2281 for (i = param_index; i < lastp; ++i) {
2282 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2284 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2286 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2288 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2297 mono_method_has_marshal_info (MonoMethod *method)
2300 MonoClass *klass = method->klass;
2301 MonoTableInfo *methodt;
2302 MonoTableInfo *paramt;
2305 if (image_is_dynamic (method->klass->image)) {
2306 MonoReflectionMethodAux *method_aux =
2307 g_hash_table_lookup (
2308 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2309 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2311 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2318 mono_class_init (klass);
2320 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2321 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2322 idx = mono_method_get_index (method);
2324 guint32 cols [MONO_PARAM_SIZE];
2325 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2327 if (idx + 1 < methodt->rows)
2328 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2330 lastp = paramt->rows + 1;
2332 for (i = param_index; i < lastp; ++i) {
2333 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2335 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2344 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2347 g_assert (method != NULL);
2348 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2350 if (method->is_inflated)
2351 method = ((MonoMethodInflated *) method)->declaring;
2352 data = ((MonoMethodWrapper *)method)->method_data;
2353 g_assert (data != NULL);
2354 g_assert (id <= GPOINTER_TO_UINT (*data));
2361 } StackWalkUserData;
2364 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2366 StackWalkUserData *d = data;
2368 switch (frame->type) {
2369 case FRAME_TYPE_DEBUGGER_INVOKE:
2370 case FRAME_TYPE_MANAGED_TO_NATIVE:
2372 case FRAME_TYPE_MANAGED:
2373 g_assert (frame->ji);
2374 return d->func (mono_jit_info_get_method (frame->ji), frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2377 g_assert_not_reached ();
2383 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2385 StackWalkUserData ud = { func, user_data };
2386 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2390 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2392 StackWalkUserData ud = { func, user_data };
2393 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2397 MonoStackWalkAsyncSafe func;
2399 } AsyncStackWalkUserData;
2403 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2405 AsyncStackWalkUserData *d = data;
2407 switch (frame->type) {
2408 case FRAME_TYPE_DEBUGGER_INVOKE:
2409 case FRAME_TYPE_MANAGED_TO_NATIVE:
2411 case FRAME_TYPE_MANAGED:
2414 if (frame->ji->async)
2415 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2417 return d->func (mono_jit_info_get_method (frame->ji), frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2420 g_assert_not_reached ();
2427 * mono_stack_walk_async_safe:
2429 * Async safe version callable from signal handlers.
2432 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2435 AsyncStackWalkUserData ud = { func, user_data };
2437 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2438 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2442 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2444 MonoMethod **dest = data;
2446 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2452 mono_method_get_last_managed (void)
2454 MonoMethod *m = NULL;
2455 mono_stack_walk_no_il (last_managed, &m);
2459 static gboolean loader_lock_track_ownership = FALSE;
2464 * See docs/thread-safety.txt for the locking strategy.
2467 mono_loader_lock (void)
2470 mono_locks_acquire (&loader_mutex, LoaderLock);
2471 MONO_FINISH_TRY_BLOCKING
2473 if (G_UNLIKELY (loader_lock_track_ownership)) {
2474 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));
2479 mono_loader_unlock (void)
2481 mono_locks_release (&loader_mutex, LoaderLock);
2482 if (G_UNLIKELY (loader_lock_track_ownership)) {
2483 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));
2488 * mono_loader_lock_track_ownership:
2490 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2491 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2492 * thread owns the loader lock.
2495 mono_loader_lock_track_ownership (gboolean track)
2497 loader_lock_track_ownership = track;
2501 * mono_loader_lock_is_owned_by_self:
2503 * Return whenever the current thread owns the loader lock.
2504 * This is useful to avoid blocking operations while holding the loader lock.
2507 mono_loader_lock_is_owned_by_self (void)
2509 g_assert (loader_lock_track_ownership);
2511 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2515 * mono_loader_lock_if_inited:
2517 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2518 * be used in runtime initialization code which can be executed before mono_loader_init ().
2521 mono_loader_lock_if_inited (void)
2523 if (loader_lock_inited)
2524 mono_loader_lock ();
2528 mono_loader_unlock_if_inited (void)
2530 if (loader_lock_inited)
2531 mono_loader_unlock ();
2535 * mono_method_signature:
2537 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2539 MonoMethodSignature*
2540 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2545 gboolean can_cache_signature;
2546 MonoGenericContainer *container;
2547 MonoMethodSignature *signature = NULL, *sig2;
2550 /* We need memory barriers below because of the double-checked locking pattern */
2552 mono_error_init (error);
2555 return m->signature;
2557 img = m->klass->image;
2559 if (m->is_inflated) {
2560 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2561 /* the lock is recursive */
2562 signature = mono_method_signature (imethod->declaring);
2563 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2564 if (!mono_error_ok (error))
2567 inflated_signatures_size += mono_metadata_signature_size (signature);
2569 mono_image_lock (img);
2571 mono_memory_barrier ();
2573 m->signature = signature;
2575 mono_image_unlock (img);
2577 return m->signature;
2580 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2581 idx = mono_metadata_token_index (m->token);
2583 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2585 g_assert (!m->klass->generic_class);
2586 container = mono_method_get_generic_container (m);
2588 container = m->klass->generic_container;
2590 /* Generic signatures depend on the container so they cannot be cached */
2591 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2592 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2594 /* If the method has parameter attributes, that can modify the signature */
2595 if (mono_metadata_method_has_param_attrs (img, idx))
2596 can_cache_signature = FALSE;
2598 if (can_cache_signature) {
2599 mono_image_lock (img);
2600 signature = g_hash_table_lookup (img->method_signatures, sig);
2601 mono_image_unlock (img);
2605 const char *sig_body;
2606 /*TODO we should cache the failure result somewhere*/
2607 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2610 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2612 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2616 if (can_cache_signature) {
2617 mono_image_lock (img);
2618 sig2 = g_hash_table_lookup (img->method_signatures, sig);
2620 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2621 mono_image_unlock (img);
2624 signatures_size += mono_metadata_signature_size (signature);
2627 /* Verify metadata consistency */
2628 if (signature->generic_param_count) {
2629 if (!container || !container->is_method) {
2630 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);
2633 if (container->type_argc != signature->generic_param_count) {
2634 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);
2637 } else if (container && container->is_method && container->type_argc) {
2638 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);
2641 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2642 signature->pinvoke = 1;
2643 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2644 MonoCallConvention conv = 0;
2645 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2646 signature->pinvoke = 1;
2648 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2649 case 0: /* no call conv, so using default */
2650 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2651 conv = MONO_CALL_DEFAULT;
2653 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2656 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2657 conv = MONO_CALL_STDCALL;
2659 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2660 conv = MONO_CALL_THISCALL;
2662 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2663 conv = MONO_CALL_FASTCALL;
2665 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2666 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2668 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);
2671 signature->call_convention = conv;
2674 mono_image_lock (img);
2676 mono_memory_barrier ();
2678 m->signature = signature;
2680 mono_image_unlock (img);
2682 return m->signature;
2686 * mono_method_signature:
2688 * Return the signature of the method M. On failure, returns NULL.
2690 MonoMethodSignature*
2691 mono_method_signature (MonoMethod *m)
2694 MonoMethodSignature *sig;
2696 sig = mono_method_signature_checked (m, &error);
2698 char *type_name = mono_type_get_full_name (m->klass);
2699 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2701 mono_error_cleanup (&error);
2708 mono_method_get_name (MonoMethod *method)
2710 return method->name;
2714 mono_method_get_class (MonoMethod *method)
2716 return method->klass;
2720 mono_method_get_token (MonoMethod *method)
2722 return method->token;
2726 mono_method_get_header (MonoMethod *method)
2732 MonoMethodHeader *header;
2733 MonoGenericContainer *container;
2735 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))
2738 img = method->klass->image;
2740 if (method->is_inflated) {
2741 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2742 MonoMethodHeader *header, *iheader;
2744 header = mono_method_get_header (imethod->declaring);
2748 iheader = inflate_generic_header (header, mono_method_get_context (method));
2749 mono_metadata_free_mh (header);
2751 mono_image_lock (img);
2753 if (imethod->header) {
2754 mono_metadata_free_mh (iheader);
2755 mono_image_unlock (img);
2756 return imethod->header;
2759 mono_memory_barrier ();
2760 imethod->header = iheader;
2762 mono_image_unlock (img);
2764 return imethod->header;
2767 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2768 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2769 g_assert (mw->header);
2774 * We don't need locks here: the new header is allocated from malloc memory
2775 * and is not stored anywhere in the runtime, the user needs to free it.
2777 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2778 idx = mono_metadata_token_index (method->token);
2779 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2781 if (!mono_verifier_verify_method_header (img, rva, NULL))
2784 loc = mono_image_rva_map (img, rva);
2789 * When parsing the types of local variables, we must pass any container available
2790 * to ensure that both VAR and MVAR will get the right owner.
2792 container = mono_method_get_generic_container (method);
2794 container = method->klass->generic_container;
2795 header = mono_metadata_parse_mh_full (img, container, loc);
2801 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2804 *iflags = method->iflags;
2805 return method->flags;
2809 * Find the method index in the metadata methodDef table.
2812 mono_method_get_index (MonoMethod *method)
2814 MonoClass *klass = method->klass;
2818 /* constructed array methods are not in the MethodDef table */
2822 return mono_metadata_token_index (method->token);
2824 mono_class_setup_methods (klass);
2825 if (klass->exception_type)
2827 for (i = 0; i < klass->method.count; ++i) {
2828 if (method == klass->methods [i]) {
2829 if (klass->image->uncompressed_metadata)
2830 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2832 return klass->method.first + i + 1;