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_image_lock (image);
605 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
606 mono_image_unlock (image);
609 mono_loader_assert_no_error ();
614 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
618 if (sig1->hasthis != sig2->hasthis ||
619 sig1->sentinelpos != sig2->sentinelpos)
622 for (i = 0; i < sig1->sentinelpos; i++) {
623 MonoType *p1 = sig1->params[i];
624 MonoType *p2 = sig2->params[i];
626 /*if (p1->attrs != p2->attrs)
629 if (!mono_metadata_type_equal (p1, p2))
633 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
639 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
640 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
644 /* Search directly in the metadata to avoid calling setup_methods () */
645 mono_error_init (error);
647 /* FIXME: !from_class->generic_class condition causes test failures. */
648 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
649 for (i = 0; i < klass->method.count; ++i) {
650 guint32 cols [MONO_METHOD_SIZE];
653 MonoMethodSignature *other_sig;
655 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
657 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
659 if (!((fqname && !strcmp (m_name, fqname)) ||
660 (qname && !strcmp (m_name, qname)) ||
661 (name && !strcmp (m_name, name))))
664 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
665 if (!mono_error_ok (error)) //bail out if we hit a loader error
668 other_sig = mono_method_signature_checked (method, error);
669 if (!mono_error_ok (error)) //bail out if we hit a loader error
671 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
677 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
679 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
680 See mono/tests/generic-type-load-exception.2.il
681 FIXME we should better report this error to the caller
683 if (!klass->methods || klass->exception_type) {
684 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
688 for (i = 0; i < klass->method.count; ++i) {
689 MonoMethod *m = klass->methods [i];
690 MonoMethodSignature *msig;
692 /* We must cope with failing to load some of the types. */
696 if (!((fqname && !strcmp (m->name, fqname)) ||
697 (qname && !strcmp (m->name, qname)) ||
698 (name && !strcmp (m->name, name))))
700 msig = mono_method_signature_checked (m, error);
701 if (!mono_error_ok (error)) //bail out if we hit a loader error
707 if (sig->call_convention == MONO_CALL_VARARG) {
708 if (mono_metadata_signature_vararg_match (sig, msig))
711 if (mono_metadata_signature_equal (sig, msig))
716 if (i < klass->method.count)
717 return mono_class_get_method_by_index (from_class, i);
722 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
725 char *qname, *fqname, *class_name;
726 gboolean is_interface;
727 MonoMethod *result = NULL;
728 MonoClass *initial_class = in_class;
730 mono_error_init (error);
731 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
734 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
736 qname = g_strconcat (class_name, ".", name, NULL);
737 if (ic->name_space && ic->name_space [0])
738 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
742 class_name = qname = fqname = NULL;
745 g_assert (from_class);
746 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
747 if (result || !mono_error_ok (error))
750 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
754 * This happens when we fail to lazily load the interfaces of one of the types.
755 * On such case we can't just bail out since user code depends on us trying harder.
757 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
758 in_class = in_class->parent;
759 from_class = from_class->parent;
763 for (i = 0; i < in_class->interface_offsets_count; i++) {
764 MonoClass *in_ic = in_class->interfaces_packed [i];
765 MonoClass *from_ic = from_class->interfaces_packed [i];
766 char *ic_qname, *ic_fqname, *ic_class_name;
768 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
769 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
770 if (in_ic->name_space && in_ic->name_space [0])
771 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
775 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
776 g_free (ic_class_name);
779 if (result || !mono_error_ok (error))
783 in_class = in_class->parent;
784 from_class = from_class->parent;
786 g_assert (!in_class == !from_class);
789 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
791 //we did not find the method
792 if (!result && mono_error_ok (error)) {
793 char *desc = mono_signature_get_desc (sig, FALSE);
794 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
805 static MonoMethodSignature*
806 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
808 MonoMethodSignature *res;
812 mono_error_init (error);
816 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
817 res->param_count = sig->param_count;
818 res->sentinelpos = -1;
819 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
820 if (!mono_error_ok (error))
822 is_open = mono_class_is_open_constructed_type (res->ret);
823 for (i = 0; i < sig->param_count; ++i) {
824 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
825 if (!mono_error_ok (error))
829 is_open = mono_class_is_open_constructed_type (res->params [i]);
831 res->hasthis = sig->hasthis;
832 res->explicit_this = sig->explicit_this;
833 res->call_convention = sig->call_convention;
834 res->pinvoke = sig->pinvoke;
835 res->generic_param_count = sig->generic_param_count;
836 res->sentinelpos = sig->sentinelpos;
837 res->has_type_parameters = is_open;
838 res->is_inflated = 1;
843 mono_metadata_free_type (res->ret);
844 for (i = 0; i < sig->param_count; ++i) {
846 mono_metadata_free_type (res->params [i]);
853 * mono_inflate_generic_signature:
855 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
858 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
860 MonoMethodSignature *res, *cached;
862 res = inflate_generic_signature_checked (NULL, sig, context, error);
863 if (!mono_error_ok (error))
865 cached = mono_metadata_get_inflated_signature (res, context);
867 mono_metadata_free_inflated_signature (res);
871 static MonoMethodHeader*
872 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
874 MonoMethodHeader *res;
876 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
877 res->code = header->code;
878 res->code_size = header->code_size;
879 res->max_stack = header->max_stack;
880 res->num_clauses = header->num_clauses;
881 res->init_locals = header->init_locals;
882 res->num_locals = header->num_locals;
883 res->clauses = header->clauses;
884 for (i = 0; i < header->num_locals; ++i)
885 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
886 if (res->num_clauses) {
887 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
888 for (i = 0; i < header->num_clauses; ++i) {
889 MonoExceptionClause *clause = &res->clauses [i];
890 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
892 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
899 * token is the method_ref/def/spec token used in a call IL instruction.
902 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
905 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
907 mono_loader_assert_no_error ();
910 g_assert (!mono_error_ok (&error));
911 mono_loader_set_error_from_mono_error (&error);
912 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
918 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
920 int table = mono_metadata_token_table (token);
921 int idx = mono_metadata_token_index (token);
923 guint32 cols [MONO_MEMBERREF_SIZE];
924 MonoMethodSignature *sig;
927 mono_error_init (error);
929 /* !table is for wrappers: we should really assign their own token to them */
930 if (!table || table == MONO_TABLE_METHOD)
931 return mono_method_signature_checked (method, error);
933 if (table == MONO_TABLE_METHODSPEC) {
934 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
935 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
938 return mono_method_signature_checked (method, error);
941 if (method->klass->generic_class)
942 return mono_method_signature_checked (method, error);
944 if (image_is_dynamic (image)) {
945 sig = mono_reflection_lookup_signature (image, method, token, error);
949 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
950 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
952 sig = find_cached_memberref_sig (image, sig_idx);
954 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
955 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
956 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
958 //FIXME include the verification error
959 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
963 ptr = mono_metadata_blob_heap (image, sig_idx);
964 mono_metadata_decode_blob_size (ptr, &ptr);
966 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
970 sig = cache_memberref_sig (image, sig_idx, sig);
972 /* FIXME: we probably should verify signature compat in the dynamic case too*/
973 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
974 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
975 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
977 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
983 MonoMethodSignature *cached;
985 /* This signature is not owned by a MonoMethod, so need to cache */
986 sig = inflate_generic_signature_checked (image, sig, context, error);
987 if (!mono_error_ok (error))
990 cached = mono_metadata_get_inflated_signature (sig, context);
992 mono_metadata_free_inflated_signature (sig);
994 inflated_signatures_size += mono_metadata_signature_size (cached);
998 g_assert (mono_error_ok (error));
1002 MonoMethodSignature*
1003 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
1006 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
1008 mono_loader_assert_no_error ();
1011 g_assert (!mono_error_ok (&error));
1012 mono_loader_set_error_from_mono_error (&error);
1013 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
1018 /* this is only for the typespec array methods */
1020 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1024 mono_class_setup_methods (klass);
1025 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
1026 for (i = 0; i < klass->method.count; ++i) {
1027 MonoMethod *method = klass->methods [i];
1028 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1035 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1036 gboolean *used_context, MonoError *error)
1038 MonoClass *klass = NULL;
1039 MonoMethod *method = NULL;
1040 MonoTableInfo *tables = image->tables;
1042 guint32 nindex, class, sig_idx;
1044 MonoMethodSignature *sig;
1047 mono_error_init (error);
1049 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1050 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1051 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1052 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1053 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1055 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1058 * Whether we actually used the `typespec_context' or not.
1059 * This is used to tell our caller whether or not it's safe to insert the returned
1060 * method into a cache.
1063 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
1066 case MONO_MEMBERREF_PARENT_TYPEREF:
1067 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1071 case MONO_MEMBERREF_PARENT_TYPESPEC:
1073 * Parse the TYPESPEC in the parent's context.
1075 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1079 case MONO_MEMBERREF_PARENT_TYPEDEF:
1080 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1084 case MONO_MEMBERREF_PARENT_METHODDEF: {
1085 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1091 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class, nindex);
1096 mono_class_init (klass);
1098 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1100 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1101 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1105 ptr = mono_metadata_blob_heap (image, sig_idx);
1106 mono_metadata_decode_blob_size (ptr, &ptr);
1108 sig = find_cached_memberref_sig (image, sig_idx);
1110 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1114 sig = cache_memberref_sig (image, sig_idx, sig);
1118 case MONO_MEMBERREF_PARENT_TYPEREF:
1119 case MONO_MEMBERREF_PARENT_TYPEDEF:
1120 method = find_method (klass, NULL, mname, sig, klass, error);
1123 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1126 type = &klass->byval_arg;
1128 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1129 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1130 method = find_method (in_class, NULL, mname, sig, klass, error);
1134 /* we're an array and we created these methods already in klass in mono_class_init () */
1135 method = mono_method_search_in_array_class (klass, mname, sig);
1139 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class, nindex);
1143 if (!method && mono_error_ok (error)) {
1144 char *msig = mono_signature_get_desc (sig, FALSE);
1145 GString *s = g_string_new (mname);
1146 if (sig->generic_param_count)
1147 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1148 g_string_append_printf (s, "(%s)", msig);
1150 msig = g_string_free (s, FALSE);
1152 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1153 mono_error_set_from_loader_error (error);
1155 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1160 mono_loader_assert_no_error ();
1164 mono_loader_assert_no_error ();
1165 g_assert (!mono_error_ok (error));
1170 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1174 MonoTableInfo *tables = image->tables;
1175 MonoGenericContext new_context;
1176 MonoGenericInst *inst;
1178 guint32 cols [MONO_METHODSPEC_SIZE];
1179 guint32 token, nindex, param_count;
1181 mono_error_init (error);
1183 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1184 token = cols [MONO_METHODSPEC_METHOD];
1185 nindex = token >> MONO_METHODDEFORREF_BITS;
1187 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1188 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1192 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1194 mono_metadata_decode_value (ptr, &ptr);
1196 param_count = mono_metadata_decode_value (ptr, &ptr);
1198 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1200 mono_loader_assert_no_error ();
1201 mono_error_set_bad_image (error, image, "Cannot parse generic instance for methodspec 0x%08x", idx);
1205 if (context && inst->is_open) {
1206 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1207 if (!mono_error_ok (error))
1211 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1212 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1216 method = method_from_memberref (image, nindex, context, NULL, error);
1222 klass = method->klass;
1224 if (klass->generic_class) {
1225 g_assert (method->is_inflated);
1226 method = ((MonoMethodInflated *) method)->declaring;
1229 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1230 new_context.method_inst = inst;
1232 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1233 mono_loader_assert_no_error ();
1237 struct _MonoDllMap {
1245 static MonoDllMap *global_dll_map;
1248 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1256 global_loader_data_lock ();
1259 * we use the first entry we find that matches, since entries from
1260 * the config file are prepended to the list and we document that the
1261 * later entries win.
1263 for (; dll_map; dll_map = dll_map->next) {
1264 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1265 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1267 } else if (strcmp (dll_map->dll, dll)) {
1270 if (!found && dll_map->target) {
1271 *rdll = dll_map->target;
1273 /* we don't quit here, because we could find a full
1274 * entry that matches also function and that has priority.
1277 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1278 *rfunc = dll_map->target_func;
1283 global_loader_data_unlock ();
1288 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1291 if (assembly && assembly->dll_map) {
1292 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1296 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1300 * mono_dllmap_insert:
1301 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1302 * @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
1303 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1304 * @tdll: The name of the library to map the specified @dll if it matches.
1305 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1307 * LOCKING: Acquires the loader lock.
1309 * This function is used to programatically add DllImport remapping in either
1310 * a specific assembly, or as a global remapping. This is done by remapping
1311 * references in a DllImport attribute from the @dll library name into the @tdll
1312 * name. If the @dll name contains the prefix "i:", the comparison of the
1313 * library name is done without case sensitivity.
1315 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1316 * or the name of the function as determined by DllImport. If you pass @func, you
1317 * must also pass @tfunc which is the name of the target function to invoke on a match.
1320 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1322 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1323 * the contents of relocated_demo_path for all assemblies in the Mono process.
1325 * NOTE: This can be called before the runtime is initialized, for example from
1326 * mono_config_parse ().
1329 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1333 mono_loader_init ();
1336 entry = g_malloc0 (sizeof (MonoDllMap));
1337 entry->dll = dll? g_strdup (dll): NULL;
1338 entry->target = tdll? g_strdup (tdll): NULL;
1339 entry->func = func? g_strdup (func): NULL;
1340 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1342 global_loader_data_lock ();
1343 entry->next = global_dll_map;
1344 global_dll_map = entry;
1345 global_loader_data_unlock ();
1347 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1348 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1349 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1350 entry->func = func? mono_image_strdup (assembly, func): NULL;
1351 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1353 mono_image_lock (assembly);
1354 entry->next = assembly->dll_map;
1355 assembly->dll_map = entry;
1356 mono_image_unlock (assembly);
1361 free_dllmap (MonoDllMap *map)
1364 MonoDllMap *next = map->next;
1367 g_free (map->target);
1369 g_free (map->target_func);
1376 dllmap_cleanup (void)
1378 free_dllmap (global_dll_map);
1379 global_dll_map = NULL;
1382 static GHashTable *global_module_map;
1385 cached_module_load (const char *name, int flags, char **err)
1391 global_loader_data_lock ();
1392 if (!global_module_map)
1393 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1394 res = g_hash_table_lookup (global_module_map, name);
1396 global_loader_data_unlock ();
1399 res = mono_dl_open (name, flags, err);
1401 g_hash_table_insert (global_module_map, g_strdup (name), res);
1402 global_loader_data_unlock ();
1406 static MonoDl *internal_module;
1409 is_absolute_path (const char *path)
1411 #ifdef PLATFORM_MACOSX
1412 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1413 !strncmp (path, "@rpath/", 7))
1416 return g_path_is_absolute (path);
1420 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1422 MonoImage *image = method->klass->image;
1423 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1424 MonoTableInfo *tables = image->tables;
1425 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1426 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1427 guint32 im_cols [MONO_IMPLMAP_SIZE];
1428 guint32 scope_token;
1429 const char *import = NULL;
1430 const char *orig_scope;
1431 const char *new_scope;
1433 char *full_name, *file_name, *found_name = NULL;
1435 MonoDl *module = NULL;
1436 gboolean cached = FALSE;
1438 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1446 return piinfo->addr;
1448 if (image_is_dynamic (method->klass->image)) {
1449 MonoReflectionMethodAux *method_aux =
1450 g_hash_table_lookup (
1451 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1455 import = method_aux->dllentry;
1456 orig_scope = method_aux->dll;
1459 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1462 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1464 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1467 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1468 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1469 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1470 orig_scope = mono_metadata_string_heap (image, scope_token);
1473 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1476 mono_image_lock (image);
1477 if (!image->pinvoke_scopes) {
1478 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1479 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1481 module = g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1482 found_name = g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1483 mono_image_unlock (image);
1487 found_name = g_strdup (found_name);
1491 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1492 "DllImport attempting to load: '%s'.", new_scope);
1494 /* we allow a special name to dlopen from the running process namespace */
1495 if (strcmp (new_scope, "__Internal") == 0){
1496 if (internal_module == NULL)
1497 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1498 module = internal_module;
1503 * Try loading the module using a variety of names
1505 for (i = 0; i < 5; ++i) {
1506 char *base_name = NULL, *dir_name = NULL;
1507 gboolean is_absolute = is_absolute_path (new_scope);
1511 /* Try the original name */
1512 file_name = g_strdup (new_scope);
1515 /* Try trimming the .dll extension */
1516 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1517 file_name = g_strdup (new_scope);
1518 file_name [strlen (new_scope) - 4] = '\0';
1525 dir_name = g_path_get_dirname (new_scope);
1526 base_name = g_path_get_basename (new_scope);
1527 if (strstr (base_name, "lib") != base_name) {
1528 char *tmp = g_strdup_printf ("lib%s", base_name);
1531 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1534 } else if (strstr (new_scope, "lib") != new_scope) {
1535 file_name = g_strdup_printf ("lib%s", new_scope);
1540 if (!is_absolute && mono_dl_get_system_dir ()) {
1541 dir_name = (char*)mono_dl_get_system_dir ();
1542 file_name = g_path_get_basename (new_scope);
1548 #ifndef TARGET_WIN32
1549 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1550 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1551 !g_ascii_strcasecmp ("user32", new_scope) ||
1552 !g_ascii_strcasecmp ("kernel", new_scope)) {
1553 file_name = g_strdup ("libMonoSupportW.so");
1557 #ifndef TARGET_WIN32
1564 dir_name = g_path_get_dirname (file_name);
1566 base_name = g_path_get_basename (file_name);
1569 if (!module && is_absolute) {
1570 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1572 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1573 "DllImport error loading library '%s': '%s'.",
1574 file_name, error_msg);
1577 found_name = g_strdup (file_name);
1581 if (!module && !is_absolute) {
1583 char *mdirname = g_path_get_dirname (image->name);
1584 while ((full_name = mono_dl_build_path (mdirname, file_name, &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);
1603 char *file_or_base = is_absolute ? base_name : file_name;
1604 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1605 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1607 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1608 "DllImport error loading library '%s': '%s'.",
1609 full_name, error_msg);
1612 found_name = g_strdup (full_name);
1621 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1623 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1624 "DllImport error loading library '%s': '%s'.",
1625 file_name, error_msg);
1627 found_name = g_strdup (file_name);
1642 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1643 "DllImport unable to load library '%s'.",
1648 *exc_class = "DllNotFoundException";
1649 *exc_arg = new_scope;
1655 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1656 "DllImport loaded library '%s'.", found_name);
1657 mono_image_lock (image);
1658 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1659 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1660 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1662 mono_image_unlock (image);
1665 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1666 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1667 g_free (found_name);
1670 if (import && import [0] == '#' && isdigit (import [1])) {
1674 id = strtol (import + 1, &end, 10);
1675 if (id > 0 && *end == '\0')
1679 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1680 "Searching for '%s'.", import);
1682 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1683 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1685 char *mangled_name = NULL, *mangled_name2 = NULL;
1688 int mangle_param_count;
1694 * Search using a variety of mangled names
1696 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1697 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1698 gboolean need_param_count = FALSE;
1700 if (mangle_stdcall > 0)
1701 need_param_count = TRUE;
1703 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1708 mangled_name = (char*)import;
1709 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1710 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1711 /* Try the mangled name first */
1712 if (mangle_charset == 0)
1713 mangled_name = g_strconcat (import, "W", NULL);
1715 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1717 if (mangle_charset == 0)
1718 mangled_name = g_strconcat (import, "W", NULL);
1720 /* Try the mangled name last */
1721 if (mangle_charset == 1)
1722 mangled_name = g_strconcat (import, "A", NULL);
1725 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1727 /* Try the mangled name last */
1728 if (mangle_charset == 1)
1729 mangled_name = g_strconcat (import, "A", NULL);
1734 if (mangle_param_count == 0)
1735 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1737 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1738 param_count = mangle_param_count;
1740 /* Try the stdcall mangled name */
1742 * gcc under windows creates mangled names without the underscore, but MS.NET
1743 * doesn't support it, so we doesn't support it either.
1745 if (mangle_stdcall == 1)
1746 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1748 mangled_name2 = mangled_name;
1750 mangled_name2 = mangled_name;
1753 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1754 "Probing '%s'.", mangled_name2);
1756 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1759 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1760 "Found as '%s'.", mangled_name2);
1762 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1763 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1768 if (mangled_name != mangled_name2)
1769 g_free (mangled_name2);
1770 if (mangled_name != import)
1771 g_free (mangled_name);
1777 if (!piinfo->addr) {
1780 *exc_class = "EntryPointNotFoundException";
1785 return piinfo->addr;
1789 * LOCKING: assumes the loader lock to be taken.
1792 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1793 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1796 int table = mono_metadata_token_table (token);
1797 int idx = mono_metadata_token_index (token);
1798 MonoTableInfo *tables = image->tables;
1799 MonoGenericContainer *generic_container = NULL, *container = NULL;
1800 const char *sig = NULL;
1801 guint32 cols [MONO_TYPEDEF_SIZE];
1803 mono_error_init (error);
1805 if (image_is_dynamic (image)) {
1806 MonoClass *handle_class;
1808 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1809 mono_loader_assert_no_error ();
1811 // This checks the memberref type as well
1812 if (result && handle_class != mono_defaults.methodhandle_class) {
1813 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1819 if (table != MONO_TABLE_METHOD) {
1820 if (table == MONO_TABLE_METHODSPEC) {
1821 if (used_context) *used_context = TRUE;
1822 return method_from_methodspec (image, context, idx, error);
1824 if (table != MONO_TABLE_MEMBERREF) {
1825 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1828 return method_from_memberref (image, idx, context, used_context, error);
1831 if (used_context) *used_context = FALSE;
1833 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1834 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1839 guint32 type = mono_metadata_typedef_from_method (image, token);
1841 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1844 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1849 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1851 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1852 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1853 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1855 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1856 methods_size += sizeof (MonoMethod);
1859 mono_stats.method_count ++;
1862 result->klass = klass;
1863 result->flags = cols [2];
1864 result->iflags = cols [1];
1865 result->token = token;
1866 result->name = mono_metadata_string_heap (image, cols [3]);
1868 if (!sig) /* already taken from the methodref */
1869 sig = mono_metadata_blob_heap (image, cols [4]);
1870 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1872 container = klass->generic_container;
1875 * load_generic_params does a binary search so only call it if the method
1879 generic_container = mono_metadata_load_generic_params (image, token, container);
1880 mono_loader_assert_no_error (); /* FIXME don't swallow this error. */
1882 if (generic_container) {
1883 result->is_generic = TRUE;
1884 generic_container->owner.method = result;
1885 /*FIXME put this before the image alloc*/
1886 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1889 container = generic_container;
1892 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1893 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1894 result->string_ctor = 1;
1895 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1896 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1899 /* IJW is P/Invoke with a predefined function pointer. */
1900 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1901 piinfo->addr = mono_image_rva_map (image, cols [0]);
1902 g_assert (piinfo->addr);
1905 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1906 /* Native methods can have no map. */
1907 if (piinfo->implmap_idx)
1908 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1911 if (generic_container)
1912 mono_method_set_generic_container (result, generic_container);
1914 mono_loader_assert_no_error ();
1919 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1921 return mono_get_method_full (image, token, klass, NULL);
1925 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1926 MonoGenericContext *context)
1929 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
1930 mono_loader_assert_no_error ();
1931 if (!mono_error_ok (&error)) {
1932 mono_loader_set_error_from_mono_error (&error);
1933 mono_error_cleanup (&error);
1939 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
1941 MonoMethod *result = NULL;
1942 gboolean used_context = FALSE;
1944 /* We do everything inside the lock to prevent creation races */
1946 mono_error_init (error);
1948 mono_image_lock (image);
1950 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1951 if (!image->method_cache)
1952 image->method_cache = g_hash_table_new (NULL, NULL);
1953 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1954 } else if (!image_is_dynamic (image)) {
1955 if (!image->methodref_cache)
1956 image->methodref_cache = g_hash_table_new (NULL, NULL);
1957 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1959 mono_image_unlock (image);
1965 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
1969 mono_image_lock (image);
1970 if (!used_context && !result->is_inflated) {
1971 MonoMethod *result2 = NULL;
1973 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1974 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1975 else if (!image_is_dynamic (image))
1976 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1979 mono_image_unlock (image);
1983 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1984 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1985 else if (!image_is_dynamic (image))
1986 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1989 mono_image_unlock (image);
1995 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
1998 MonoClass *ic = NULL;
1999 MonoGenericContext *method_context = NULL;
2000 MonoMethodSignature *sig, *original_sig;
2002 mono_error_init (error);
2004 mono_class_init (constrained_class);
2005 original_sig = sig = mono_method_signature_checked (method, error);
2010 if (method->is_inflated && sig->generic_param_count) {
2011 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2012 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
2015 method_context = mono_method_get_context (method);
2019 * We must inflate the signature with the class instantiation to work on
2020 * cases where a class inherit from a generic type and the override replaces
2021 * any type argument which a concrete type. See #325283.
2023 if (method_context->class_inst) {
2024 MonoGenericContext ctx;
2025 ctx.method_inst = NULL;
2026 ctx.class_inst = method_context->class_inst;
2027 /*Fixme, property propagate this error*/
2028 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2034 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2037 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2038 if (sig != original_sig)
2039 mono_metadata_free_inflated_signature (sig);
2044 if (method_context) {
2045 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2054 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2055 MonoGenericContext *context, MonoError *error)
2059 return get_method_constrained (image, method, constrained_class, context, error);
2063 * mono_get_method_constrained:
2065 * This is used when JITing the `constrained.' opcode.
2067 * This returns two values: the contrained method, which has been inflated
2068 * as the function return value; And the original CIL-stream method as
2069 * declared in cil_method. The later is used for verification.
2072 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2073 MonoGenericContext *context, MonoMethod **cil_method)
2076 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2078 mono_loader_assert_no_error ();
2079 if (!mono_error_ok (&error)) {
2080 mono_loader_set_error_from_mono_error (&error);
2081 mono_error_cleanup (&error);
2087 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2089 mono_error_init (error);
2091 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2095 return get_method_constrained (image, *cil_method, constrained_class, context, error);
2099 mono_free_method (MonoMethod *method)
2101 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2102 mono_profiler_method_free (method);
2104 /* FIXME: This hack will go away when the profiler will support freeing methods */
2105 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2108 if (method->signature) {
2110 * FIXME: This causes crashes because the types inside signatures and
2111 * locals are shared.
2113 /* mono_metadata_free_method_signature (method->signature); */
2114 /* g_free (method->signature); */
2117 if (method_is_dynamic (method)) {
2118 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2121 mono_marshal_free_dynamic_wrappers (method);
2123 mono_image_property_remove (method->klass->image, method);
2125 g_free ((char*)method->name);
2127 g_free ((char*)mw->header->code);
2128 for (i = 0; i < mw->header->num_locals; ++i)
2129 g_free (mw->header->locals [i]);
2130 g_free (mw->header->clauses);
2131 g_free (mw->header);
2133 g_free (mw->method_data);
2134 g_free (method->signature);
2140 mono_method_get_param_names (MonoMethod *method, const char **names)
2144 MonoTableInfo *methodt;
2145 MonoTableInfo *paramt;
2146 MonoMethodSignature *signature;
2149 if (method->is_inflated)
2150 method = ((MonoMethodInflated *) method)->declaring;
2152 signature = mono_method_signature (method);
2153 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2154 number of arguments and allocate a properly sized array. */
2155 if (signature == NULL)
2158 if (!signature->param_count)
2161 for (i = 0; i < signature->param_count; ++i)
2164 klass = method->klass;
2168 mono_class_init (klass);
2170 if (image_is_dynamic (klass->image)) {
2171 MonoReflectionMethodAux *method_aux =
2172 g_hash_table_lookup (
2173 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2174 if (method_aux && method_aux->param_names) {
2175 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2176 if (method_aux->param_names [i + 1])
2177 names [i] = method_aux->param_names [i + 1];
2182 if (method->wrapper_type) {
2183 char **pnames = NULL;
2185 mono_image_lock (klass->image);
2186 if (klass->image->wrapper_param_names)
2187 pnames = g_hash_table_lookup (klass->image->wrapper_param_names, method);
2188 mono_image_unlock (klass->image);
2191 for (i = 0; i < signature->param_count; ++i)
2192 names [i] = pnames [i];
2197 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2198 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2199 idx = mono_method_get_index (method);
2201 guint32 cols [MONO_PARAM_SIZE];
2204 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2206 if (idx < methodt->rows)
2207 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2209 lastp = paramt->rows + 1;
2210 for (i = param_index; i < lastp; ++i) {
2211 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2212 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2213 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2219 mono_method_get_param_token (MonoMethod *method, int index)
2221 MonoClass *klass = method->klass;
2222 MonoTableInfo *methodt;
2225 mono_class_init (klass);
2227 if (image_is_dynamic (klass->image))
2228 g_assert_not_reached ();
2230 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2231 idx = mono_method_get_index (method);
2233 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2237 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2239 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2246 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2249 MonoClass *klass = method->klass;
2250 MonoTableInfo *methodt;
2251 MonoTableInfo *paramt;
2252 MonoMethodSignature *signature;
2255 signature = mono_method_signature (method);
2256 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2258 for (i = 0; i < signature->param_count + 1; ++i)
2261 if (image_is_dynamic (method->klass->image)) {
2262 MonoReflectionMethodAux *method_aux =
2263 g_hash_table_lookup (
2264 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2265 if (method_aux && method_aux->param_marshall) {
2266 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2267 for (i = 0; i < signature->param_count + 1; ++i)
2268 if (dyn_specs [i]) {
2269 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2270 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2271 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2272 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2278 mono_class_init (klass);
2280 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2281 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2282 idx = mono_method_get_index (method);
2284 guint32 cols [MONO_PARAM_SIZE];
2285 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2287 if (idx < methodt->rows)
2288 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2290 lastp = paramt->rows + 1;
2292 for (i = param_index; i < lastp; ++i) {
2293 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2295 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2297 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2299 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2308 mono_method_has_marshal_info (MonoMethod *method)
2311 MonoClass *klass = method->klass;
2312 MonoTableInfo *methodt;
2313 MonoTableInfo *paramt;
2316 if (image_is_dynamic (method->klass->image)) {
2317 MonoReflectionMethodAux *method_aux =
2318 g_hash_table_lookup (
2319 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2320 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2322 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2329 mono_class_init (klass);
2331 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2332 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2333 idx = mono_method_get_index (method);
2335 guint32 cols [MONO_PARAM_SIZE];
2336 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2338 if (idx + 1 < methodt->rows)
2339 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2341 lastp = paramt->rows + 1;
2343 for (i = param_index; i < lastp; ++i) {
2344 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2346 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2355 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2358 g_assert (method != NULL);
2359 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2361 if (method->is_inflated)
2362 method = ((MonoMethodInflated *) method)->declaring;
2363 data = ((MonoMethodWrapper *)method)->method_data;
2364 g_assert (data != NULL);
2365 g_assert (id <= GPOINTER_TO_UINT (*data));
2372 } StackWalkUserData;
2375 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2377 StackWalkUserData *d = data;
2379 switch (frame->type) {
2380 case FRAME_TYPE_DEBUGGER_INVOKE:
2381 case FRAME_TYPE_MANAGED_TO_NATIVE:
2382 case FRAME_TYPE_TRAMPOLINE:
2384 case FRAME_TYPE_MANAGED:
2385 g_assert (frame->ji);
2386 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2389 g_assert_not_reached ();
2395 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2397 StackWalkUserData ud = { func, user_data };
2398 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2402 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2404 StackWalkUserData ud = { func, user_data };
2405 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2409 MonoStackWalkAsyncSafe func;
2411 } AsyncStackWalkUserData;
2415 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2417 AsyncStackWalkUserData *d = data;
2419 switch (frame->type) {
2420 case FRAME_TYPE_DEBUGGER_INVOKE:
2421 case FRAME_TYPE_MANAGED_TO_NATIVE:
2422 case FRAME_TYPE_TRAMPOLINE:
2424 case FRAME_TYPE_MANAGED:
2427 if (frame->ji->async) {
2428 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2430 return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2434 g_assert_not_reached ();
2441 * mono_stack_walk_async_safe:
2443 * Async safe version callable from signal handlers.
2446 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2449 AsyncStackWalkUserData ud = { func, user_data };
2451 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2452 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2456 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2458 MonoMethod **dest = data;
2460 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2466 mono_method_get_last_managed (void)
2468 MonoMethod *m = NULL;
2469 mono_stack_walk_no_il (last_managed, &m);
2473 static gboolean loader_lock_track_ownership = FALSE;
2478 * See docs/thread-safety.txt for the locking strategy.
2481 mono_loader_lock (void)
2484 mono_locks_acquire (&loader_mutex, LoaderLock);
2485 MONO_FINISH_TRY_BLOCKING;
2487 if (G_UNLIKELY (loader_lock_track_ownership)) {
2488 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));
2493 mono_loader_unlock (void)
2495 mono_locks_release (&loader_mutex, LoaderLock);
2496 if (G_UNLIKELY (loader_lock_track_ownership)) {
2497 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));
2502 * mono_loader_lock_track_ownership:
2504 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2505 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2506 * thread owns the loader lock.
2509 mono_loader_lock_track_ownership (gboolean track)
2511 loader_lock_track_ownership = track;
2515 * mono_loader_lock_is_owned_by_self:
2517 * Return whenever the current thread owns the loader lock.
2518 * This is useful to avoid blocking operations while holding the loader lock.
2521 mono_loader_lock_is_owned_by_self (void)
2523 g_assert (loader_lock_track_ownership);
2525 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2529 * mono_loader_lock_if_inited:
2531 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2532 * be used in runtime initialization code which can be executed before mono_loader_init ().
2535 mono_loader_lock_if_inited (void)
2537 if (loader_lock_inited)
2538 mono_loader_lock ();
2542 mono_loader_unlock_if_inited (void)
2544 if (loader_lock_inited)
2545 mono_loader_unlock ();
2549 * mono_method_signature:
2551 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2553 MonoMethodSignature*
2554 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2559 gboolean can_cache_signature;
2560 MonoGenericContainer *container;
2561 MonoMethodSignature *signature = NULL, *sig2;
2564 /* We need memory barriers below because of the double-checked locking pattern */
2566 mono_error_init (error);
2569 return m->signature;
2571 img = m->klass->image;
2573 if (m->is_inflated) {
2574 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2575 /* the lock is recursive */
2576 signature = mono_method_signature (imethod->declaring);
2577 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2578 if (!mono_error_ok (error))
2581 inflated_signatures_size += mono_metadata_signature_size (signature);
2583 mono_image_lock (img);
2585 mono_memory_barrier ();
2587 m->signature = signature;
2589 mono_image_unlock (img);
2591 return m->signature;
2594 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2595 idx = mono_metadata_token_index (m->token);
2597 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2599 g_assert (!m->klass->generic_class);
2600 container = mono_method_get_generic_container (m);
2602 container = m->klass->generic_container;
2604 /* Generic signatures depend on the container so they cannot be cached */
2605 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2606 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2608 /* If the method has parameter attributes, that can modify the signature */
2609 if (mono_metadata_method_has_param_attrs (img, idx))
2610 can_cache_signature = FALSE;
2612 if (can_cache_signature) {
2613 mono_image_lock (img);
2614 signature = g_hash_table_lookup (img->method_signatures, sig);
2615 mono_image_unlock (img);
2619 const char *sig_body;
2620 /*TODO we should cache the failure result somewhere*/
2621 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2624 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2626 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2630 if (can_cache_signature) {
2631 mono_image_lock (img);
2632 sig2 = g_hash_table_lookup (img->method_signatures, sig);
2634 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2635 mono_image_unlock (img);
2638 signatures_size += mono_metadata_signature_size (signature);
2641 /* Verify metadata consistency */
2642 if (signature->generic_param_count) {
2643 if (!container || !container->is_method) {
2644 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);
2647 if (container->type_argc != signature->generic_param_count) {
2648 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);
2651 } else if (container && container->is_method && container->type_argc) {
2652 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);
2655 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2656 signature->pinvoke = 1;
2657 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2658 MonoCallConvention conv = 0;
2659 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2660 signature->pinvoke = 1;
2662 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2663 case 0: /* no call conv, so using default */
2664 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2665 conv = MONO_CALL_DEFAULT;
2667 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2670 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2671 conv = MONO_CALL_STDCALL;
2673 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2674 conv = MONO_CALL_THISCALL;
2676 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2677 conv = MONO_CALL_FASTCALL;
2679 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2680 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2682 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);
2685 signature->call_convention = conv;
2688 mono_image_lock (img);
2690 mono_memory_barrier ();
2692 m->signature = signature;
2694 mono_image_unlock (img);
2696 return m->signature;
2700 * mono_method_signature:
2702 * Return the signature of the method M. On failure, returns NULL.
2704 MonoMethodSignature*
2705 mono_method_signature (MonoMethod *m)
2708 MonoMethodSignature *sig;
2710 sig = mono_method_signature_checked (m, &error);
2712 char *type_name = mono_type_get_full_name (m->klass);
2713 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2715 mono_error_cleanup (&error);
2722 mono_method_get_name (MonoMethod *method)
2724 return method->name;
2728 mono_method_get_class (MonoMethod *method)
2730 return method->klass;
2734 mono_method_get_token (MonoMethod *method)
2736 return method->token;
2740 mono_method_get_header (MonoMethod *method)
2746 MonoMethodHeader *header;
2747 MonoGenericContainer *container;
2749 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))
2752 img = method->klass->image;
2754 if (method->is_inflated) {
2755 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2756 MonoMethodHeader *header, *iheader;
2758 header = mono_method_get_header (imethod->declaring);
2762 iheader = inflate_generic_header (header, mono_method_get_context (method));
2763 mono_metadata_free_mh (header);
2765 mono_image_lock (img);
2767 if (imethod->header) {
2768 mono_metadata_free_mh (iheader);
2769 mono_image_unlock (img);
2770 return imethod->header;
2773 mono_memory_barrier ();
2774 imethod->header = iheader;
2776 mono_image_unlock (img);
2778 return imethod->header;
2781 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2782 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2783 g_assert (mw->header);
2788 * We don't need locks here: the new header is allocated from malloc memory
2789 * and is not stored anywhere in the runtime, the user needs to free it.
2791 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2792 idx = mono_metadata_token_index (method->token);
2793 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2795 if (!mono_verifier_verify_method_header (img, rva, NULL))
2798 loc = mono_image_rva_map (img, rva);
2803 * When parsing the types of local variables, we must pass any container available
2804 * to ensure that both VAR and MVAR will get the right owner.
2806 container = mono_method_get_generic_container (method);
2808 container = method->klass->generic_container;
2809 header = mono_metadata_parse_mh_full (img, container, loc);
2815 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2818 *iflags = method->iflags;
2819 return method->flags;
2823 * Find the method index in the metadata methodDef table.
2826 mono_method_get_index (MonoMethod *method)
2828 MonoClass *klass = method->klass;
2832 /* constructed array methods are not in the MethodDef table */
2836 return mono_metadata_token_index (method->token);
2838 mono_class_setup_methods (klass);
2839 if (klass->exception_type)
2841 for (i = 0; i < klass->method.count; ++i) {
2842 if (method == klass->methods [i]) {
2843 if (klass->image->uncompressed_metadata)
2844 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2846 return klass->method.first + i + 1;