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.
20 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
27 #include <mono/metadata/metadata.h>
28 #include <mono/metadata/image.h>
29 #include <mono/metadata/assembly.h>
30 #include <mono/metadata/tokentype.h>
31 #include <mono/metadata/tabledefs.h>
32 #include <mono/metadata/metadata-internals.h>
33 #include <mono/metadata/loader.h>
34 #include <mono/metadata/class-internals.h>
35 #include <mono/metadata/debug-helpers.h>
36 #include <mono/metadata/reflection.h>
37 #include <mono/metadata/profiler.h>
38 #include <mono/metadata/profiler-private.h>
39 #include <mono/metadata/exception.h>
40 #include <mono/metadata/marshal.h>
41 #include <mono/metadata/lock-tracer.h>
42 #include <mono/metadata/verify-internals.h>
43 #include <mono/utils/mono-logger-internals.h>
44 #include <mono/utils/mono-dl.h>
45 #include <mono/utils/mono-membar.h>
46 #include <mono/utils/mono-counters.h>
47 #include <mono/utils/mono-error-internals.h>
48 #include <mono/utils/mono-tls.h>
49 #include <mono/utils/mono-path.h>
51 MonoDefaults mono_defaults;
54 * This lock protects the hash tables inside MonoImage used by the metadata
55 * loading functions in class.c and loader.c.
57 * See domain-internals.h for locking policy in combination with the
60 static MonoCoopMutex loader_mutex;
61 static mono_mutex_t global_loader_data_mutex;
62 static gboolean loader_lock_inited;
65 static guint32 inflated_signatures_size;
66 static guint32 memberref_sig_cache_size;
67 static guint32 methods_size;
68 static guint32 signatures_size;
71 * This TLS variable contains the last type load error encountered by the loader.
73 MonoNativeTlsKey loader_error_thread_id;
76 * This TLS variable holds how many times the current thread has acquired the loader
79 MonoNativeTlsKey loader_lock_nest_id;
81 static void dllmap_cleanup (void);
85 global_loader_data_lock (void)
87 mono_locks_os_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
91 global_loader_data_unlock (void)
93 mono_locks_os_release (&global_loader_data_mutex, LoaderGlobalDataLock);
99 static gboolean inited;
102 mono_coop_mutex_init_recursive (&loader_mutex);
103 mono_os_mutex_init_recursive (&global_loader_data_mutex);
104 loader_lock_inited = TRUE;
106 mono_native_tls_alloc (&loader_error_thread_id, NULL);
107 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
109 mono_counters_init ();
110 mono_counters_register ("Inflated signatures size",
111 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
112 mono_counters_register ("Memberref signature cache size",
113 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
114 mono_counters_register ("MonoMethod size",
115 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
116 mono_counters_register ("MonoMethodSignature size",
117 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
124 mono_loader_cleanup (void)
128 mono_native_tls_free (loader_error_thread_id);
129 mono_native_tls_free (loader_lock_nest_id);
131 mono_coop_mutex_destroy (&loader_mutex);
132 mono_os_mutex_destroy (&global_loader_data_mutex);
133 loader_lock_inited = FALSE;
137 * Handling of type load errors should be done as follows:
139 * If something could not be loaded, the loader should call one of the
140 * mono_loader_set_error_XXX functions ()
141 * with the appropriate arguments, then return NULL to report the failure. The error
142 * should be propagated until it reaches code which can throw managed exceptions. At that
143 * point, an exception should be thrown based on the information returned by
144 * mono_loader_get_last_error (). Then the error should be cleared by calling
145 * mono_loader_clear_error ().
149 set_loader_error (MonoLoaderError *error)
151 mono_loader_clear_error ();
152 mono_native_tls_set_value (loader_error_thread_id, error);
156 * mono_loader_set_error_assembly_load:
158 * Set the loader error for this thread.
161 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
163 MonoLoaderError *error;
165 if (mono_loader_get_last_error ())
168 error = g_new0 (MonoLoaderError, 1);
169 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
170 error->assembly_name = g_strdup (assembly_name);
171 error->ref_only = ref_only;
174 * This is not strictly needed, but some (most) of the loader code still
175 * can't deal with load errors, and this message is more helpful than an
179 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);
181 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
183 set_loader_error (error);
187 * mono_loader_set_error_type_load:
189 * Set the loader error for this thread.
192 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
194 MonoLoaderError *error;
196 if (mono_loader_get_last_error ())
199 error = g_new0 (MonoLoaderError, 1);
200 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
201 error->class_name = g_strdup (class_name);
202 error->assembly_name = g_strdup (assembly_name);
205 * This is not strictly needed, but some (most) of the loader code still
206 * can't deal with load errors, and this message is more helpful than an
209 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
211 set_loader_error (error);
215 * mono_loader_set_error_method_load:
217 * Set the loader error for this thread. MEMBER_NAME should point to a string
221 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
223 MonoLoaderError *error;
225 /* FIXME: Store the signature as well */
226 if (mono_loader_get_last_error ())
229 error = g_new0 (MonoLoaderError, 1);
230 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
231 error->class_name = g_strdup (class_name);
232 error->member_name = member_name;
234 set_loader_error (error);
238 * mono_loader_set_error_field_load:
240 * Set the loader error for this thread. MEMBER_NAME should point to a string
244 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
246 MonoLoaderError *error;
248 /* FIXME: Store the signature as well */
249 if (mono_loader_get_last_error ())
252 error = g_new0 (MonoLoaderError, 1);
253 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
254 error->klass = klass;
255 error->member_name = member_name;
257 set_loader_error (error);
261 * mono_loader_set_error_bad_image:
263 * Set the loader error for this thread.
266 mono_loader_set_error_bad_image (char *msg)
268 MonoLoaderError *error;
270 if (mono_loader_get_last_error ())
273 error = g_new0 (MonoLoaderError, 1);
274 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
277 set_loader_error (error);
282 * mono_loader_get_last_error:
284 * Returns information about the last type load exception encountered by the loader, or
285 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
288 mono_loader_get_last_error (void)
290 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
294 mono_loader_assert_no_error (void)
296 MonoLoaderError *error = mono_loader_get_last_error ();
299 g_print ("Unhandled loader error: %x, %s %s %s\n", error->exception_type, error->msg, error->assembly_name, error->class_name);
300 g_assert_not_reached ();
305 * mono_loader_clear_error:
307 * Disposes any loader error messages on this thread
310 mono_loader_clear_error (void)
312 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
315 g_free (ex->class_name);
316 g_free (ex->assembly_name);
320 mono_native_tls_set_value (loader_error_thread_id, NULL);
325 * mono_loader_error_prepare_exception:
326 * @error: The MonoLoaderError to turn into an exception
328 * This turns a MonoLoaderError into an exception that can be thrown
329 * and resets the Mono Loader Error state during this process.
333 mono_loader_error_prepare_exception (MonoLoaderError *error)
335 MonoException *ex = NULL;
337 switch (error->exception_type) {
338 case MONO_EXCEPTION_TYPE_LOAD: {
339 char *cname = g_strdup (error->class_name);
340 char *aname = g_strdup (error->assembly_name);
341 MonoString *class_name;
343 mono_loader_clear_error ();
345 class_name = mono_string_new (mono_domain_get (), cname);
347 ex = mono_get_exception_type_load (class_name, aname);
352 case MONO_EXCEPTION_MISSING_METHOD: {
353 char *cname = g_strdup (error->class_name);
354 char *aname = g_strdup (error->member_name);
356 mono_loader_clear_error ();
357 ex = mono_get_exception_missing_method (cname, aname);
363 case MONO_EXCEPTION_MISSING_FIELD: {
365 char *cmembername = g_strdup (error->member_name);
367 class_name = mono_type_get_full_name (error->klass);
369 class_name = g_strdup ("");
371 mono_loader_clear_error ();
373 ex = mono_get_exception_missing_field (class_name, cmembername);
375 g_free (cmembername);
379 case MONO_EXCEPTION_FILE_NOT_FOUND: {
384 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);
386 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
387 filename = g_strdup (error->assembly_name);
388 /* Has to call this before calling anything which might call mono_class_init () */
389 mono_loader_clear_error ();
390 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
396 case MONO_EXCEPTION_BAD_IMAGE: {
397 char *msg = g_strdup (error->msg);
398 mono_loader_clear_error ();
399 ex = mono_get_exception_bad_image_format (msg);
405 g_assert_not_reached ();
412 * find_cached_memberref_sig:
414 * Return a cached copy of the memberref signature identified by SIG_IDX.
415 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
416 * A cache is needed since the type/signature parsing routines allocate everything
417 * from a mempool, so without a cache, multiple requests for the same signature would
418 * lead to unbounded memory growth. For normal methods/fields this is not a problem
419 * since the resulting methods/fields are cached, but inflated methods/fields cannot
421 * LOCKING: Acquires the loader lock.
424 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
428 mono_image_lock (image);
429 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
430 mono_image_unlock (image);
436 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
440 mono_image_lock (image);
441 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
443 /* Somebody got in before us */
447 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
448 /* An approximation based on glib 2.18 */
449 memberref_sig_cache_size += sizeof (gpointer) * 4;
451 mono_image_unlock (image);
456 static MonoClassField*
457 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
458 MonoGenericContext *context, MonoError *error)
460 MonoClass *klass = NULL;
461 MonoClassField *field;
462 MonoTableInfo *tables = image->tables;
465 guint32 nindex, class_index;
468 guint32 idx = mono_metadata_token_index (token);
470 mono_error_init (error);
472 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
473 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
474 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
476 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
478 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
479 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class_index, token);
483 switch (class_index) {
484 case MONO_MEMBERREF_PARENT_TYPEDEF:
485 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
487 case MONO_MEMBERREF_PARENT_TYPEREF:
488 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
490 case MONO_MEMBERREF_PARENT_TYPESPEC:
491 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
494 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class_index, token);
500 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
501 mono_metadata_decode_blob_size (ptr, &ptr);
502 /* we may want to check the signature here... */
505 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class_index, fname, token);
509 /* FIXME: This needs a cache, especially for generic instances, since
510 * we ask mono_metadata_parse_type_checked () to allocates everything from a mempool.
511 * FIXME part2, mono_metadata_parse_type_checked actually allows for a transient type instead.
512 * FIXME part3, transient types are not 100% transient, so we need to take care of that first.
514 sig_type = (MonoType *)find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
516 MonoError inner_error;
517 sig_type = mono_metadata_parse_type_checked (image, NULL, 0, FALSE, ptr, &ptr, &inner_error);
518 if (sig_type == NULL) {
519 mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x due to: %s", fname, token, mono_error_get_message (&inner_error));
520 mono_error_cleanup (&inner_error);
523 sig_type = (MonoType *)cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
526 mono_class_init (klass); /*FIXME is this really necessary?*/
529 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
532 mono_loader_assert_no_error ();
533 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
540 * mono_field_from_token:
541 * @deprecated use the _checked variant
542 * Notes: runtime code MUST not use this function
545 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
548 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
549 g_assert (mono_error_ok (&error));
554 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
558 MonoClassField *field;
560 mono_error_init (error);
562 if (image_is_dynamic (image)) {
563 MonoClassField *result;
564 MonoClass *handle_class;
567 MonoError inner_error;
568 result = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, &inner_error);
569 mono_error_cleanup (&inner_error);
570 // This checks the memberref type as well
571 if (!result || handle_class != mono_defaults.fieldhandle_class) {
572 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
575 *retklass = result->parent;
579 if ((field = (MonoClassField *)mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
580 *retklass = field->parent;
584 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
585 field = field_from_memberref (image, token, retklass, context, error);
586 mono_loader_assert_no_error ();
588 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
590 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
593 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
600 field = mono_class_get_field (k, token);
602 if (mono_loader_get_last_error ())
603 mono_error_set_from_loader_error (error);
605 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
609 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container) {
610 mono_image_lock (image);
611 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
612 mono_image_unlock (image);
615 mono_loader_assert_no_error ();
620 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
624 if (sig1->hasthis != sig2->hasthis ||
625 sig1->sentinelpos != sig2->sentinelpos)
628 for (i = 0; i < sig1->sentinelpos; i++) {
629 MonoType *p1 = sig1->params[i];
630 MonoType *p2 = sig2->params[i];
632 /*if (p1->attrs != p2->attrs)
635 if (!mono_metadata_type_equal (p1, p2))
639 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
645 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
646 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
650 /* Search directly in the metadata to avoid calling setup_methods () */
651 mono_error_init (error);
653 /* FIXME: !from_class->generic_class condition causes test failures. */
654 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
655 for (i = 0; i < klass->method.count; ++i) {
656 guint32 cols [MONO_METHOD_SIZE];
659 MonoMethodSignature *other_sig;
661 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
663 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
665 if (!((fqname && !strcmp (m_name, fqname)) ||
666 (qname && !strcmp (m_name, qname)) ||
667 (name && !strcmp (m_name, name))))
670 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
671 if (!mono_error_ok (error)) //bail out if we hit a loader error
674 other_sig = mono_method_signature_checked (method, error);
675 if (!mono_error_ok (error)) //bail out if we hit a loader error
677 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
683 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
685 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
686 See mono/tests/generic-type-load-exception.2.il
687 FIXME we should better report this error to the caller
689 if (!klass->methods || mono_class_has_failure (klass)) {
690 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
694 for (i = 0; i < klass->method.count; ++i) {
695 MonoMethod *m = klass->methods [i];
696 MonoMethodSignature *msig;
698 /* We must cope with failing to load some of the types. */
702 if (!((fqname && !strcmp (m->name, fqname)) ||
703 (qname && !strcmp (m->name, qname)) ||
704 (name && !strcmp (m->name, name))))
706 msig = mono_method_signature_checked (m, error);
707 if (!mono_error_ok (error)) //bail out if we hit a loader error
713 if (sig->call_convention == MONO_CALL_VARARG) {
714 if (mono_metadata_signature_vararg_match (sig, msig))
717 if (mono_metadata_signature_equal (sig, msig))
722 if (i < klass->method.count)
723 return mono_class_get_method_by_index (from_class, i);
728 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
731 char *qname, *fqname, *class_name;
732 gboolean is_interface;
733 MonoMethod *result = NULL;
734 MonoClass *initial_class = in_class;
736 mono_error_init (error);
737 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
740 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
742 qname = g_strconcat (class_name, ".", name, NULL);
743 if (ic->name_space && ic->name_space [0])
744 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
748 class_name = qname = fqname = NULL;
751 g_assert (from_class);
752 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
753 if (result || !mono_error_ok (error))
756 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
760 * This happens when we fail to lazily load the interfaces of one of the types.
761 * On such case we can't just bail out since user code depends on us trying harder.
763 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
764 in_class = in_class->parent;
765 from_class = from_class->parent;
769 for (i = 0; i < in_class->interface_offsets_count; i++) {
770 MonoClass *in_ic = in_class->interfaces_packed [i];
771 MonoClass *from_ic = from_class->interfaces_packed [i];
772 char *ic_qname, *ic_fqname, *ic_class_name;
774 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
775 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
776 if (in_ic->name_space && in_ic->name_space [0])
777 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
781 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
782 g_free (ic_class_name);
785 if (result || !mono_error_ok (error))
789 in_class = in_class->parent;
790 from_class = from_class->parent;
792 g_assert (!in_class == !from_class);
795 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
797 //we did not find the method
798 if (!result && mono_error_ok (error)) {
799 char *desc = mono_signature_get_desc (sig, FALSE);
800 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
811 static MonoMethodSignature*
812 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
814 MonoMethodSignature *res;
818 mono_error_init (error);
822 res = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
823 res->param_count = sig->param_count;
824 res->sentinelpos = -1;
825 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
826 if (!mono_error_ok (error))
828 is_open = mono_class_is_open_constructed_type (res->ret);
829 for (i = 0; i < sig->param_count; ++i) {
830 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
831 if (!mono_error_ok (error))
835 is_open = mono_class_is_open_constructed_type (res->params [i]);
837 res->hasthis = sig->hasthis;
838 res->explicit_this = sig->explicit_this;
839 res->call_convention = sig->call_convention;
840 res->pinvoke = sig->pinvoke;
841 res->generic_param_count = sig->generic_param_count;
842 res->sentinelpos = sig->sentinelpos;
843 res->has_type_parameters = is_open;
844 res->is_inflated = 1;
849 mono_metadata_free_type (res->ret);
850 for (i = 0; i < sig->param_count; ++i) {
852 mono_metadata_free_type (res->params [i]);
859 * mono_inflate_generic_signature:
861 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
864 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
866 MonoMethodSignature *res, *cached;
868 res = inflate_generic_signature_checked (NULL, sig, context, error);
869 if (!mono_error_ok (error))
871 cached = mono_metadata_get_inflated_signature (res, context);
873 mono_metadata_free_inflated_signature (res);
877 static MonoMethodHeader*
878 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context, MonoError *error)
880 size_t locals_size = sizeof (gpointer) * header->num_locals;
881 size_t clauses_size = header->num_clauses * sizeof (MonoExceptionClause);
882 size_t header_size = MONO_SIZEOF_METHOD_HEADER + locals_size + clauses_size;
883 MonoMethodHeader *res = (MonoMethodHeader *)g_malloc0 (header_size);
884 res->num_locals = header->num_locals;
885 res->clauses = (MonoExceptionClause *) &res->locals [res->num_locals] ;
886 memcpy (res->clauses, header->clauses, clauses_size);
888 res->code = header->code;
889 res->code_size = header->code_size;
890 res->max_stack = header->max_stack;
891 res->num_clauses = header->num_clauses;
892 res->init_locals = header->init_locals;
894 res->is_transient = TRUE;
896 mono_error_init (error);
898 for (int i = 0; i < header->num_locals; ++i) {
899 res->locals [i] = mono_class_inflate_generic_type_checked (header->locals [i], context, error);
903 if (res->num_clauses) {
904 for (int i = 0; i < header->num_clauses; ++i) {
905 MonoExceptionClause *clause = &res->clauses [i];
906 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
908 clause->data.catch_class = mono_class_inflate_generic_class_checked (clause->data.catch_class, context, error);
920 * token is the method_ref/def/spec token used in a call IL instruction.
921 * @deprecated use the _checked variant
922 * Notes: runtime code MUST not use this function
925 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
928 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
929 mono_error_cleanup (&error);
934 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
936 int table = mono_metadata_token_table (token);
937 int idx = mono_metadata_token_index (token);
939 guint32 cols [MONO_MEMBERREF_SIZE];
940 MonoMethodSignature *sig;
943 mono_error_init (error);
945 /* !table is for wrappers: we should really assign their own token to them */
946 if (!table || table == MONO_TABLE_METHOD)
947 return mono_method_signature_checked (method, error);
949 if (table == MONO_TABLE_METHODSPEC) {
950 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
951 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated) {
952 mono_error_set_bad_image (error, image, "Method is a pinvoke or open generic");
956 return mono_method_signature_checked (method, error);
959 if (method->klass->generic_class)
960 return mono_method_signature_checked (method, error);
962 if (image_is_dynamic (image)) {
963 sig = mono_reflection_lookup_signature (image, method, token, error);
967 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
968 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
970 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
972 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
973 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
974 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
976 //FIXME include the verification error
977 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
981 ptr = mono_metadata_blob_heap (image, sig_idx);
982 mono_metadata_decode_blob_size (ptr, &ptr);
984 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
988 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
990 /* FIXME: we probably should verify signature compat in the dynamic case too*/
991 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
992 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
993 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
995 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
1001 MonoMethodSignature *cached;
1003 /* This signature is not owned by a MonoMethod, so need to cache */
1004 sig = inflate_generic_signature_checked (image, sig, context, error);
1005 if (!mono_error_ok (error))
1008 cached = mono_metadata_get_inflated_signature (sig, context);
1010 mono_metadata_free_inflated_signature (sig);
1012 inflated_signatures_size += mono_metadata_signature_size (cached);
1016 g_assert (mono_error_ok (error));
1021 * token is the method_ref/def/spec token used in a call IL instruction.
1022 * @deprecated use the _checked variant
1023 * Notes: runtime code MUST not use this function
1025 MonoMethodSignature*
1026 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
1029 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
1030 mono_error_cleanup (&error);
1034 /* this is only for the typespec array methods */
1036 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1040 mono_class_setup_methods (klass);
1041 g_assert (!mono_class_has_failure (klass)); /*FIXME this should not fail, right?*/
1042 for (i = 0; i < klass->method.count; ++i) {
1043 MonoMethod *method = klass->methods [i];
1044 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1051 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1052 gboolean *used_context, MonoError *error)
1054 MonoClass *klass = NULL;
1055 MonoMethod *method = NULL;
1056 MonoTableInfo *tables = image->tables;
1058 guint32 nindex, class_index, sig_idx;
1060 MonoMethodSignature *sig;
1063 mono_error_init (error);
1065 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1066 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1067 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1068 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1069 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1071 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1074 * Whether we actually used the `typespec_context' or not.
1075 * This is used to tell our caller whether or not it's safe to insert the returned
1076 * method into a cache.
1079 *used_context = class_index == MONO_MEMBERREF_PARENT_TYPESPEC;
1081 switch (class_index) {
1082 case MONO_MEMBERREF_PARENT_TYPEREF:
1083 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1087 case MONO_MEMBERREF_PARENT_TYPESPEC:
1089 * Parse the TYPESPEC in the parent's context.
1091 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1095 case MONO_MEMBERREF_PARENT_TYPEDEF:
1096 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1100 case MONO_MEMBERREF_PARENT_METHODDEF: {
1101 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1107 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class_index, nindex);
1112 mono_class_init (klass);
1114 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1116 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1117 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1121 ptr = mono_metadata_blob_heap (image, sig_idx);
1122 mono_metadata_decode_blob_size (ptr, &ptr);
1124 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
1126 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1130 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
1133 switch (class_index) {
1134 case MONO_MEMBERREF_PARENT_TYPEREF:
1135 case MONO_MEMBERREF_PARENT_TYPEDEF:
1136 method = find_method (klass, NULL, mname, sig, klass, error);
1139 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1142 type = &klass->byval_arg;
1144 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1145 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1146 method = find_method (in_class, NULL, mname, sig, klass, error);
1150 /* we're an array and we created these methods already in klass in mono_class_init () */
1151 method = mono_method_search_in_array_class (klass, mname, sig);
1155 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class_index, nindex);
1159 if (!method && mono_error_ok (error)) {
1160 char *msig = mono_signature_get_desc (sig, FALSE);
1161 GString *s = g_string_new (mname);
1162 if (sig->generic_param_count)
1163 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1164 g_string_append_printf (s, "(%s)", msig);
1166 msig = g_string_free (s, FALSE);
1168 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1169 mono_error_set_from_loader_error (error);
1171 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1176 mono_loader_assert_no_error ();
1180 mono_loader_assert_no_error ();
1181 g_assert (!mono_error_ok (error));
1186 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1190 MonoTableInfo *tables = image->tables;
1191 MonoGenericContext new_context;
1192 MonoGenericInst *inst;
1194 guint32 cols [MONO_METHODSPEC_SIZE];
1195 guint32 token, nindex, param_count;
1197 mono_error_init (error);
1199 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1200 token = cols [MONO_METHODSPEC_METHOD];
1201 nindex = token >> MONO_METHODDEFORREF_BITS;
1203 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1204 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1208 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1210 mono_metadata_decode_value (ptr, &ptr);
1212 param_count = mono_metadata_decode_value (ptr, &ptr);
1214 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr, error);
1218 if (context && inst->is_open) {
1219 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1220 if (!mono_error_ok (error))
1224 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1225 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1229 method = method_from_memberref (image, nindex, context, NULL, error);
1235 klass = method->klass;
1237 if (klass->generic_class) {
1238 g_assert (method->is_inflated);
1239 method = ((MonoMethodInflated *) method)->declaring;
1242 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1243 new_context.method_inst = inst;
1245 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1246 mono_loader_assert_no_error ();
1250 struct _MonoDllMap {
1258 static MonoDllMap *global_dll_map;
1261 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1269 global_loader_data_lock ();
1272 * we use the first entry we find that matches, since entries from
1273 * the config file are prepended to the list and we document that the
1274 * later entries win.
1276 for (; dll_map; dll_map = dll_map->next) {
1277 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1278 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1280 } else if (strcmp (dll_map->dll, dll)) {
1283 if (!found && dll_map->target) {
1284 *rdll = dll_map->target;
1286 /* we don't quit here, because we could find a full
1287 * entry that matches also function and that has priority.
1290 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1291 *rfunc = dll_map->target_func;
1296 global_loader_data_unlock ();
1301 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1304 if (assembly && assembly->dll_map) {
1305 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1309 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1313 * mono_dllmap_insert:
1314 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1315 * @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
1316 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1317 * @tdll: The name of the library to map the specified @dll if it matches.
1318 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1320 * LOCKING: Acquires the loader lock.
1322 * This function is used to programatically add DllImport remapping in either
1323 * a specific assembly, or as a global remapping. This is done by remapping
1324 * references in a DllImport attribute from the @dll library name into the @tdll
1325 * name. If the @dll name contains the prefix "i:", the comparison of the
1326 * library name is done without case sensitivity.
1328 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1329 * or the name of the function as determined by DllImport. If you pass @func, you
1330 * must also pass @tfunc which is the name of the target function to invoke on a match.
1333 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1335 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1336 * the contents of relocated_demo_path for all assemblies in the Mono process.
1338 * NOTE: This can be called before the runtime is initialized, for example from
1339 * mono_config_parse ().
1342 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1346 mono_loader_init ();
1349 entry = (MonoDllMap *)g_malloc0 (sizeof (MonoDllMap));
1350 entry->dll = dll? g_strdup (dll): NULL;
1351 entry->target = tdll? g_strdup (tdll): NULL;
1352 entry->func = func? g_strdup (func): NULL;
1353 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1355 global_loader_data_lock ();
1356 entry->next = global_dll_map;
1357 global_dll_map = entry;
1358 global_loader_data_unlock ();
1360 entry = (MonoDllMap *)mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1361 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1362 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1363 entry->func = func? mono_image_strdup (assembly, func): NULL;
1364 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1366 mono_image_lock (assembly);
1367 entry->next = assembly->dll_map;
1368 assembly->dll_map = entry;
1369 mono_image_unlock (assembly);
1374 free_dllmap (MonoDllMap *map)
1377 MonoDllMap *next = map->next;
1380 g_free (map->target);
1382 g_free (map->target_func);
1389 dllmap_cleanup (void)
1391 free_dllmap (global_dll_map);
1392 global_dll_map = NULL;
1395 static GHashTable *global_module_map;
1398 cached_module_load (const char *name, int flags, char **err)
1404 global_loader_data_lock ();
1405 if (!global_module_map)
1406 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1407 res = (MonoDl *)g_hash_table_lookup (global_module_map, name);
1409 global_loader_data_unlock ();
1412 res = mono_dl_open (name, flags, err);
1414 g_hash_table_insert (global_module_map, g_strdup (name), res);
1415 global_loader_data_unlock ();
1419 static MonoDl *internal_module;
1422 is_absolute_path (const char *path)
1424 #ifdef PLATFORM_MACOSX
1425 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1426 !strncmp (path, "@rpath/", 7))
1429 return g_path_is_absolute (path);
1433 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1435 MonoImage *image = method->klass->image;
1436 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1437 MonoTableInfo *tables = image->tables;
1438 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1439 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1440 guint32 im_cols [MONO_IMPLMAP_SIZE];
1441 guint32 scope_token;
1442 const char *import = NULL;
1443 const char *orig_scope;
1444 const char *new_scope;
1446 char *full_name, *file_name, *found_name = NULL;
1448 MonoDl *module = NULL;
1449 gboolean cached = FALSE;
1451 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1459 return piinfo->addr;
1461 if (image_is_dynamic (method->klass->image)) {
1462 MonoReflectionMethodAux *method_aux =
1463 (MonoReflectionMethodAux *)g_hash_table_lookup (
1464 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1468 import = method_aux->dllentry;
1469 orig_scope = method_aux->dll;
1472 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1475 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1477 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1480 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1481 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1482 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1483 orig_scope = mono_metadata_string_heap (image, scope_token);
1486 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1489 mono_image_lock (image);
1490 if (!image->pinvoke_scopes) {
1491 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1492 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1494 module = (MonoDl *)g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1495 found_name = (char *)g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1496 mono_image_unlock (image);
1500 found_name = g_strdup (found_name);
1504 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1505 "DllImport attempting to load: '%s'.", new_scope);
1507 /* we allow a special name to dlopen from the running process namespace */
1508 if (strcmp (new_scope, "__Internal") == 0){
1509 if (internal_module == NULL)
1510 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1511 module = internal_module;
1516 * Try loading the module using a variety of names
1518 for (i = 0; i < 5; ++i) {
1519 char *base_name = NULL, *dir_name = NULL;
1520 gboolean is_absolute = is_absolute_path (new_scope);
1524 /* Try the original name */
1525 file_name = g_strdup (new_scope);
1528 /* Try trimming the .dll extension */
1529 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1530 file_name = g_strdup (new_scope);
1531 file_name [strlen (new_scope) - 4] = '\0';
1538 dir_name = g_path_get_dirname (new_scope);
1539 base_name = g_path_get_basename (new_scope);
1540 if (strstr (base_name, "lib") != base_name) {
1541 char *tmp = g_strdup_printf ("lib%s", base_name);
1544 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1547 } else if (strstr (new_scope, "lib") != new_scope) {
1548 file_name = g_strdup_printf ("lib%s", new_scope);
1553 if (!is_absolute && mono_dl_get_system_dir ()) {
1554 dir_name = (char*)mono_dl_get_system_dir ();
1555 file_name = g_path_get_basename (new_scope);
1561 #ifndef TARGET_WIN32
1562 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1563 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1564 !g_ascii_strcasecmp ("user32", new_scope) ||
1565 !g_ascii_strcasecmp ("kernel", new_scope)) {
1566 file_name = g_strdup ("libMonoSupportW.so");
1570 #ifndef TARGET_WIN32
1577 dir_name = g_path_get_dirname (file_name);
1579 base_name = g_path_get_basename (file_name);
1582 if (!module && is_absolute) {
1583 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1585 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1586 "DllImport error loading library '%s': '%s'.",
1587 file_name, error_msg);
1590 found_name = g_strdup (file_name);
1594 if (!module && !is_absolute) {
1598 for (j = 0; j < 3; ++j) {
1603 mdirname = g_path_get_dirname (image->name);
1605 case 1: /* @executable_path@/../lib */
1609 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1611 char *base, *newbase;
1614 resolvedname = mono_path_resolve_symlinks (buf);
1616 base = g_path_get_dirname (resolvedname);
1617 newbase = g_path_get_dirname(base);
1618 mdirname = g_strdup_printf ("%s/lib", newbase);
1620 g_free (resolvedname);
1627 case 2: /* @executable_path@/../Libraries */
1631 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1633 char *base, *newbase;
1636 resolvedname = mono_path_resolve_symlinks (buf);
1638 base = g_path_get_dirname (resolvedname);
1639 newbase = g_path_get_dirname(base);
1640 mdirname = g_strdup_printf ("%s/Libraries", newbase);
1642 g_free (resolvedname);
1654 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1655 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1657 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1658 "DllImport error loading library '%s': '%s'.",
1659 full_name, error_msg);
1662 found_name = g_strdup (full_name);
1678 char *file_or_base = is_absolute ? base_name : file_name;
1679 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1680 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1682 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1683 "DllImport error loading library '%s': '%s'.",
1684 full_name, error_msg);
1687 found_name = g_strdup (full_name);
1696 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1698 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1699 "DllImport error loading library '%s': '%s'.",
1700 file_name, error_msg);
1702 found_name = g_strdup (file_name);
1717 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1718 "DllImport unable to load library '%s'.",
1723 *exc_class = "DllNotFoundException";
1724 *exc_arg = new_scope;
1730 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1731 "DllImport loaded library '%s'.", found_name);
1732 mono_image_lock (image);
1733 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1734 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1735 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1737 mono_image_unlock (image);
1740 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1741 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1742 g_free (found_name);
1745 if (import && import [0] == '#' && isdigit (import [1])) {
1749 id = strtol (import + 1, &end, 10);
1750 if (id > 0 && *end == '\0')
1754 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1755 "Searching for '%s'.", import);
1757 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1758 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1760 char *mangled_name = NULL, *mangled_name2 = NULL;
1763 int mangle_param_count;
1769 * Search using a variety of mangled names
1771 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1772 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1773 gboolean need_param_count = FALSE;
1775 if (mangle_stdcall > 0)
1776 need_param_count = TRUE;
1778 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1783 mangled_name = (char*)import;
1784 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1785 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1786 /* Try the mangled name first */
1787 if (mangle_charset == 0)
1788 mangled_name = g_strconcat (import, "W", NULL);
1790 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1792 if (mangle_charset == 0)
1793 mangled_name = g_strconcat (import, "W", NULL);
1795 /* Try the mangled name last */
1796 if (mangle_charset == 1)
1797 mangled_name = g_strconcat (import, "A", NULL);
1800 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1802 /* Try the mangled name last */
1803 if (mangle_charset == 1)
1804 mangled_name = g_strconcat (import, "A", NULL);
1809 if (mangle_param_count == 0)
1810 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1812 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1813 param_count = mangle_param_count;
1815 /* Try the stdcall mangled name */
1817 * gcc under windows creates mangled names without the underscore, but MS.NET
1818 * doesn't support it, so we doesn't support it either.
1820 if (mangle_stdcall == 1)
1821 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1823 mangled_name2 = mangled_name;
1825 mangled_name2 = mangled_name;
1828 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1829 "Probing '%s'.", mangled_name2);
1831 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1834 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1835 "Found as '%s'.", mangled_name2);
1837 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1838 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1843 if (mangled_name != mangled_name2)
1844 g_free (mangled_name2);
1845 if (mangled_name != import)
1846 g_free (mangled_name);
1852 if (!piinfo->addr) {
1855 *exc_class = "EntryPointNotFoundException";
1860 return piinfo->addr;
1864 * LOCKING: assumes the loader lock to be taken.
1867 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1868 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1871 int table = mono_metadata_token_table (token);
1872 int idx = mono_metadata_token_index (token);
1873 MonoTableInfo *tables = image->tables;
1874 MonoGenericContainer *generic_container = NULL, *container = NULL;
1875 const char *sig = NULL;
1876 guint32 cols [MONO_TYPEDEF_SIZE];
1878 mono_error_init (error);
1880 if (image_is_dynamic (image)) {
1881 MonoClass *handle_class;
1883 result = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, error);
1884 mono_error_assert_ok (error);
1885 mono_loader_assert_no_error ();
1887 // This checks the memberref type as well
1888 if (result && handle_class != mono_defaults.methodhandle_class) {
1889 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1895 if (table != MONO_TABLE_METHOD) {
1896 if (table == MONO_TABLE_METHODSPEC) {
1897 if (used_context) *used_context = TRUE;
1898 return method_from_methodspec (image, context, idx, error);
1900 if (table != MONO_TABLE_MEMBERREF) {
1901 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1904 return method_from_memberref (image, idx, context, used_context, error);
1907 if (used_context) *used_context = FALSE;
1909 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1910 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1915 guint32 type = mono_metadata_typedef_from_method (image, token);
1917 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1920 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1925 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1927 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1928 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1929 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1931 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1932 methods_size += sizeof (MonoMethod);
1935 mono_stats.method_count ++;
1938 result->klass = klass;
1939 result->flags = cols [2];
1940 result->iflags = cols [1];
1941 result->token = token;
1942 result->name = mono_metadata_string_heap (image, cols [3]);
1944 if (!sig) /* already taken from the methodref */
1945 sig = mono_metadata_blob_heap (image, cols [4]);
1946 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1948 container = klass->generic_container;
1951 * load_generic_params does a binary search so only call it if the method
1955 generic_container = mono_metadata_load_generic_params (image, token, container);
1956 mono_loader_assert_no_error (); /* FIXME don't swallow this error. */
1958 if (generic_container) {
1959 result->is_generic = TRUE;
1960 generic_container->owner.method = result;
1961 generic_container->is_anonymous = FALSE; // Method is now known, container is no longer anonymous
1962 /*FIXME put this before the image alloc*/
1963 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1966 container = generic_container;
1969 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1970 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1971 result->string_ctor = 1;
1972 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1973 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1976 /* IJW is P/Invoke with a predefined function pointer. */
1977 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1978 piinfo->addr = mono_image_rva_map (image, cols [0]);
1979 g_assert (piinfo->addr);
1982 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1983 /* Native methods can have no map. */
1984 if (piinfo->implmap_idx)
1985 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1988 if (generic_container)
1989 mono_method_set_generic_container (result, generic_container);
1991 mono_loader_assert_no_error ();
1996 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1999 MonoMethod *result = mono_get_method_checked (image, token, klass, NULL, &error);
2000 mono_error_cleanup (&error);
2005 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
2006 MonoGenericContext *context)
2009 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
2010 mono_error_cleanup (&error);
2015 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
2017 MonoMethod *result = NULL;
2018 gboolean used_context = FALSE;
2020 /* We do everything inside the lock to prevent creation races */
2022 mono_error_init (error);
2024 mono_image_lock (image);
2026 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
2027 if (!image->method_cache)
2028 image->method_cache = g_hash_table_new (NULL, NULL);
2029 result = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2030 } else if (!image_is_dynamic (image)) {
2031 if (!image->methodref_cache)
2032 image->methodref_cache = g_hash_table_new (NULL, NULL);
2033 result = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2035 mono_image_unlock (image);
2041 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
2045 mono_image_lock (image);
2046 if (!used_context && !result->is_inflated) {
2047 MonoMethod *result2 = NULL;
2049 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2050 result2 = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2051 else if (!image_is_dynamic (image))
2052 result2 = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2055 mono_image_unlock (image);
2059 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2060 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
2061 else if (!image_is_dynamic (image))
2062 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
2065 mono_image_unlock (image);
2071 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
2074 MonoClass *ic = NULL;
2075 MonoGenericContext *method_context = NULL;
2076 MonoMethodSignature *sig, *original_sig;
2078 mono_error_init (error);
2080 mono_class_init (constrained_class);
2081 original_sig = sig = mono_method_signature_checked (method, error);
2086 if (method->is_inflated && sig->generic_param_count) {
2087 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2088 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
2091 method_context = mono_method_get_context (method);
2095 * We must inflate the signature with the class instantiation to work on
2096 * cases where a class inherit from a generic type and the override replaces
2097 * any type argument which a concrete type. See #325283.
2099 if (method_context->class_inst) {
2100 MonoGenericContext ctx;
2101 ctx.method_inst = NULL;
2102 ctx.class_inst = method_context->class_inst;
2103 /*Fixme, property propagate this error*/
2104 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2110 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2113 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2114 if (sig != original_sig)
2115 mono_metadata_free_inflated_signature (sig);
2120 if (method_context) {
2121 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2130 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2131 MonoGenericContext *context, MonoError *error)
2135 return get_method_constrained (image, method, constrained_class, context, error);
2139 * mono_get_method_constrained:
2141 * This is used when JITing the `constrained.' opcode.
2143 * This returns two values: the contrained method, which has been inflated
2144 * as the function return value; And the original CIL-stream method as
2145 * declared in cil_method. The later is used for verification.
2148 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2149 MonoGenericContext *context, MonoMethod **cil_method)
2152 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2153 mono_error_cleanup (&error);
2158 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2160 mono_error_init (error);
2162 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2166 return get_method_constrained (image, *cil_method, constrained_class, context, error);
2170 mono_free_method (MonoMethod *method)
2172 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2173 mono_profiler_method_free (method);
2175 /* FIXME: This hack will go away when the profiler will support freeing methods */
2176 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2179 if (method->signature) {
2181 * FIXME: This causes crashes because the types inside signatures and
2182 * locals are shared.
2184 /* mono_metadata_free_method_signature (method->signature); */
2185 /* g_free (method->signature); */
2188 if (method_is_dynamic (method)) {
2189 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2192 mono_marshal_free_dynamic_wrappers (method);
2194 mono_image_property_remove (method->klass->image, method);
2196 g_free ((char*)method->name);
2198 g_free ((char*)mw->header->code);
2199 for (i = 0; i < mw->header->num_locals; ++i)
2200 g_free (mw->header->locals [i]);
2201 g_free (mw->header->clauses);
2202 g_free (mw->header);
2204 g_free (mw->method_data);
2205 g_free (method->signature);
2211 mono_method_get_param_names (MonoMethod *method, const char **names)
2215 MonoTableInfo *methodt;
2216 MonoTableInfo *paramt;
2217 MonoMethodSignature *signature;
2220 if (method->is_inflated)
2221 method = ((MonoMethodInflated *) method)->declaring;
2223 signature = mono_method_signature (method);
2224 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2225 number of arguments and allocate a properly sized array. */
2226 if (signature == NULL)
2229 if (!signature->param_count)
2232 for (i = 0; i < signature->param_count; ++i)
2235 klass = method->klass;
2239 mono_class_init (klass);
2241 if (image_is_dynamic (klass->image)) {
2242 MonoReflectionMethodAux *method_aux =
2243 (MonoReflectionMethodAux *)g_hash_table_lookup (
2244 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2245 if (method_aux && method_aux->param_names) {
2246 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2247 if (method_aux->param_names [i + 1])
2248 names [i] = method_aux->param_names [i + 1];
2253 if (method->wrapper_type) {
2254 char **pnames = NULL;
2256 mono_image_lock (klass->image);
2257 if (klass->image->wrapper_param_names)
2258 pnames = (char **)g_hash_table_lookup (klass->image->wrapper_param_names, method);
2259 mono_image_unlock (klass->image);
2262 for (i = 0; i < signature->param_count; ++i)
2263 names [i] = pnames [i];
2268 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2269 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2270 idx = mono_method_get_index (method);
2272 guint32 cols [MONO_PARAM_SIZE];
2275 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2277 if (idx < methodt->rows)
2278 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2280 lastp = paramt->rows + 1;
2281 for (i = param_index; i < lastp; ++i) {
2282 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2283 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2284 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2290 mono_method_get_param_token (MonoMethod *method, int index)
2292 MonoClass *klass = method->klass;
2293 MonoTableInfo *methodt;
2296 mono_class_init (klass);
2298 if (image_is_dynamic (klass->image))
2299 g_assert_not_reached ();
2301 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2302 idx = mono_method_get_index (method);
2304 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2308 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2310 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2317 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2320 MonoClass *klass = method->klass;
2321 MonoTableInfo *methodt;
2322 MonoTableInfo *paramt;
2323 MonoMethodSignature *signature;
2326 signature = mono_method_signature (method);
2327 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2329 for (i = 0; i < signature->param_count + 1; ++i)
2332 if (image_is_dynamic (method->klass->image)) {
2333 MonoReflectionMethodAux *method_aux =
2334 (MonoReflectionMethodAux *)g_hash_table_lookup (
2335 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2336 if (method_aux && method_aux->param_marshall) {
2337 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2338 for (i = 0; i < signature->param_count + 1; ++i)
2339 if (dyn_specs [i]) {
2340 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2341 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2342 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2343 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2349 mono_class_init (klass);
2351 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2352 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2353 idx = mono_method_get_index (method);
2355 guint32 cols [MONO_PARAM_SIZE];
2356 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2358 if (idx < methodt->rows)
2359 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2361 lastp = paramt->rows + 1;
2363 for (i = param_index; i < lastp; ++i) {
2364 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2366 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2368 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2370 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2379 mono_method_has_marshal_info (MonoMethod *method)
2382 MonoClass *klass = method->klass;
2383 MonoTableInfo *methodt;
2384 MonoTableInfo *paramt;
2387 if (image_is_dynamic (method->klass->image)) {
2388 MonoReflectionMethodAux *method_aux =
2389 (MonoReflectionMethodAux *)g_hash_table_lookup (
2390 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2391 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2393 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2400 mono_class_init (klass);
2402 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2403 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2404 idx = mono_method_get_index (method);
2406 guint32 cols [MONO_PARAM_SIZE];
2407 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2409 if (idx + 1 < methodt->rows)
2410 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2412 lastp = paramt->rows + 1;
2414 for (i = param_index; i < lastp; ++i) {
2415 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2417 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2426 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2429 g_assert (method != NULL);
2430 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2432 if (method->is_inflated)
2433 method = ((MonoMethodInflated *) method)->declaring;
2434 data = (void **)((MonoMethodWrapper *)method)->method_data;
2435 g_assert (data != NULL);
2436 g_assert (id <= GPOINTER_TO_UINT (*data));
2443 } StackWalkUserData;
2446 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2448 StackWalkUserData *d = (StackWalkUserData *)data;
2450 switch (frame->type) {
2451 case FRAME_TYPE_DEBUGGER_INVOKE:
2452 case FRAME_TYPE_MANAGED_TO_NATIVE:
2453 case FRAME_TYPE_TRAMPOLINE:
2455 case FRAME_TYPE_MANAGED:
2456 g_assert (frame->ji);
2457 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2460 g_assert_not_reached ();
2466 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2468 StackWalkUserData ud = { func, user_data };
2469 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2473 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2475 StackWalkUserData ud = { func, user_data };
2476 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2480 MonoStackWalkAsyncSafe func;
2482 } AsyncStackWalkUserData;
2486 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2488 AsyncStackWalkUserData *d = (AsyncStackWalkUserData *)data;
2490 switch (frame->type) {
2491 case FRAME_TYPE_DEBUGGER_INVOKE:
2492 case FRAME_TYPE_MANAGED_TO_NATIVE:
2493 case FRAME_TYPE_TRAMPOLINE:
2495 case FRAME_TYPE_MANAGED:
2498 if (frame->ji->async) {
2499 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2501 return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2505 g_assert_not_reached ();
2512 * mono_stack_walk_async_safe:
2514 * Async safe version callable from signal handlers.
2517 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2520 AsyncStackWalkUserData ud = { func, user_data };
2522 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2523 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2527 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2529 MonoMethod **dest = (MonoMethod **)data;
2531 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2537 mono_method_get_last_managed (void)
2539 MonoMethod *m = NULL;
2540 mono_stack_walk_no_il (last_managed, &m);
2544 static gboolean loader_lock_track_ownership = FALSE;
2549 * See docs/thread-safety.txt for the locking strategy.
2552 mono_loader_lock (void)
2554 mono_locks_coop_acquire (&loader_mutex, LoaderLock);
2555 if (G_UNLIKELY (loader_lock_track_ownership)) {
2556 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));
2561 mono_loader_unlock (void)
2563 mono_locks_coop_release (&loader_mutex, LoaderLock);
2564 if (G_UNLIKELY (loader_lock_track_ownership)) {
2565 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));
2570 * mono_loader_lock_track_ownership:
2572 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2573 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2574 * thread owns the loader lock.
2577 mono_loader_lock_track_ownership (gboolean track)
2579 loader_lock_track_ownership = track;
2583 * mono_loader_lock_is_owned_by_self:
2585 * Return whenever the current thread owns the loader lock.
2586 * This is useful to avoid blocking operations while holding the loader lock.
2589 mono_loader_lock_is_owned_by_self (void)
2591 g_assert (loader_lock_track_ownership);
2593 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2597 * mono_loader_lock_if_inited:
2599 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2600 * be used in runtime initialization code which can be executed before mono_loader_init ().
2603 mono_loader_lock_if_inited (void)
2605 if (loader_lock_inited)
2606 mono_loader_lock ();
2610 mono_loader_unlock_if_inited (void)
2612 if (loader_lock_inited)
2613 mono_loader_unlock ();
2617 * mono_method_signature:
2619 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2621 MonoMethodSignature*
2622 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2627 gboolean can_cache_signature;
2628 MonoGenericContainer *container;
2629 MonoMethodSignature *signature = NULL, *sig2;
2632 /* We need memory barriers below because of the double-checked locking pattern */
2634 mono_error_init (error);
2637 return m->signature;
2639 img = m->klass->image;
2641 if (m->is_inflated) {
2642 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2643 /* the lock is recursive */
2644 signature = mono_method_signature (imethod->declaring);
2645 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2646 if (!mono_error_ok (error))
2649 inflated_signatures_size += mono_metadata_signature_size (signature);
2651 mono_image_lock (img);
2653 mono_memory_barrier ();
2655 m->signature = signature;
2657 mono_image_unlock (img);
2659 return m->signature;
2662 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2663 idx = mono_metadata_token_index (m->token);
2665 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2667 g_assert (!m->klass->generic_class);
2668 container = mono_method_get_generic_container (m);
2670 container = m->klass->generic_container;
2672 /* Generic signatures depend on the container so they cannot be cached */
2673 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2674 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2676 /* If the method has parameter attributes, that can modify the signature */
2677 if (mono_metadata_method_has_param_attrs (img, idx))
2678 can_cache_signature = FALSE;
2680 if (can_cache_signature) {
2681 mono_image_lock (img);
2682 signature = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2683 mono_image_unlock (img);
2687 const char *sig_body;
2688 /*TODO we should cache the failure result somewhere*/
2689 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2692 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2694 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2698 if (can_cache_signature) {
2699 mono_image_lock (img);
2700 sig2 = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2702 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2703 mono_image_unlock (img);
2706 signatures_size += mono_metadata_signature_size (signature);
2709 /* Verify metadata consistency */
2710 if (signature->generic_param_count) {
2711 if (!container || !container->is_method) {
2712 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);
2715 if (container->type_argc != signature->generic_param_count) {
2716 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);
2719 } else if (container && container->is_method && container->type_argc) {
2720 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);
2723 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2724 signature->pinvoke = 1;
2725 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2726 MonoCallConvention conv = (MonoCallConvention)0;
2727 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2728 signature->pinvoke = 1;
2730 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2731 case 0: /* no call conv, so using default */
2732 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2733 conv = MONO_CALL_DEFAULT;
2735 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2738 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2739 conv = MONO_CALL_STDCALL;
2741 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2742 conv = MONO_CALL_THISCALL;
2744 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2745 conv = MONO_CALL_FASTCALL;
2747 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2748 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2750 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);
2753 signature->call_convention = conv;
2756 mono_image_lock (img);
2758 mono_memory_barrier ();
2760 m->signature = signature;
2762 mono_image_unlock (img);
2764 return m->signature;
2768 * mono_method_signature:
2770 * Return the signature of the method M. On failure, returns NULL.
2772 MonoMethodSignature*
2773 mono_method_signature (MonoMethod *m)
2776 MonoMethodSignature *sig;
2778 sig = mono_method_signature_checked (m, &error);
2780 char *type_name = mono_type_get_full_name (m->klass);
2781 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2783 mono_error_cleanup (&error);
2790 mono_method_get_name (MonoMethod *method)
2792 return method->name;
2796 mono_method_get_class (MonoMethod *method)
2798 return method->klass;
2802 mono_method_get_token (MonoMethod *method)
2804 return method->token;
2808 mono_method_get_header_checked (MonoMethod *method, MonoError *error)
2814 MonoGenericContainer *container;
2816 mono_error_init (error);
2817 img = method->klass->image;
2819 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)) {
2820 mono_error_set_bad_image (error, img, "Method has no body");
2824 if (method->is_inflated) {
2825 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2826 MonoMethodHeader *header, *iheader;
2828 header = mono_method_get_header_checked (imethod->declaring, error);
2832 iheader = inflate_generic_header (header, mono_method_get_context (method), error);
2833 mono_metadata_free_mh (header);
2841 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2842 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2843 g_assert (mw->header);
2848 * We don't need locks here: the new header is allocated from malloc memory
2849 * and is not stored anywhere in the runtime, the user needs to free it.
2851 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2852 idx = mono_metadata_token_index (method->token);
2853 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2855 if (!mono_verifier_verify_method_header (img, rva, NULL)) {
2856 mono_error_set_bad_image (error, img, "Invalid method header, failed verification");
2860 loc = mono_image_rva_map (img, rva);
2862 mono_error_set_bad_image (error, img, "Method has zero rva");
2867 * When parsing the types of local variables, we must pass any container available
2868 * to ensure that both VAR and MVAR will get the right owner.
2870 container = mono_method_get_generic_container (method);
2872 container = method->klass->generic_container;
2873 return mono_metadata_parse_mh_full (img, container, (const char *)loc, error);
2877 mono_method_get_header (MonoMethod *method)
2880 MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
2881 mono_error_cleanup (&error);
2887 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2890 *iflags = method->iflags;
2891 return method->flags;
2895 * Find the method index in the metadata methodDef table.
2898 mono_method_get_index (MonoMethod *method)
2900 MonoClass *klass = method->klass;
2904 /* constructed array methods are not in the MethodDef table */
2908 return mono_metadata_token_index (method->token);
2910 mono_class_setup_methods (klass);
2911 if (mono_class_has_failure (klass))
2913 for (i = 0; i < klass->method.count; ++i) {
2914 if (method == klass->methods [i]) {
2915 if (klass->image->uncompressed_metadata)
2916 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2918 return klass->method.first + i + 1;