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_clear_error:
293 * Disposes any loader error messages on this thread
296 mono_loader_clear_error (void)
298 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
301 g_free (ex->class_name);
302 g_free (ex->assembly_name);
306 mono_native_tls_set_value (loader_error_thread_id, NULL);
311 * mono_loader_error_prepare_exception:
312 * @error: The MonoLoaderError to turn into an exception
314 * This turns a MonoLoaderError into an exception that can be thrown
315 * and resets the Mono Loader Error state during this process.
319 mono_loader_error_prepare_exception (MonoLoaderError *error)
321 MonoException *ex = NULL;
323 switch (error->exception_type) {
324 case MONO_EXCEPTION_TYPE_LOAD: {
325 char *cname = g_strdup (error->class_name);
326 char *aname = g_strdup (error->assembly_name);
327 MonoString *class_name;
329 mono_loader_clear_error ();
331 class_name = mono_string_new (mono_domain_get (), cname);
333 ex = mono_get_exception_type_load (class_name, aname);
338 case MONO_EXCEPTION_MISSING_METHOD: {
339 char *cname = g_strdup (error->class_name);
340 char *aname = g_strdup (error->member_name);
342 mono_loader_clear_error ();
343 ex = mono_get_exception_missing_method (cname, aname);
349 case MONO_EXCEPTION_MISSING_FIELD: {
351 char *cmembername = g_strdup (error->member_name);
353 class_name = mono_type_get_full_name (error->klass);
355 class_name = g_strdup ("");
357 mono_loader_clear_error ();
359 ex = mono_get_exception_missing_field (class_name, cmembername);
361 g_free (cmembername);
365 case MONO_EXCEPTION_FILE_NOT_FOUND: {
370 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);
372 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
373 filename = g_strdup (error->assembly_name);
374 /* Has to call this before calling anything which might call mono_class_init () */
375 mono_loader_clear_error ();
376 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
382 case MONO_EXCEPTION_BAD_IMAGE: {
383 char *msg = g_strdup (error->msg);
384 mono_loader_clear_error ();
385 ex = mono_get_exception_bad_image_format (msg);
391 g_assert_not_reached ();
398 * find_cached_memberref_sig:
400 * Return a cached copy of the memberref signature identified by SIG_IDX.
401 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
402 * A cache is needed since the type/signature parsing routines allocate everything
403 * from a mempool, so without a cache, multiple requests for the same signature would
404 * lead to unbounded memory growth. For normal methods/fields this is not a problem
405 * since the resulting methods/fields are cached, but inflated methods/fields cannot
407 * LOCKING: Acquires the loader lock.
410 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
414 mono_image_lock (image);
415 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
416 mono_image_unlock (image);
422 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
426 mono_image_lock (image);
427 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
429 /* Somebody got in before us */
433 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
434 /* An approximation based on glib 2.18 */
435 memberref_sig_cache_size += sizeof (gpointer) * 4;
437 mono_image_unlock (image);
442 static MonoClassField*
443 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
444 MonoGenericContext *context, MonoError *error)
446 MonoClass *klass = NULL;
447 MonoClassField *field;
448 MonoTableInfo *tables = image->tables;
451 guint32 nindex, class, class_table;
454 guint32 idx = mono_metadata_token_index (token);
456 mono_error_init (error);
458 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
459 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
460 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
462 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
464 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
465 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class, token);
470 case MONO_MEMBERREF_PARENT_TYPEDEF:
471 class_table = MONO_TOKEN_TYPE_DEF;
472 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
474 case MONO_MEMBERREF_PARENT_TYPEREF:
475 class_table = MONO_TOKEN_TYPE_REF;
476 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
478 case MONO_MEMBERREF_PARENT_TYPESPEC:
479 class_table = MONO_TOKEN_TYPE_SPEC;
480 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
483 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class, token);
489 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
490 mono_metadata_decode_blob_size (ptr, &ptr);
491 /* we may want to check the signature here... */
494 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class, fname, token);
498 /* FIXME: This needs a cache, especially for generic instances, since
499 * mono_metadata_parse_type () allocates everything from a mempool.
501 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
503 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
504 if (sig_type == NULL) {
505 mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x", fname, token);
508 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
511 mono_class_init (klass); /*FIXME is this really necessary?*/
514 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
517 g_assert (!mono_loader_get_last_error ());
518 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
525 * mono_field_from_token:
526 * @deprecated use the _checked variant
529 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
532 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
533 g_assert (!mono_loader_get_last_error ());
534 if (!mono_error_ok (&error)) {
535 mono_loader_set_error_from_mono_error (&error);
536 mono_error_cleanup (&error);
542 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
546 MonoClassField *field;
548 mono_error_init (error);
550 if (image_is_dynamic (image)) {
551 MonoClassField *result;
552 MonoClass *handle_class;
555 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
556 // This checks the memberref type as well
557 if (!result || handle_class != mono_defaults.fieldhandle_class) {
558 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
561 *retklass = result->parent;
565 if ((field = mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
566 *retklass = field->parent;
570 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
571 field = field_from_memberref (image, token, retklass, context, error);
572 g_assert (!mono_loader_get_last_error ());
574 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
576 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
579 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
586 field = mono_class_get_field (k, token);
588 if (mono_loader_get_last_error ())
589 mono_error_set_from_loader_error (error);
591 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
595 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
596 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
598 g_assert (!mono_loader_get_last_error ());
603 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
607 if (sig1->hasthis != sig2->hasthis ||
608 sig1->sentinelpos != sig2->sentinelpos)
611 for (i = 0; i < sig1->sentinelpos; i++) {
612 MonoType *p1 = sig1->params[i];
613 MonoType *p2 = sig2->params[i];
615 /*if (p1->attrs != p2->attrs)
618 if (!mono_metadata_type_equal (p1, p2))
622 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
628 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
629 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
633 /* Search directly in the metadata to avoid calling setup_methods () */
634 mono_error_init (error);
636 /* FIXME: !from_class->generic_class condition causes test failures. */
637 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
638 for (i = 0; i < klass->method.count; ++i) {
639 guint32 cols [MONO_METHOD_SIZE];
642 MonoMethodSignature *other_sig;
644 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
646 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
648 if (!((fqname && !strcmp (m_name, fqname)) ||
649 (qname && !strcmp (m_name, qname)) ||
650 (name && !strcmp (m_name, name))))
653 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
654 if (!mono_error_ok (error)) //bail out if we hit a loader error
657 other_sig = mono_method_signature_checked (method, error);
658 if (!mono_error_ok (error)) //bail out if we hit a loader error
660 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
666 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
668 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
669 See mono/tests/generic-type-load-exception.2.il
670 FIXME we should better report this error to the caller
672 if (!klass->methods || klass->exception_type) {
673 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
677 for (i = 0; i < klass->method.count; ++i) {
678 MonoMethod *m = klass->methods [i];
679 MonoMethodSignature *msig;
681 /* We must cope with failing to load some of the types. */
685 if (!((fqname && !strcmp (m->name, fqname)) ||
686 (qname && !strcmp (m->name, qname)) ||
687 (name && !strcmp (m->name, name))))
689 msig = mono_method_signature_checked (m, error);
690 if (!mono_error_ok (error)) //bail out if we hit a loader error
696 if (sig->call_convention == MONO_CALL_VARARG) {
697 if (mono_metadata_signature_vararg_match (sig, msig))
700 if (mono_metadata_signature_equal (sig, msig))
705 if (i < klass->method.count)
706 return mono_class_get_method_by_index (from_class, i);
711 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
714 char *qname, *fqname, *class_name;
715 gboolean is_interface;
716 MonoMethod *result = NULL;
717 MonoClass *initial_class = in_class;
719 mono_error_init (error);
720 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
723 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
725 qname = g_strconcat (class_name, ".", name, NULL);
726 if (ic->name_space && ic->name_space [0])
727 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
731 class_name = qname = fqname = NULL;
734 g_assert (from_class);
735 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
736 if (result || !mono_error_ok (error))
739 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
743 * This happens when we fail to lazily load the interfaces of one of the types.
744 * On such case we can't just bail out since user code depends on us trying harder.
746 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
747 in_class = in_class->parent;
748 from_class = from_class->parent;
752 for (i = 0; i < in_class->interface_offsets_count; i++) {
753 MonoClass *in_ic = in_class->interfaces_packed [i];
754 MonoClass *from_ic = from_class->interfaces_packed [i];
755 char *ic_qname, *ic_fqname, *ic_class_name;
757 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
758 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
759 if (in_ic->name_space && in_ic->name_space [0])
760 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
764 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
765 g_free (ic_class_name);
768 if (result || !mono_error_ok (error))
772 in_class = in_class->parent;
773 from_class = from_class->parent;
775 g_assert (!in_class == !from_class);
778 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
780 //we did not find the method
781 if (!result && mono_error_ok (error)) {
782 char *desc = mono_signature_get_desc (sig, FALSE);
783 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
794 static MonoMethodSignature*
795 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
797 MonoMethodSignature *res;
801 mono_error_init (error);
805 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
806 res->param_count = sig->param_count;
807 res->sentinelpos = -1;
808 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
809 if (!mono_error_ok (error))
811 is_open = mono_class_is_open_constructed_type (res->ret);
812 for (i = 0; i < sig->param_count; ++i) {
813 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
814 if (!mono_error_ok (error))
818 is_open = mono_class_is_open_constructed_type (res->params [i]);
820 res->hasthis = sig->hasthis;
821 res->explicit_this = sig->explicit_this;
822 res->call_convention = sig->call_convention;
823 res->pinvoke = sig->pinvoke;
824 res->generic_param_count = sig->generic_param_count;
825 res->sentinelpos = sig->sentinelpos;
826 res->has_type_parameters = is_open;
827 res->is_inflated = 1;
832 mono_metadata_free_type (res->ret);
833 for (i = 0; i < sig->param_count; ++i) {
835 mono_metadata_free_type (res->params [i]);
842 * mono_inflate_generic_signature:
844 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
847 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
849 MonoMethodSignature *res, *cached;
851 res = inflate_generic_signature_checked (NULL, sig, context, error);
852 if (!mono_error_ok (error))
854 cached = mono_metadata_get_inflated_signature (res, context);
856 mono_metadata_free_inflated_signature (res);
860 static MonoMethodHeader*
861 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
863 MonoMethodHeader *res;
865 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
866 res->code = header->code;
867 res->code_size = header->code_size;
868 res->max_stack = header->max_stack;
869 res->num_clauses = header->num_clauses;
870 res->init_locals = header->init_locals;
871 res->num_locals = header->num_locals;
872 res->clauses = header->clauses;
873 for (i = 0; i < header->num_locals; ++i)
874 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
875 if (res->num_clauses) {
876 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
877 for (i = 0; i < header->num_clauses; ++i) {
878 MonoExceptionClause *clause = &res->clauses [i];
879 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
881 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
888 * token is the method_ref/def/spec token used in a call IL instruction.
891 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
894 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
896 g_assert (!mono_loader_get_last_error ());
899 g_assert (!mono_error_ok (&error));
900 mono_loader_set_error_from_mono_error (&error);
901 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
907 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
909 int table = mono_metadata_token_table (token);
910 int idx = mono_metadata_token_index (token);
912 guint32 cols [MONO_MEMBERREF_SIZE];
913 MonoMethodSignature *sig;
916 mono_error_init (error);
918 /* !table is for wrappers: we should really assign their own token to them */
919 if (!table || table == MONO_TABLE_METHOD)
920 return mono_method_signature_checked (method, error);
922 if (table == MONO_TABLE_METHODSPEC) {
923 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
924 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
927 return mono_method_signature_checked (method, error);
930 if (method->klass->generic_class)
931 return mono_method_signature_checked (method, error);
933 if (image_is_dynamic (image)) {
934 sig = mono_reflection_lookup_signature (image, method, token, error);
938 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
939 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
941 sig = find_cached_memberref_sig (image, sig_idx);
943 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
944 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
945 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
947 //FIXME include the verification error
948 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
952 ptr = mono_metadata_blob_heap (image, sig_idx);
953 mono_metadata_decode_blob_size (ptr, &ptr);
955 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
959 sig = cache_memberref_sig (image, sig_idx, sig);
961 /* FIXME: we probably should verify signature compat in the dynamic case too*/
962 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
963 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
964 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
966 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
972 MonoMethodSignature *cached;
974 /* This signature is not owned by a MonoMethod, so need to cache */
975 sig = inflate_generic_signature_checked (image, sig, context, error);
976 if (!mono_error_ok (error))
979 cached = mono_metadata_get_inflated_signature (sig, context);
981 mono_metadata_free_inflated_signature (sig);
983 inflated_signatures_size += mono_metadata_signature_size (cached);
987 g_assert (mono_error_ok (error));
992 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
995 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
997 g_assert (!mono_loader_get_last_error ());
1000 g_assert (!mono_error_ok (&error));
1001 mono_loader_set_error_from_mono_error (&error);
1002 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
1007 /* this is only for the typespec array methods */
1009 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1013 mono_class_setup_methods (klass);
1014 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
1015 for (i = 0; i < klass->method.count; ++i) {
1016 MonoMethod *method = klass->methods [i];
1017 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1024 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1025 gboolean *used_context, MonoError *error)
1027 MonoClass *klass = NULL;
1028 MonoMethod *method = NULL;
1029 MonoTableInfo *tables = image->tables;
1031 guint32 nindex, class, sig_idx;
1033 MonoMethodSignature *sig;
1036 mono_error_init (error);
1038 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1039 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1040 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1041 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1042 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1044 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1047 * Whether we actually used the `typespec_context' or not.
1048 * This is used to tell our caller whether or not it's safe to insert the returned
1049 * method into a cache.
1052 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
1055 case MONO_MEMBERREF_PARENT_TYPEREF:
1056 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1060 case MONO_MEMBERREF_PARENT_TYPESPEC:
1062 * Parse the TYPESPEC in the parent's context.
1064 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1068 case MONO_MEMBERREF_PARENT_TYPEDEF:
1069 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1073 case MONO_MEMBERREF_PARENT_METHODDEF: {
1074 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1080 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class, nindex);
1085 mono_class_init (klass);
1087 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1089 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1090 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1094 ptr = mono_metadata_blob_heap (image, sig_idx);
1095 mono_metadata_decode_blob_size (ptr, &ptr);
1097 sig = find_cached_memberref_sig (image, sig_idx);
1099 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1103 sig = cache_memberref_sig (image, sig_idx, sig);
1107 case MONO_MEMBERREF_PARENT_TYPEREF:
1108 case MONO_MEMBERREF_PARENT_TYPEDEF:
1109 method = find_method (klass, NULL, mname, sig, klass, error);
1112 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1115 type = &klass->byval_arg;
1117 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1118 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1119 method = find_method (in_class, NULL, mname, sig, klass, error);
1123 /* we're an array and we created these methods already in klass in mono_class_init () */
1124 method = mono_method_search_in_array_class (klass, mname, sig);
1128 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class, nindex);
1132 if (!method && mono_error_ok (error)) {
1133 char *msig = mono_signature_get_desc (sig, FALSE);
1134 GString *s = g_string_new (mname);
1135 if (sig->generic_param_count)
1136 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1137 g_string_append_printf (s, "(%s)", msig);
1139 msig = g_string_free (s, FALSE);
1141 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1142 mono_error_set_from_loader_error (error);
1144 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1149 g_assert (!mono_loader_get_last_error ());
1153 g_assert (!mono_loader_get_last_error ());
1154 g_assert (!mono_error_ok (error));
1159 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1163 MonoTableInfo *tables = image->tables;
1164 MonoGenericContext new_context;
1165 MonoGenericInst *inst;
1167 guint32 cols [MONO_METHODSPEC_SIZE];
1168 guint32 token, nindex, param_count;
1170 mono_error_init (error);
1172 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1173 token = cols [MONO_METHODSPEC_METHOD];
1174 nindex = token >> MONO_METHODDEFORREF_BITS;
1176 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1177 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1181 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1183 mono_metadata_decode_value (ptr, &ptr);
1185 param_count = mono_metadata_decode_value (ptr, &ptr);
1187 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1189 g_assert (!mono_loader_get_last_error ());
1190 mono_error_set_bad_image (error, image, "Cannot parse generic instance for methodspec 0x%08x", idx);
1194 if (context && inst->is_open) {
1195 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1196 if (!mono_error_ok (error))
1200 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1201 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1205 method = method_from_memberref (image, nindex, context, NULL, error);
1211 klass = method->klass;
1213 if (klass->generic_class) {
1214 g_assert (method->is_inflated);
1215 method = ((MonoMethodInflated *) method)->declaring;
1218 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1219 new_context.method_inst = inst;
1221 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1222 g_assert (!mono_loader_get_last_error ());
1226 struct _MonoDllMap {
1234 static MonoDllMap *global_dll_map;
1237 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1245 global_loader_data_lock ();
1248 * we use the first entry we find that matches, since entries from
1249 * the config file are prepended to the list and we document that the
1250 * later entries win.
1252 for (; dll_map; dll_map = dll_map->next) {
1253 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1254 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1256 } else if (strcmp (dll_map->dll, dll)) {
1259 if (!found && dll_map->target) {
1260 *rdll = dll_map->target;
1262 /* we don't quit here, because we could find a full
1263 * entry that matches also function and that has priority.
1266 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1267 *rfunc = dll_map->target_func;
1272 global_loader_data_unlock ();
1277 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1280 if (assembly && assembly->dll_map) {
1281 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1285 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1289 * mono_dllmap_insert:
1290 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1291 * @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
1292 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1293 * @tdll: The name of the library to map the specified @dll if it matches.
1294 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1296 * LOCKING: Acquires the loader lock.
1298 * This function is used to programatically add DllImport remapping in either
1299 * a specific assembly, or as a global remapping. This is done by remapping
1300 * references in a DllImport attribute from the @dll library name into the @tdll
1301 * name. If the @dll name contains the prefix "i:", the comparison of the
1302 * library name is done without case sensitivity.
1304 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1305 * or the name of the function as determined by DllImport. If you pass @func, you
1306 * must also pass @tfunc which is the name of the target function to invoke on a match.
1309 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1311 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1312 * the contents of relocated_demo_path for all assemblies in the Mono process.
1314 * NOTE: This can be called before the runtime is initialized, for example from
1315 * mono_config_parse ().
1318 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1322 mono_loader_init ();
1325 entry = g_malloc0 (sizeof (MonoDllMap));
1326 entry->dll = dll? g_strdup (dll): NULL;
1327 entry->target = tdll? g_strdup (tdll): NULL;
1328 entry->func = func? g_strdup (func): NULL;
1329 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1331 global_loader_data_lock ();
1332 entry->next = global_dll_map;
1333 global_dll_map = entry;
1334 global_loader_data_unlock ();
1336 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1337 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1338 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1339 entry->func = func? mono_image_strdup (assembly, func): NULL;
1340 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1342 mono_image_lock (assembly);
1343 entry->next = assembly->dll_map;
1344 assembly->dll_map = entry;
1345 mono_image_unlock (assembly);
1350 free_dllmap (MonoDllMap *map)
1353 MonoDllMap *next = map->next;
1356 g_free (map->target);
1358 g_free (map->target_func);
1365 dllmap_cleanup (void)
1367 free_dllmap (global_dll_map);
1368 global_dll_map = NULL;
1371 static GHashTable *global_module_map;
1374 cached_module_load (const char *name, int flags, char **err)
1380 global_loader_data_lock ();
1381 if (!global_module_map)
1382 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1383 res = g_hash_table_lookup (global_module_map, name);
1385 global_loader_data_unlock ();
1388 res = mono_dl_open (name, flags, err);
1390 g_hash_table_insert (global_module_map, g_strdup (name), res);
1391 global_loader_data_unlock ();
1395 static MonoDl *internal_module;
1398 is_absolute_path (const char *path)
1400 #ifdef PLATFORM_MACOSX
1401 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1402 !strncmp (path, "@rpath/", 7))
1405 return g_path_is_absolute (path);
1409 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1411 MonoImage *image = method->klass->image;
1412 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1413 MonoTableInfo *tables = image->tables;
1414 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1415 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1416 guint32 im_cols [MONO_IMPLMAP_SIZE];
1417 guint32 scope_token;
1418 const char *import = NULL;
1419 const char *orig_scope;
1420 const char *new_scope;
1422 char *full_name, *file_name, *found_name = NULL;
1424 MonoDl *module = NULL;
1425 gboolean cached = FALSE;
1427 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1435 return piinfo->addr;
1437 if (image_is_dynamic (method->klass->image)) {
1438 MonoReflectionMethodAux *method_aux =
1439 g_hash_table_lookup (
1440 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1444 import = method_aux->dllentry;
1445 orig_scope = method_aux->dll;
1448 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1451 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1453 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1456 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1457 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1458 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1459 orig_scope = mono_metadata_string_heap (image, scope_token);
1462 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1465 mono_image_lock (image);
1466 if (!image->pinvoke_scopes) {
1467 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1468 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1470 module = g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1471 found_name = g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1472 mono_image_unlock (image);
1476 found_name = g_strdup (found_name);
1480 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1481 "DllImport attempting to load: '%s'.", new_scope);
1483 /* we allow a special name to dlopen from the running process namespace */
1484 if (strcmp (new_scope, "__Internal") == 0){
1485 if (internal_module == NULL)
1486 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1487 module = internal_module;
1492 * Try loading the module using a variety of names
1494 for (i = 0; i < 4; ++i) {
1495 char *base_name = NULL, *dir_name = NULL;
1496 gboolean is_absolute = is_absolute_path (new_scope);
1500 /* Try the original name */
1501 file_name = g_strdup (new_scope);
1504 /* Try trimming the .dll extension */
1505 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1506 file_name = g_strdup (new_scope);
1507 file_name [strlen (new_scope) - 4] = '\0';
1514 dir_name = g_path_get_dirname (new_scope);
1515 base_name = g_path_get_basename (new_scope);
1516 if (strstr (base_name, "lib") != base_name) {
1517 char *tmp = g_strdup_printf ("lib%s", base_name);
1520 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1523 } else if (strstr (new_scope, "lib") != new_scope) {
1524 file_name = g_strdup_printf ("lib%s", new_scope);
1529 #ifndef TARGET_WIN32
1530 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1531 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1532 !g_ascii_strcasecmp ("user32", new_scope) ||
1533 !g_ascii_strcasecmp ("kernel", new_scope)) {
1534 file_name = g_strdup ("libMonoSupportW.so");
1538 #ifndef TARGET_WIN32
1545 dir_name = g_path_get_dirname (file_name);
1547 base_name = g_path_get_basename (file_name);
1550 if (!module && is_absolute) {
1551 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1553 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1554 "DllImport error loading library '%s': '%s'.",
1555 file_name, error_msg);
1558 found_name = g_strdup (file_name);
1562 if (!module && !is_absolute) {
1564 char *mdirname = g_path_get_dirname (image->name);
1565 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1566 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1568 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1569 "DllImport error loading library '%s': '%s'.",
1570 full_name, error_msg);
1573 found_name = g_strdup (full_name);
1584 char *file_or_base = is_absolute ? base_name : file_name;
1585 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1586 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1588 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1589 "DllImport error loading library '%s': '%s'.",
1590 full_name, error_msg);
1593 found_name = g_strdup (full_name);
1602 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1604 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1605 "DllImport error loading library '%s': '%s'.",
1606 file_name, error_msg);
1608 found_name = g_strdup (file_name);
1623 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1624 "DllImport unable to load library '%s'.",
1629 *exc_class = "DllNotFoundException";
1630 *exc_arg = new_scope;
1636 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1637 "DllImport loaded library '%s'.", found_name);
1638 mono_image_lock (image);
1639 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1640 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1641 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1643 mono_image_unlock (image);
1646 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1647 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1648 g_free (found_name);
1651 if (import && import [0] == '#' && isdigit (import [1])) {
1655 id = strtol (import + 1, &end, 10);
1656 if (id > 0 && *end == '\0')
1660 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1661 "Searching for '%s'.", import);
1663 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1664 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1666 char *mangled_name = NULL, *mangled_name2 = NULL;
1669 int mangle_param_count;
1675 * Search using a variety of mangled names
1677 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1678 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1679 gboolean need_param_count = FALSE;
1681 if (mangle_stdcall > 0)
1682 need_param_count = TRUE;
1684 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1689 mangled_name = (char*)import;
1690 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1691 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1692 /* Try the mangled name first */
1693 if (mangle_charset == 0)
1694 mangled_name = g_strconcat (import, "W", NULL);
1696 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1698 if (mangle_charset == 0)
1699 mangled_name = g_strconcat (import, "W", NULL);
1701 /* Try the mangled name last */
1702 if (mangle_charset == 1)
1703 mangled_name = g_strconcat (import, "A", NULL);
1706 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1708 /* Try the mangled name last */
1709 if (mangle_charset == 1)
1710 mangled_name = g_strconcat (import, "A", NULL);
1715 if (mangle_param_count == 0)
1716 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1718 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1719 param_count = mangle_param_count;
1721 /* Try the stdcall mangled name */
1723 * gcc under windows creates mangled names without the underscore, but MS.NET
1724 * doesn't support it, so we doesn't support it either.
1726 if (mangle_stdcall == 1)
1727 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1729 mangled_name2 = mangled_name;
1731 mangled_name2 = mangled_name;
1734 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1735 "Probing '%s'.", mangled_name2);
1737 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1740 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1741 "Found as '%s'.", mangled_name2);
1743 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1744 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1749 if (mangled_name != mangled_name2)
1750 g_free (mangled_name2);
1751 if (mangled_name != import)
1752 g_free (mangled_name);
1758 if (!piinfo->addr) {
1761 *exc_class = "EntryPointNotFoundException";
1766 return piinfo->addr;
1770 * LOCKING: assumes the loader lock to be taken.
1773 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1774 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1777 int table = mono_metadata_token_table (token);
1778 int idx = mono_metadata_token_index (token);
1779 MonoTableInfo *tables = image->tables;
1780 MonoGenericContainer *generic_container = NULL, *container = NULL;
1781 const char *sig = NULL;
1783 guint32 cols [MONO_TYPEDEF_SIZE];
1785 mono_error_init (error);
1787 if (image_is_dynamic (image)) {
1788 MonoClass *handle_class;
1790 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1791 g_assert (!mono_loader_get_last_error ());
1793 // This checks the memberref type as well
1794 if (result && handle_class != mono_defaults.methodhandle_class) {
1795 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1801 if (table != MONO_TABLE_METHOD) {
1802 if (table == MONO_TABLE_METHODSPEC) {
1803 if (used_context) *used_context = TRUE;
1804 return method_from_methodspec (image, context, idx, error);
1806 if (table != MONO_TABLE_MEMBERREF) {
1807 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1810 return method_from_memberref (image, idx, context, used_context, error);
1813 if (used_context) *used_context = FALSE;
1815 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1816 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1821 guint32 type = mono_metadata_typedef_from_method (image, token);
1823 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1826 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1831 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1833 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1834 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1835 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1837 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1838 methods_size += sizeof (MonoMethod);
1841 mono_stats.method_count ++;
1844 result->klass = klass;
1845 result->flags = cols [2];
1846 result->iflags = cols [1];
1847 result->token = token;
1848 result->name = mono_metadata_string_heap (image, cols [3]);
1850 if (!sig) /* already taken from the methodref */
1851 sig = mono_metadata_blob_heap (image, cols [4]);
1852 size = mono_metadata_decode_blob_size (sig, &sig);
1854 container = klass->generic_container;
1857 * load_generic_params does a binary search so only call it if the method
1861 generic_container = mono_metadata_load_generic_params (image, token, container);
1862 g_assert (!mono_loader_get_last_error ()); /* FIXME don't swallow this error. */
1864 if (generic_container) {
1865 result->is_generic = TRUE;
1866 generic_container->owner.method = result;
1867 /*FIXME put this before the image alloc*/
1868 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1871 container = generic_container;
1874 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1875 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1876 result->string_ctor = 1;
1877 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1878 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1881 /* IJW is P/Invoke with a predefined function pointer. */
1882 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1883 piinfo->addr = mono_image_rva_map (image, cols [0]);
1884 g_assert (piinfo->addr);
1887 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1888 /* Native methods can have no map. */
1889 if (piinfo->implmap_idx)
1890 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1893 if (generic_container)
1894 mono_method_set_generic_container (result, generic_container);
1896 g_assert (!mono_loader_get_last_error ());
1901 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1903 return mono_get_method_full (image, token, klass, NULL);
1907 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1908 MonoGenericContext *context)
1911 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
1912 g_assert (!mono_loader_get_last_error ());
1913 if (!mono_error_ok (&error)) {
1914 mono_loader_set_error_from_mono_error (&error);
1915 mono_error_cleanup (&error);
1921 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
1923 MonoMethod *result = NULL;
1924 gboolean used_context = FALSE;
1926 /* We do everything inside the lock to prevent creation races */
1928 mono_error_init (error);
1930 mono_image_lock (image);
1932 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1933 if (!image->method_cache)
1934 image->method_cache = g_hash_table_new (NULL, NULL);
1935 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1936 } else if (!image_is_dynamic (image)) {
1937 if (!image->methodref_cache)
1938 image->methodref_cache = g_hash_table_new (NULL, NULL);
1939 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1941 mono_image_unlock (image);
1947 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
1951 mono_image_lock (image);
1952 if (!used_context && !result->is_inflated) {
1953 MonoMethod *result2 = NULL;
1955 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1956 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1957 else if (!image_is_dynamic (image))
1958 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1961 mono_image_unlock (image);
1965 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1966 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1967 else if (!image_is_dynamic (image))
1968 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1971 mono_image_unlock (image);
1977 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
1980 MonoClass *ic = NULL;
1981 MonoGenericContext *method_context = NULL;
1982 MonoMethodSignature *sig, *original_sig;
1984 mono_error_init (error);
1986 mono_class_init (constrained_class);
1987 original_sig = sig = mono_method_signature_checked (method, error);
1992 if (method->is_inflated && sig->generic_param_count) {
1993 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1994 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1997 method_context = mono_method_get_context (method);
2001 * We must inflate the signature with the class instantiation to work on
2002 * cases where a class inherit from a generic type and the override replaces
2003 * any type argument which a concrete type. See #325283.
2005 if (method_context->class_inst) {
2006 MonoGenericContext ctx;
2007 ctx.method_inst = NULL;
2008 ctx.class_inst = method_context->class_inst;
2009 /*Fixme, property propagate this error*/
2010 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2016 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2019 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2020 if (sig != original_sig)
2021 mono_metadata_free_inflated_signature (sig);
2026 if (method_context) {
2027 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2036 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2037 MonoGenericContext *context, MonoError *error)
2041 return get_method_constrained (image, method, constrained_class, context, error);
2045 * mono_get_method_constrained:
2047 * This is used when JITing the `constrained.' opcode.
2049 * This returns two values: the contrained method, which has been inflated
2050 * as the function return value; And the original CIL-stream method as
2051 * declared in cil_method. The later is used for verification.
2054 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2055 MonoGenericContext *context, MonoMethod **cil_method)
2058 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2060 g_assert (!mono_loader_get_last_error ());
2061 if (!mono_error_ok (&error)) {
2062 mono_loader_set_error_from_mono_error (&error);
2063 mono_error_cleanup (&error);
2069 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2071 mono_error_init (error);
2073 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2077 return get_method_constrained (image, *cil_method, constrained_class, context, error);
2081 mono_free_method (MonoMethod *method)
2083 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2084 mono_profiler_method_free (method);
2086 /* FIXME: This hack will go away when the profiler will support freeing methods */
2087 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2090 if (method->signature) {
2092 * FIXME: This causes crashes because the types inside signatures and
2093 * locals are shared.
2095 /* mono_metadata_free_method_signature (method->signature); */
2096 /* g_free (method->signature); */
2099 if (method_is_dynamic (method)) {
2100 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2103 mono_marshal_free_dynamic_wrappers (method);
2105 mono_image_property_remove (method->klass->image, method);
2107 g_free ((char*)method->name);
2109 g_free ((char*)mw->header->code);
2110 for (i = 0; i < mw->header->num_locals; ++i)
2111 g_free (mw->header->locals [i]);
2112 g_free (mw->header->clauses);
2113 g_free (mw->header);
2115 g_free (mw->method_data);
2116 g_free (method->signature);
2122 mono_method_get_param_names (MonoMethod *method, const char **names)
2126 MonoTableInfo *methodt;
2127 MonoTableInfo *paramt;
2128 MonoMethodSignature *signature;
2131 if (method->is_inflated)
2132 method = ((MonoMethodInflated *) method)->declaring;
2134 signature = mono_method_signature (method);
2135 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2136 number of arguments and allocate a properly sized array. */
2137 if (signature == NULL)
2140 if (!signature->param_count)
2143 for (i = 0; i < signature->param_count; ++i)
2146 klass = method->klass;
2150 mono_class_init (klass);
2152 if (image_is_dynamic (klass->image)) {
2153 MonoReflectionMethodAux *method_aux =
2154 g_hash_table_lookup (
2155 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2156 if (method_aux && method_aux->param_names) {
2157 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2158 if (method_aux->param_names [i + 1])
2159 names [i] = method_aux->param_names [i + 1];
2164 if (method->wrapper_type) {
2165 char **pnames = NULL;
2167 mono_image_lock (klass->image);
2168 if (klass->image->wrapper_param_names)
2169 pnames = g_hash_table_lookup (klass->image->wrapper_param_names, method);
2170 mono_image_unlock (klass->image);
2173 for (i = 0; i < signature->param_count; ++i)
2174 names [i] = pnames [i];
2179 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2180 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2181 idx = mono_method_get_index (method);
2183 guint32 cols [MONO_PARAM_SIZE];
2186 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2188 if (idx < methodt->rows)
2189 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2191 lastp = paramt->rows + 1;
2192 for (i = param_index; i < lastp; ++i) {
2193 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2194 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2195 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2201 mono_method_get_param_token (MonoMethod *method, int index)
2203 MonoClass *klass = method->klass;
2204 MonoTableInfo *methodt;
2207 mono_class_init (klass);
2209 if (image_is_dynamic (klass->image))
2210 g_assert_not_reached ();
2212 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2213 idx = mono_method_get_index (method);
2215 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2219 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2221 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2228 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2231 MonoClass *klass = method->klass;
2232 MonoTableInfo *methodt;
2233 MonoTableInfo *paramt;
2234 MonoMethodSignature *signature;
2237 signature = mono_method_signature (method);
2238 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2240 for (i = 0; i < signature->param_count + 1; ++i)
2243 if (image_is_dynamic (method->klass->image)) {
2244 MonoReflectionMethodAux *method_aux =
2245 g_hash_table_lookup (
2246 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2247 if (method_aux && method_aux->param_marshall) {
2248 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2249 for (i = 0; i < signature->param_count + 1; ++i)
2250 if (dyn_specs [i]) {
2251 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2252 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2253 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2254 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2260 mono_class_init (klass);
2262 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2263 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2264 idx = mono_method_get_index (method);
2266 guint32 cols [MONO_PARAM_SIZE];
2267 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2269 if (idx < methodt->rows)
2270 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2272 lastp = paramt->rows + 1;
2274 for (i = param_index; i < lastp; ++i) {
2275 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2277 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2279 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2281 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2290 mono_method_has_marshal_info (MonoMethod *method)
2293 MonoClass *klass = method->klass;
2294 MonoTableInfo *methodt;
2295 MonoTableInfo *paramt;
2298 if (image_is_dynamic (method->klass->image)) {
2299 MonoReflectionMethodAux *method_aux =
2300 g_hash_table_lookup (
2301 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2302 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2304 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2311 mono_class_init (klass);
2313 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2314 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2315 idx = mono_method_get_index (method);
2317 guint32 cols [MONO_PARAM_SIZE];
2318 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2320 if (idx + 1 < methodt->rows)
2321 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2323 lastp = paramt->rows + 1;
2325 for (i = param_index; i < lastp; ++i) {
2326 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2328 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2337 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2340 g_assert (method != NULL);
2341 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2343 if (method->is_inflated)
2344 method = ((MonoMethodInflated *) method)->declaring;
2345 data = ((MonoMethodWrapper *)method)->method_data;
2346 g_assert (data != NULL);
2347 g_assert (id <= GPOINTER_TO_UINT (*data));
2354 } StackWalkUserData;
2357 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2359 StackWalkUserData *d = data;
2361 switch (frame->type) {
2362 case FRAME_TYPE_DEBUGGER_INVOKE:
2363 case FRAME_TYPE_MANAGED_TO_NATIVE:
2365 case FRAME_TYPE_MANAGED:
2366 g_assert (frame->ji);
2367 return d->func (mono_jit_info_get_method (frame->ji), frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2370 g_assert_not_reached ();
2376 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2378 StackWalkUserData ud = { func, user_data };
2379 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2383 mono_stack_walk_no_il (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_DEFAULT, &ud);
2390 MonoStackWalkAsyncSafe func;
2392 } AsyncStackWalkUserData;
2396 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2398 AsyncStackWalkUserData *d = data;
2400 switch (frame->type) {
2401 case FRAME_TYPE_DEBUGGER_INVOKE:
2402 case FRAME_TYPE_MANAGED_TO_NATIVE:
2404 case FRAME_TYPE_MANAGED:
2407 if (frame->ji->async)
2408 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2410 return d->func (mono_jit_info_get_method (frame->ji), frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2413 g_assert_not_reached ();
2420 * mono_stack_walk_async_safe:
2422 * Async safe version callable from signal handlers.
2425 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2428 AsyncStackWalkUserData ud = { func, user_data };
2430 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2431 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2435 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2437 MonoMethod **dest = data;
2439 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2445 mono_method_get_last_managed (void)
2447 MonoMethod *m = NULL;
2448 mono_stack_walk_no_il (last_managed, &m);
2452 static gboolean loader_lock_track_ownership = FALSE;
2457 * See docs/thread-safety.txt for the locking strategy.
2460 mono_loader_lock (void)
2462 mono_locks_acquire (&loader_mutex, LoaderLock);
2463 if (G_UNLIKELY (loader_lock_track_ownership)) {
2464 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));
2469 mono_loader_unlock (void)
2471 mono_locks_release (&loader_mutex, LoaderLock);
2472 if (G_UNLIKELY (loader_lock_track_ownership)) {
2473 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));
2478 * mono_loader_lock_track_ownership:
2480 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2481 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2482 * thread owns the loader lock.
2485 mono_loader_lock_track_ownership (gboolean track)
2487 loader_lock_track_ownership = track;
2491 * mono_loader_lock_is_owned_by_self:
2493 * Return whenever the current thread owns the loader lock.
2494 * This is useful to avoid blocking operations while holding the loader lock.
2497 mono_loader_lock_is_owned_by_self (void)
2499 g_assert (loader_lock_track_ownership);
2501 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2505 * mono_loader_lock_if_inited:
2507 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2508 * be used in runtime initialization code which can be executed before mono_loader_init ().
2511 mono_loader_lock_if_inited (void)
2513 if (loader_lock_inited)
2514 mono_loader_lock ();
2518 mono_loader_unlock_if_inited (void)
2520 if (loader_lock_inited)
2521 mono_loader_unlock ();
2525 * mono_method_signature:
2527 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2529 MonoMethodSignature*
2530 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2536 gboolean can_cache_signature;
2537 MonoGenericContainer *container;
2538 MonoMethodSignature *signature = NULL, *sig2;
2541 /* We need memory barriers below because of the double-checked locking pattern */
2543 mono_error_init (error);
2546 return m->signature;
2548 img = m->klass->image;
2550 if (m->is_inflated) {
2551 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2552 /* the lock is recursive */
2553 signature = mono_method_signature (imethod->declaring);
2554 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2555 if (!mono_error_ok (error))
2558 inflated_signatures_size += mono_metadata_signature_size (signature);
2560 mono_image_lock (img);
2562 mono_memory_barrier ();
2564 m->signature = signature;
2566 mono_image_unlock (img);
2568 return m->signature;
2571 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2572 idx = mono_metadata_token_index (m->token);
2574 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2576 g_assert (!m->klass->generic_class);
2577 container = mono_method_get_generic_container (m);
2579 container = m->klass->generic_container;
2581 /* Generic signatures depend on the container so they cannot be cached */
2582 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2583 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2585 /* If the method has parameter attributes, that can modify the signature */
2586 if (mono_metadata_method_has_param_attrs (img, idx))
2587 can_cache_signature = FALSE;
2589 if (can_cache_signature) {
2590 mono_image_lock (img);
2591 signature = g_hash_table_lookup (img->method_signatures, sig);
2592 mono_image_unlock (img);
2596 const char *sig_body;
2597 /*TODO we should cache the failure result somewhere*/
2598 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2601 size = mono_metadata_decode_blob_size (sig, &sig_body);
2603 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2607 if (can_cache_signature) {
2608 mono_image_lock (img);
2609 sig2 = g_hash_table_lookup (img->method_signatures, sig);
2611 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2612 mono_image_unlock (img);
2615 signatures_size += mono_metadata_signature_size (signature);
2618 /* Verify metadata consistency */
2619 if (signature->generic_param_count) {
2620 if (!container || !container->is_method) {
2621 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);
2624 if (container->type_argc != signature->generic_param_count) {
2625 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);
2628 } else if (container && container->is_method && container->type_argc) {
2629 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);
2632 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2633 signature->pinvoke = 1;
2634 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2635 MonoCallConvention conv = 0;
2636 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2637 signature->pinvoke = 1;
2639 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2640 case 0: /* no call conv, so using default */
2641 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2642 conv = MONO_CALL_DEFAULT;
2644 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2647 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2648 conv = MONO_CALL_STDCALL;
2650 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2651 conv = MONO_CALL_THISCALL;
2653 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2654 conv = MONO_CALL_FASTCALL;
2656 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2657 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2659 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);
2662 signature->call_convention = conv;
2665 mono_image_lock (img);
2667 mono_memory_barrier ();
2669 m->signature = signature;
2671 mono_image_unlock (img);
2673 return m->signature;
2677 * mono_method_signature:
2679 * Return the signature of the method M. On failure, returns NULL.
2681 MonoMethodSignature*
2682 mono_method_signature (MonoMethod *m)
2685 MonoMethodSignature *sig;
2687 sig = mono_method_signature_checked (m, &error);
2689 char *type_name = mono_type_get_full_name (m->klass);
2690 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2692 mono_error_cleanup (&error);
2699 mono_method_get_name (MonoMethod *method)
2701 return method->name;
2705 mono_method_get_class (MonoMethod *method)
2707 return method->klass;
2711 mono_method_get_token (MonoMethod *method)
2713 return method->token;
2717 mono_method_get_header (MonoMethod *method)
2723 MonoMethodHeader *header;
2724 MonoGenericContainer *container;
2726 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))
2729 img = method->klass->image;
2731 if (method->is_inflated) {
2732 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2733 MonoMethodHeader *header, *iheader;
2735 header = mono_method_get_header (imethod->declaring);
2739 iheader = inflate_generic_header (header, mono_method_get_context (method));
2740 mono_metadata_free_mh (header);
2742 mono_image_lock (img);
2744 if (imethod->header) {
2745 mono_metadata_free_mh (iheader);
2746 mono_image_unlock (img);
2747 return imethod->header;
2750 mono_memory_barrier ();
2751 imethod->header = iheader;
2753 mono_image_unlock (img);
2755 return imethod->header;
2758 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2759 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2760 g_assert (mw->header);
2765 * We don't need locks here: the new header is allocated from malloc memory
2766 * and is not stored anywhere in the runtime, the user needs to free it.
2768 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2769 idx = mono_metadata_token_index (method->token);
2770 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2772 if (!mono_verifier_verify_method_header (img, rva, NULL))
2775 loc = mono_image_rva_map (img, rva);
2780 * When parsing the types of local variables, we must pass any container available
2781 * to ensure that both VAR and MVAR will get the right owner.
2783 container = mono_method_get_generic_container (method);
2785 container = method->klass->generic_container;
2786 header = mono_metadata_parse_mh_full (img, container, loc);
2792 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2795 *iflags = method->iflags;
2796 return method->flags;
2800 * Find the method index in the metadata methodDef table.
2803 mono_method_get_index (MonoMethod *method)
2805 MonoClass *klass = method->klass;
2809 /* constructed array methods are not in the MethodDef table */
2813 return mono_metadata_token_index (method->token);
2815 mono_class_setup_methods (klass);
2816 if (klass->exception_type)
2818 for (i = 0; i < klass->method.count; ++i) {
2819 if (method == klass->methods [i]) {
2820 if (klass->image->uncompressed_metadata)
2821 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2823 return klass->method.first + i + 1;