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-internals.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>
48 #include <mono/utils/mono-path.h>
50 MonoDefaults mono_defaults;
53 * This lock protects the hash tables inside MonoImage used by the metadata
54 * loading functions in class.c and loader.c.
56 * See domain-internals.h for locking policy in combination with the
59 static MonoCoopMutex loader_mutex;
60 static mono_mutex_t global_loader_data_mutex;
61 static gboolean loader_lock_inited;
64 static guint32 inflated_signatures_size;
65 static guint32 memberref_sig_cache_size;
66 static guint32 methods_size;
67 static guint32 signatures_size;
70 * This TLS variable contains the last type load error encountered by the loader.
72 MonoNativeTlsKey loader_error_thread_id;
75 * This TLS variable holds how many times the current thread has acquired the loader
78 MonoNativeTlsKey loader_lock_nest_id;
80 static void dllmap_cleanup (void);
84 global_loader_data_lock (void)
86 mono_locks_os_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
90 global_loader_data_unlock (void)
92 mono_locks_os_release (&global_loader_data_mutex, LoaderGlobalDataLock);
98 static gboolean inited;
101 mono_coop_mutex_init_recursive (&loader_mutex);
102 mono_os_mutex_init_recursive (&global_loader_data_mutex);
103 loader_lock_inited = TRUE;
105 mono_native_tls_alloc (&loader_error_thread_id, NULL);
106 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
108 mono_counters_init ();
109 mono_counters_register ("Inflated signatures size",
110 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
111 mono_counters_register ("Memberref signature cache size",
112 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
113 mono_counters_register ("MonoMethod size",
114 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
115 mono_counters_register ("MonoMethodSignature size",
116 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
123 mono_loader_cleanup (void)
127 mono_native_tls_free (loader_error_thread_id);
128 mono_native_tls_free (loader_lock_nest_id);
130 mono_coop_mutex_destroy (&loader_mutex);
131 mono_os_mutex_destroy (&global_loader_data_mutex);
132 loader_lock_inited = FALSE;
136 * Handling of type load errors should be done as follows:
138 * If something could not be loaded, the loader should call one of the
139 * mono_loader_set_error_XXX functions ()
140 * with the appropriate arguments, then return NULL to report the failure. The error
141 * should be propagated until it reaches code which can throw managed exceptions. At that
142 * point, an exception should be thrown based on the information returned by
143 * mono_loader_get_last_error (). Then the error should be cleared by calling
144 * mono_loader_clear_error ().
148 set_loader_error (MonoLoaderError *error)
150 mono_loader_clear_error ();
151 mono_native_tls_set_value (loader_error_thread_id, error);
155 * mono_loader_set_error_assembly_load:
157 * Set the loader error for this thread.
160 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
162 MonoLoaderError *error;
164 if (mono_loader_get_last_error ())
167 error = g_new0 (MonoLoaderError, 1);
168 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
169 error->assembly_name = g_strdup (assembly_name);
170 error->ref_only = ref_only;
173 * This is not strictly needed, but some (most) of the loader code still
174 * can't deal with load errors, and this message is more helpful than an
178 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);
180 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
182 set_loader_error (error);
186 * mono_loader_set_error_type_load:
188 * Set the loader error for this thread.
191 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
193 MonoLoaderError *error;
195 if (mono_loader_get_last_error ())
198 error = g_new0 (MonoLoaderError, 1);
199 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
200 error->class_name = g_strdup (class_name);
201 error->assembly_name = g_strdup (assembly_name);
204 * This is not strictly needed, but some (most) of the loader code still
205 * can't deal with load errors, and this message is more helpful than an
208 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
210 set_loader_error (error);
214 * mono_loader_set_error_method_load:
216 * Set the loader error for this thread. MEMBER_NAME should point to a string
220 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
222 MonoLoaderError *error;
224 /* FIXME: Store the signature as well */
225 if (mono_loader_get_last_error ())
228 error = g_new0 (MonoLoaderError, 1);
229 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
230 error->class_name = g_strdup (class_name);
231 error->member_name = member_name;
233 set_loader_error (error);
237 * mono_loader_set_error_field_load:
239 * Set the loader error for this thread. MEMBER_NAME should point to a string
243 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
245 MonoLoaderError *error;
247 /* FIXME: Store the signature as well */
248 if (mono_loader_get_last_error ())
251 error = g_new0 (MonoLoaderError, 1);
252 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
253 error->klass = klass;
254 error->member_name = member_name;
256 set_loader_error (error);
260 * mono_loader_set_error_bad_image:
262 * Set the loader error for this thread.
265 mono_loader_set_error_bad_image (char *msg)
267 MonoLoaderError *error;
269 if (mono_loader_get_last_error ())
272 error = g_new0 (MonoLoaderError, 1);
273 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
276 set_loader_error (error);
281 * mono_loader_get_last_error:
283 * Returns information about the last type load exception encountered by the loader, or
284 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
287 mono_loader_get_last_error (void)
289 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
293 mono_loader_assert_no_error (void)
295 MonoLoaderError *error = mono_loader_get_last_error ();
298 g_print ("Unhandled loader error: %x, %s %s %s\n", error->exception_type, error->msg, error->assembly_name, error->class_name);
299 g_assert_not_reached ();
304 * mono_loader_clear_error:
306 * Disposes any loader error messages on this thread
309 mono_loader_clear_error (void)
311 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
314 g_free (ex->class_name);
315 g_free (ex->assembly_name);
319 mono_native_tls_set_value (loader_error_thread_id, NULL);
324 * mono_loader_error_prepare_exception:
325 * @error: The MonoLoaderError to turn into an exception
327 * This turns a MonoLoaderError into an exception that can be thrown
328 * and resets the Mono Loader Error state during this process.
332 mono_loader_error_prepare_exception (MonoLoaderError *error)
334 MonoException *ex = NULL;
336 switch (error->exception_type) {
337 case MONO_EXCEPTION_TYPE_LOAD: {
338 char *cname = g_strdup (error->class_name);
339 char *aname = g_strdup (error->assembly_name);
340 MonoString *class_name;
342 mono_loader_clear_error ();
344 class_name = mono_string_new (mono_domain_get (), cname);
346 ex = mono_get_exception_type_load (class_name, aname);
351 case MONO_EXCEPTION_MISSING_METHOD: {
352 char *cname = g_strdup (error->class_name);
353 char *aname = g_strdup (error->member_name);
355 mono_loader_clear_error ();
356 ex = mono_get_exception_missing_method (cname, aname);
362 case MONO_EXCEPTION_MISSING_FIELD: {
364 char *cmembername = g_strdup (error->member_name);
366 class_name = mono_type_get_full_name (error->klass);
368 class_name = g_strdup ("");
370 mono_loader_clear_error ();
372 ex = mono_get_exception_missing_field (class_name, cmembername);
374 g_free (cmembername);
378 case MONO_EXCEPTION_FILE_NOT_FOUND: {
383 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);
385 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
386 filename = g_strdup (error->assembly_name);
387 /* Has to call this before calling anything which might call mono_class_init () */
388 mono_loader_clear_error ();
389 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
395 case MONO_EXCEPTION_BAD_IMAGE: {
396 char *msg = g_strdup (error->msg);
397 mono_loader_clear_error ();
398 ex = mono_get_exception_bad_image_format (msg);
404 g_assert_not_reached ();
411 * find_cached_memberref_sig:
413 * Return a cached copy of the memberref signature identified by SIG_IDX.
414 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
415 * A cache is needed since the type/signature parsing routines allocate everything
416 * from a mempool, so without a cache, multiple requests for the same signature would
417 * lead to unbounded memory growth. For normal methods/fields this is not a problem
418 * since the resulting methods/fields are cached, but inflated methods/fields cannot
420 * LOCKING: Acquires the loader lock.
423 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
427 mono_image_lock (image);
428 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
429 mono_image_unlock (image);
435 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
439 mono_image_lock (image);
440 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
442 /* Somebody got in before us */
446 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
447 /* An approximation based on glib 2.18 */
448 memberref_sig_cache_size += sizeof (gpointer) * 4;
450 mono_image_unlock (image);
455 static MonoClassField*
456 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
457 MonoGenericContext *context, MonoError *error)
459 MonoClass *klass = NULL;
460 MonoClassField *field;
461 MonoTableInfo *tables = image->tables;
464 guint32 nindex, class_index;
467 guint32 idx = mono_metadata_token_index (token);
469 mono_error_init (error);
471 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
472 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
473 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
475 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
477 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
478 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class_index, token);
482 switch (class_index) {
483 case MONO_MEMBERREF_PARENT_TYPEDEF:
484 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
486 case MONO_MEMBERREF_PARENT_TYPEREF:
487 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
489 case MONO_MEMBERREF_PARENT_TYPESPEC:
490 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
493 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class_index, token);
499 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
500 mono_metadata_decode_blob_size (ptr, &ptr);
501 /* we may want to check the signature here... */
504 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class_index, fname, token);
508 /* FIXME: This needs a cache, especially for generic instances, since
509 * we ask mono_metadata_parse_type_checked () to allocates everything from a mempool.
510 * FIXME part2, mono_metadata_parse_type_checked actually allows for a transient type instead.
511 * FIXME part3, transient types are not 100% transient, so we need to take care of that first.
513 sig_type = (MonoType *)find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
515 MonoError inner_error;
516 sig_type = mono_metadata_parse_type_checked (image, NULL, 0, FALSE, ptr, &ptr, &inner_error);
517 if (sig_type == NULL) {
518 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));
519 mono_error_cleanup (&inner_error);
522 sig_type = (MonoType *)cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
525 mono_class_init (klass); /*FIXME is this really necessary?*/
528 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
531 mono_loader_assert_no_error ();
532 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
539 * mono_field_from_token:
540 * @deprecated use the _checked variant
541 * Notes: runtime code MUST not use this function
544 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
547 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
548 g_assert (mono_error_ok (&error));
553 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
557 MonoClassField *field;
559 mono_error_init (error);
561 if (image_is_dynamic (image)) {
562 MonoClassField *result;
563 MonoClass *handle_class;
566 MonoError inner_error;
567 result = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, &inner_error);
568 mono_error_cleanup (&inner_error);
569 // This checks the memberref type as well
570 if (!result || handle_class != mono_defaults.fieldhandle_class) {
571 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
574 *retklass = result->parent;
578 if ((field = (MonoClassField *)mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
579 *retklass = field->parent;
583 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
584 field = field_from_memberref (image, token, retklass, context, error);
585 mono_loader_assert_no_error ();
587 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
589 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
592 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
599 field = mono_class_get_field (k, token);
601 if (mono_loader_get_last_error ())
602 mono_error_set_from_loader_error (error);
604 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
608 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container) {
609 mono_image_lock (image);
610 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
611 mono_image_unlock (image);
614 mono_loader_assert_no_error ();
619 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
623 if (sig1->hasthis != sig2->hasthis ||
624 sig1->sentinelpos != sig2->sentinelpos)
627 for (i = 0; i < sig1->sentinelpos; i++) {
628 MonoType *p1 = sig1->params[i];
629 MonoType *p2 = sig2->params[i];
631 /*if (p1->attrs != p2->attrs)
634 if (!mono_metadata_type_equal (p1, p2))
638 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
644 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
645 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
649 /* Search directly in the metadata to avoid calling setup_methods () */
650 mono_error_init (error);
652 /* FIXME: !from_class->generic_class condition causes test failures. */
653 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
654 for (i = 0; i < klass->method.count; ++i) {
655 guint32 cols [MONO_METHOD_SIZE];
658 MonoMethodSignature *other_sig;
660 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
662 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
664 if (!((fqname && !strcmp (m_name, fqname)) ||
665 (qname && !strcmp (m_name, qname)) ||
666 (name && !strcmp (m_name, name))))
669 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
670 if (!mono_error_ok (error)) //bail out if we hit a loader error
673 other_sig = mono_method_signature_checked (method, error);
674 if (!mono_error_ok (error)) //bail out if we hit a loader error
676 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
682 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
684 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
685 See mono/tests/generic-type-load-exception.2.il
686 FIXME we should better report this error to the caller
688 if (!klass->methods || mono_class_has_failure (klass)) {
689 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
693 for (i = 0; i < klass->method.count; ++i) {
694 MonoMethod *m = klass->methods [i];
695 MonoMethodSignature *msig;
697 /* We must cope with failing to load some of the types. */
701 if (!((fqname && !strcmp (m->name, fqname)) ||
702 (qname && !strcmp (m->name, qname)) ||
703 (name && !strcmp (m->name, name))))
705 msig = mono_method_signature_checked (m, error);
706 if (!mono_error_ok (error)) //bail out if we hit a loader error
712 if (sig->call_convention == MONO_CALL_VARARG) {
713 if (mono_metadata_signature_vararg_match (sig, msig))
716 if (mono_metadata_signature_equal (sig, msig))
721 if (i < klass->method.count)
722 return mono_class_get_method_by_index (from_class, i);
727 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
730 char *qname, *fqname, *class_name;
731 gboolean is_interface;
732 MonoMethod *result = NULL;
733 MonoClass *initial_class = in_class;
735 mono_error_init (error);
736 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
739 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
741 qname = g_strconcat (class_name, ".", name, NULL);
742 if (ic->name_space && ic->name_space [0])
743 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
747 class_name = qname = fqname = NULL;
750 g_assert (from_class);
751 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
752 if (result || !mono_error_ok (error))
755 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
759 * This happens when we fail to lazily load the interfaces of one of the types.
760 * On such case we can't just bail out since user code depends on us trying harder.
762 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
763 in_class = in_class->parent;
764 from_class = from_class->parent;
768 for (i = 0; i < in_class->interface_offsets_count; i++) {
769 MonoClass *in_ic = in_class->interfaces_packed [i];
770 MonoClass *from_ic = from_class->interfaces_packed [i];
771 char *ic_qname, *ic_fqname, *ic_class_name;
773 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
774 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
775 if (in_ic->name_space && in_ic->name_space [0])
776 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
780 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
781 g_free (ic_class_name);
784 if (result || !mono_error_ok (error))
788 in_class = in_class->parent;
789 from_class = from_class->parent;
791 g_assert (!in_class == !from_class);
794 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
796 //we did not find the method
797 if (!result && mono_error_ok (error)) {
798 char *desc = mono_signature_get_desc (sig, FALSE);
799 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
810 static MonoMethodSignature*
811 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
813 MonoMethodSignature *res;
817 mono_error_init (error);
821 res = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
822 res->param_count = sig->param_count;
823 res->sentinelpos = -1;
824 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
825 if (!mono_error_ok (error))
827 is_open = mono_class_is_open_constructed_type (res->ret);
828 for (i = 0; i < sig->param_count; ++i) {
829 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
830 if (!mono_error_ok (error))
834 is_open = mono_class_is_open_constructed_type (res->params [i]);
836 res->hasthis = sig->hasthis;
837 res->explicit_this = sig->explicit_this;
838 res->call_convention = sig->call_convention;
839 res->pinvoke = sig->pinvoke;
840 res->generic_param_count = sig->generic_param_count;
841 res->sentinelpos = sig->sentinelpos;
842 res->has_type_parameters = is_open;
843 res->is_inflated = 1;
848 mono_metadata_free_type (res->ret);
849 for (i = 0; i < sig->param_count; ++i) {
851 mono_metadata_free_type (res->params [i]);
858 * mono_inflate_generic_signature:
860 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
863 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
865 MonoMethodSignature *res, *cached;
867 res = inflate_generic_signature_checked (NULL, sig, context, error);
868 if (!mono_error_ok (error))
870 cached = mono_metadata_get_inflated_signature (res, context);
872 mono_metadata_free_inflated_signature (res);
876 static MonoMethodHeader*
877 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context, MonoError *error)
879 size_t locals_size = sizeof (gpointer) * header->num_locals;
880 size_t clauses_size = header->num_clauses * sizeof (MonoExceptionClause);
881 size_t header_size = MONO_SIZEOF_METHOD_HEADER + locals_size + clauses_size;
882 MonoMethodHeader *res = (MonoMethodHeader *)g_malloc0 (header_size);
883 res->num_locals = header->num_locals;
884 res->clauses = (MonoExceptionClause *) &res->locals [res->num_locals] ;
885 memcpy (res->clauses, header->clauses, clauses_size);
887 res->code = header->code;
888 res->code_size = header->code_size;
889 res->max_stack = header->max_stack;
890 res->num_clauses = header->num_clauses;
891 res->init_locals = header->init_locals;
893 res->is_transient = TRUE;
895 mono_error_init (error);
897 for (int i = 0; i < header->num_locals; ++i) {
898 res->locals [i] = mono_class_inflate_generic_type_checked (header->locals [i], context, error);
902 if (res->num_clauses) {
903 for (int i = 0; i < header->num_clauses; ++i) {
904 MonoExceptionClause *clause = &res->clauses [i];
905 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
907 clause->data.catch_class = mono_class_inflate_generic_class_checked (clause->data.catch_class, context, error);
919 * token is the method_ref/def/spec token used in a call IL instruction.
920 * @deprecated use the _checked variant
921 * Notes: runtime code MUST not use this function
924 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
927 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
928 mono_error_cleanup (&error);
933 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
935 int table = mono_metadata_token_table (token);
936 int idx = mono_metadata_token_index (token);
938 guint32 cols [MONO_MEMBERREF_SIZE];
939 MonoMethodSignature *sig;
942 mono_error_init (error);
944 /* !table is for wrappers: we should really assign their own token to them */
945 if (!table || table == MONO_TABLE_METHOD)
946 return mono_method_signature_checked (method, error);
948 if (table == MONO_TABLE_METHODSPEC) {
949 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
950 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated) {
951 mono_error_set_bad_image (error, image, "Method is a pinvoke or open generic");
955 return mono_method_signature_checked (method, error);
958 if (method->klass->generic_class)
959 return mono_method_signature_checked (method, error);
961 if (image_is_dynamic (image)) {
962 sig = mono_reflection_lookup_signature (image, method, token, error);
966 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
967 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
969 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
971 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
972 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
973 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
975 //FIXME include the verification error
976 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
980 ptr = mono_metadata_blob_heap (image, sig_idx);
981 mono_metadata_decode_blob_size (ptr, &ptr);
983 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
987 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
989 /* FIXME: we probably should verify signature compat in the dynamic case too*/
990 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
991 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
992 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
994 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
1000 MonoMethodSignature *cached;
1002 /* This signature is not owned by a MonoMethod, so need to cache */
1003 sig = inflate_generic_signature_checked (image, sig, context, error);
1004 if (!mono_error_ok (error))
1007 cached = mono_metadata_get_inflated_signature (sig, context);
1009 mono_metadata_free_inflated_signature (sig);
1011 inflated_signatures_size += mono_metadata_signature_size (cached);
1015 g_assert (mono_error_ok (error));
1020 * token is the method_ref/def/spec token used in a call IL instruction.
1021 * @deprecated use the _checked variant
1022 * Notes: runtime code MUST not use this function
1024 MonoMethodSignature*
1025 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
1028 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
1029 mono_error_cleanup (&error);
1033 /* this is only for the typespec array methods */
1035 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1039 mono_class_setup_methods (klass);
1040 g_assert (!mono_class_has_failure (klass)); /*FIXME this should not fail, right?*/
1041 for (i = 0; i < klass->method.count; ++i) {
1042 MonoMethod *method = klass->methods [i];
1043 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1050 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1051 gboolean *used_context, MonoError *error)
1053 MonoClass *klass = NULL;
1054 MonoMethod *method = NULL;
1055 MonoTableInfo *tables = image->tables;
1057 guint32 nindex, class_index, sig_idx;
1059 MonoMethodSignature *sig;
1062 mono_error_init (error);
1064 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1065 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1066 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1067 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1068 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1070 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1073 * Whether we actually used the `typespec_context' or not.
1074 * This is used to tell our caller whether or not it's safe to insert the returned
1075 * method into a cache.
1078 *used_context = class_index == MONO_MEMBERREF_PARENT_TYPESPEC;
1080 switch (class_index) {
1081 case MONO_MEMBERREF_PARENT_TYPEREF:
1082 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1086 case MONO_MEMBERREF_PARENT_TYPESPEC:
1088 * Parse the TYPESPEC in the parent's context.
1090 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1094 case MONO_MEMBERREF_PARENT_TYPEDEF:
1095 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1099 case MONO_MEMBERREF_PARENT_METHODDEF: {
1100 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1106 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class_index, nindex);
1111 mono_class_init (klass);
1113 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1115 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1116 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1120 ptr = mono_metadata_blob_heap (image, sig_idx);
1121 mono_metadata_decode_blob_size (ptr, &ptr);
1123 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
1125 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1129 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
1132 switch (class_index) {
1133 case MONO_MEMBERREF_PARENT_TYPEREF:
1134 case MONO_MEMBERREF_PARENT_TYPEDEF:
1135 method = find_method (klass, NULL, mname, sig, klass, error);
1138 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1141 type = &klass->byval_arg;
1143 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1144 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1145 method = find_method (in_class, NULL, mname, sig, klass, error);
1149 /* we're an array and we created these methods already in klass in mono_class_init () */
1150 method = mono_method_search_in_array_class (klass, mname, sig);
1154 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class_index, nindex);
1158 if (!method && mono_error_ok (error)) {
1159 char *msig = mono_signature_get_desc (sig, FALSE);
1160 GString *s = g_string_new (mname);
1161 if (sig->generic_param_count)
1162 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1163 g_string_append_printf (s, "(%s)", msig);
1165 msig = g_string_free (s, FALSE);
1167 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1168 mono_error_set_from_loader_error (error);
1170 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1175 mono_loader_assert_no_error ();
1179 mono_loader_assert_no_error ();
1180 g_assert (!mono_error_ok (error));
1185 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1189 MonoTableInfo *tables = image->tables;
1190 MonoGenericContext new_context;
1191 MonoGenericInst *inst;
1193 guint32 cols [MONO_METHODSPEC_SIZE];
1194 guint32 token, nindex, param_count;
1196 mono_error_init (error);
1198 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1199 token = cols [MONO_METHODSPEC_METHOD];
1200 nindex = token >> MONO_METHODDEFORREF_BITS;
1202 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1203 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1207 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1209 mono_metadata_decode_value (ptr, &ptr);
1211 param_count = mono_metadata_decode_value (ptr, &ptr);
1213 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr, error);
1217 if (context && inst->is_open) {
1218 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1219 if (!mono_error_ok (error))
1223 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1224 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1228 method = method_from_memberref (image, nindex, context, NULL, error);
1234 klass = method->klass;
1236 if (klass->generic_class) {
1237 g_assert (method->is_inflated);
1238 method = ((MonoMethodInflated *) method)->declaring;
1241 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1242 new_context.method_inst = inst;
1244 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1245 mono_loader_assert_no_error ();
1249 struct _MonoDllMap {
1257 static MonoDllMap *global_dll_map;
1260 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1268 global_loader_data_lock ();
1271 * we use the first entry we find that matches, since entries from
1272 * the config file are prepended to the list and we document that the
1273 * later entries win.
1275 for (; dll_map; dll_map = dll_map->next) {
1276 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1277 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1279 } else if (strcmp (dll_map->dll, dll)) {
1282 if (!found && dll_map->target) {
1283 *rdll = dll_map->target;
1285 /* we don't quit here, because we could find a full
1286 * entry that matches also function and that has priority.
1289 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1290 *rfunc = dll_map->target_func;
1295 global_loader_data_unlock ();
1300 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1303 if (assembly && assembly->dll_map) {
1304 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1308 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1312 * mono_dllmap_insert:
1313 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1314 * @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
1315 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1316 * @tdll: The name of the library to map the specified @dll if it matches.
1317 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1319 * LOCKING: Acquires the loader lock.
1321 * This function is used to programatically add DllImport remapping in either
1322 * a specific assembly, or as a global remapping. This is done by remapping
1323 * references in a DllImport attribute from the @dll library name into the @tdll
1324 * name. If the @dll name contains the prefix "i:", the comparison of the
1325 * library name is done without case sensitivity.
1327 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1328 * or the name of the function as determined by DllImport. If you pass @func, you
1329 * must also pass @tfunc which is the name of the target function to invoke on a match.
1332 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1334 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1335 * the contents of relocated_demo_path for all assemblies in the Mono process.
1337 * NOTE: This can be called before the runtime is initialized, for example from
1338 * mono_config_parse ().
1341 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1345 mono_loader_init ();
1348 entry = (MonoDllMap *)g_malloc0 (sizeof (MonoDllMap));
1349 entry->dll = dll? g_strdup (dll): NULL;
1350 entry->target = tdll? g_strdup (tdll): NULL;
1351 entry->func = func? g_strdup (func): NULL;
1352 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1354 global_loader_data_lock ();
1355 entry->next = global_dll_map;
1356 global_dll_map = entry;
1357 global_loader_data_unlock ();
1359 entry = (MonoDllMap *)mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1360 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1361 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1362 entry->func = func? mono_image_strdup (assembly, func): NULL;
1363 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1365 mono_image_lock (assembly);
1366 entry->next = assembly->dll_map;
1367 assembly->dll_map = entry;
1368 mono_image_unlock (assembly);
1373 free_dllmap (MonoDllMap *map)
1376 MonoDllMap *next = map->next;
1379 g_free (map->target);
1381 g_free (map->target_func);
1388 dllmap_cleanup (void)
1390 free_dllmap (global_dll_map);
1391 global_dll_map = NULL;
1394 static GHashTable *global_module_map;
1397 cached_module_load (const char *name, int flags, char **err)
1403 global_loader_data_lock ();
1404 if (!global_module_map)
1405 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1406 res = (MonoDl *)g_hash_table_lookup (global_module_map, name);
1408 global_loader_data_unlock ();
1411 res = mono_dl_open (name, flags, err);
1413 g_hash_table_insert (global_module_map, g_strdup (name), res);
1414 global_loader_data_unlock ();
1418 static MonoDl *internal_module;
1421 is_absolute_path (const char *path)
1423 #ifdef PLATFORM_MACOSX
1424 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1425 !strncmp (path, "@rpath/", 7))
1428 return g_path_is_absolute (path);
1432 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1434 MonoImage *image = method->klass->image;
1435 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1436 MonoTableInfo *tables = image->tables;
1437 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1438 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1439 guint32 im_cols [MONO_IMPLMAP_SIZE];
1440 guint32 scope_token;
1441 const char *import = NULL;
1442 const char *orig_scope;
1443 const char *new_scope;
1445 char *full_name, *file_name, *found_name = NULL;
1447 MonoDl *module = NULL;
1448 gboolean cached = FALSE;
1450 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1458 return piinfo->addr;
1460 if (image_is_dynamic (method->klass->image)) {
1461 MonoReflectionMethodAux *method_aux =
1462 (MonoReflectionMethodAux *)g_hash_table_lookup (
1463 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1467 import = method_aux->dllentry;
1468 orig_scope = method_aux->dll;
1471 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1474 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1476 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1479 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1480 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1481 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1482 orig_scope = mono_metadata_string_heap (image, scope_token);
1485 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1488 mono_image_lock (image);
1489 if (!image->pinvoke_scopes) {
1490 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1491 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1493 module = (MonoDl *)g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1494 found_name = (char *)g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1495 mono_image_unlock (image);
1499 found_name = g_strdup (found_name);
1503 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1504 "DllImport attempting to load: '%s'.", new_scope);
1506 /* we allow a special name to dlopen from the running process namespace */
1507 if (strcmp (new_scope, "__Internal") == 0){
1508 if (internal_module == NULL)
1509 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1510 module = internal_module;
1515 * Try loading the module using a variety of names
1517 for (i = 0; i < 5; ++i) {
1518 char *base_name = NULL, *dir_name = NULL;
1519 gboolean is_absolute = is_absolute_path (new_scope);
1523 /* Try the original name */
1524 file_name = g_strdup (new_scope);
1527 /* Try trimming the .dll extension */
1528 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1529 file_name = g_strdup (new_scope);
1530 file_name [strlen (new_scope) - 4] = '\0';
1537 dir_name = g_path_get_dirname (new_scope);
1538 base_name = g_path_get_basename (new_scope);
1539 if (strstr (base_name, "lib") != base_name) {
1540 char *tmp = g_strdup_printf ("lib%s", base_name);
1543 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1546 } else if (strstr (new_scope, "lib") != new_scope) {
1547 file_name = g_strdup_printf ("lib%s", new_scope);
1552 if (!is_absolute && mono_dl_get_system_dir ()) {
1553 dir_name = (char*)mono_dl_get_system_dir ();
1554 file_name = g_path_get_basename (new_scope);
1560 #ifndef TARGET_WIN32
1561 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1562 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1563 !g_ascii_strcasecmp ("user32", new_scope) ||
1564 !g_ascii_strcasecmp ("kernel", new_scope)) {
1565 file_name = g_strdup ("libMonoSupportW.so");
1569 #ifndef TARGET_WIN32
1576 dir_name = g_path_get_dirname (file_name);
1578 base_name = g_path_get_basename (file_name);
1581 if (!module && is_absolute) {
1582 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1584 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1585 "DllImport error loading library '%s': '%s'.",
1586 file_name, error_msg);
1589 found_name = g_strdup (file_name);
1593 if (!module && !is_absolute) {
1597 for (j = 0; j < 3; ++j) {
1602 mdirname = g_path_get_dirname (image->name);
1604 case 1: /* @executable_path@/../lib */
1608 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1610 char *base, *newbase;
1613 resolvedname = mono_path_resolve_symlinks (buf);
1615 base = g_path_get_dirname (resolvedname);
1616 newbase = g_path_get_dirname(base);
1617 mdirname = g_strdup_printf ("%s/lib", newbase);
1619 g_free (resolvedname);
1626 case 2: /* @executable_path@/../Libraries */
1630 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1632 char *base, *newbase;
1635 resolvedname = mono_path_resolve_symlinks (buf);
1637 base = g_path_get_dirname (resolvedname);
1638 newbase = g_path_get_dirname(base);
1639 mdirname = g_strdup_printf ("%s/Libraries", newbase);
1641 g_free (resolvedname);
1653 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1654 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1656 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1657 "DllImport error loading library '%s': '%s'.",
1658 full_name, error_msg);
1661 found_name = g_strdup (full_name);
1677 char *file_or_base = is_absolute ? base_name : file_name;
1678 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1679 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1681 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1682 "DllImport error loading library '%s': '%s'.",
1683 full_name, error_msg);
1686 found_name = g_strdup (full_name);
1695 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1697 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1698 "DllImport error loading library '%s': '%s'.",
1699 file_name, error_msg);
1701 found_name = g_strdup (file_name);
1716 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1717 "DllImport unable to load library '%s'.",
1722 *exc_class = "DllNotFoundException";
1723 *exc_arg = new_scope;
1729 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1730 "DllImport loaded library '%s'.", found_name);
1731 mono_image_lock (image);
1732 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1733 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1734 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1736 mono_image_unlock (image);
1739 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1740 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1741 g_free (found_name);
1744 if (import && import [0] == '#' && isdigit (import [1])) {
1748 id = strtol (import + 1, &end, 10);
1749 if (id > 0 && *end == '\0')
1753 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1754 "Searching for '%s'.", import);
1756 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1757 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1759 char *mangled_name = NULL, *mangled_name2 = NULL;
1762 int mangle_param_count;
1768 * Search using a variety of mangled names
1770 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1771 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1772 gboolean need_param_count = FALSE;
1774 if (mangle_stdcall > 0)
1775 need_param_count = TRUE;
1777 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1782 mangled_name = (char*)import;
1783 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1784 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1785 /* Try the mangled name first */
1786 if (mangle_charset == 0)
1787 mangled_name = g_strconcat (import, "W", NULL);
1789 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1791 if (mangle_charset == 0)
1792 mangled_name = g_strconcat (import, "W", NULL);
1794 /* Try the mangled name last */
1795 if (mangle_charset == 1)
1796 mangled_name = g_strconcat (import, "A", NULL);
1799 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1801 /* Try the mangled name last */
1802 if (mangle_charset == 1)
1803 mangled_name = g_strconcat (import, "A", NULL);
1808 if (mangle_param_count == 0)
1809 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1811 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1812 param_count = mangle_param_count;
1814 /* Try the stdcall mangled name */
1816 * gcc under windows creates mangled names without the underscore, but MS.NET
1817 * doesn't support it, so we doesn't support it either.
1819 if (mangle_stdcall == 1)
1820 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1822 mangled_name2 = mangled_name;
1824 mangled_name2 = mangled_name;
1827 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1828 "Probing '%s'.", mangled_name2);
1830 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1833 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1834 "Found as '%s'.", mangled_name2);
1836 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1837 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1842 if (mangled_name != mangled_name2)
1843 g_free (mangled_name2);
1844 if (mangled_name != import)
1845 g_free (mangled_name);
1851 if (!piinfo->addr) {
1854 *exc_class = "EntryPointNotFoundException";
1859 return piinfo->addr;
1863 * LOCKING: assumes the loader lock to be taken.
1866 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1867 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1870 int table = mono_metadata_token_table (token);
1871 int idx = mono_metadata_token_index (token);
1872 MonoTableInfo *tables = image->tables;
1873 MonoGenericContainer *generic_container = NULL, *container = NULL;
1874 const char *sig = NULL;
1875 guint32 cols [MONO_TYPEDEF_SIZE];
1877 mono_error_init (error);
1879 if (image_is_dynamic (image)) {
1880 MonoClass *handle_class;
1882 result = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, error);
1883 mono_error_assert_ok (error);
1884 mono_loader_assert_no_error ();
1886 // This checks the memberref type as well
1887 if (result && handle_class != mono_defaults.methodhandle_class) {
1888 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1894 if (table != MONO_TABLE_METHOD) {
1895 if (table == MONO_TABLE_METHODSPEC) {
1896 if (used_context) *used_context = TRUE;
1897 return method_from_methodspec (image, context, idx, error);
1899 if (table != MONO_TABLE_MEMBERREF) {
1900 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1903 return method_from_memberref (image, idx, context, used_context, error);
1906 if (used_context) *used_context = FALSE;
1908 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1909 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1914 guint32 type = mono_metadata_typedef_from_method (image, token);
1916 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1919 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1924 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1926 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1927 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1928 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1930 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1931 methods_size += sizeof (MonoMethod);
1934 mono_stats.method_count ++;
1937 result->klass = klass;
1938 result->flags = cols [2];
1939 result->iflags = cols [1];
1940 result->token = token;
1941 result->name = mono_metadata_string_heap (image, cols [3]);
1943 if (!sig) /* already taken from the methodref */
1944 sig = mono_metadata_blob_heap (image, cols [4]);
1945 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1947 container = klass->generic_container;
1950 * load_generic_params does a binary search so only call it if the method
1954 generic_container = mono_metadata_load_generic_params (image, token, container);
1955 mono_loader_assert_no_error (); /* FIXME don't swallow this error. */
1957 if (generic_container) {
1958 result->is_generic = TRUE;
1959 generic_container->owner.method = result;
1960 generic_container->is_anonymous = FALSE; // Method is now known, container is no longer anonymous
1961 /*FIXME put this before the image alloc*/
1962 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1965 container = generic_container;
1968 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1969 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1970 result->string_ctor = 1;
1971 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1972 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1975 /* IJW is P/Invoke with a predefined function pointer. */
1976 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1977 piinfo->addr = mono_image_rva_map (image, cols [0]);
1978 g_assert (piinfo->addr);
1981 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1982 /* Native methods can have no map. */
1983 if (piinfo->implmap_idx)
1984 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1987 if (generic_container)
1988 mono_method_set_generic_container (result, generic_container);
1990 mono_loader_assert_no_error ();
1995 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1998 MonoMethod *result = mono_get_method_checked (image, token, klass, NULL, &error);
1999 mono_error_cleanup (&error);
2004 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
2005 MonoGenericContext *context)
2008 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
2009 mono_error_cleanup (&error);
2014 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
2016 MonoMethod *result = NULL;
2017 gboolean used_context = FALSE;
2019 /* We do everything inside the lock to prevent creation races */
2021 mono_error_init (error);
2023 mono_image_lock (image);
2025 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
2026 if (!image->method_cache)
2027 image->method_cache = g_hash_table_new (NULL, NULL);
2028 result = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2029 } else if (!image_is_dynamic (image)) {
2030 if (!image->methodref_cache)
2031 image->methodref_cache = g_hash_table_new (NULL, NULL);
2032 result = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2034 mono_image_unlock (image);
2040 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
2044 mono_image_lock (image);
2045 if (!used_context && !result->is_inflated) {
2046 MonoMethod *result2 = NULL;
2048 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2049 result2 = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2050 else if (!image_is_dynamic (image))
2051 result2 = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2054 mono_image_unlock (image);
2058 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2059 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
2060 else if (!image_is_dynamic (image))
2061 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
2064 mono_image_unlock (image);
2070 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
2073 MonoClass *ic = NULL;
2074 MonoGenericContext *method_context = NULL;
2075 MonoMethodSignature *sig, *original_sig;
2077 mono_error_init (error);
2079 mono_class_init (constrained_class);
2080 original_sig = sig = mono_method_signature_checked (method, error);
2085 if (method->is_inflated && sig->generic_param_count) {
2086 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2087 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
2090 method_context = mono_method_get_context (method);
2094 * We must inflate the signature with the class instantiation to work on
2095 * cases where a class inherit from a generic type and the override replaces
2096 * any type argument which a concrete type. See #325283.
2098 if (method_context->class_inst) {
2099 MonoGenericContext ctx;
2100 ctx.method_inst = NULL;
2101 ctx.class_inst = method_context->class_inst;
2102 /*Fixme, property propagate this error*/
2103 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2109 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2112 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2113 if (sig != original_sig)
2114 mono_metadata_free_inflated_signature (sig);
2119 if (method_context) {
2120 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2129 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2130 MonoGenericContext *context, MonoError *error)
2134 return get_method_constrained (image, method, constrained_class, context, error);
2138 * mono_get_method_constrained:
2140 * This is used when JITing the `constrained.' opcode.
2142 * This returns two values: the contrained method, which has been inflated
2143 * as the function return value; And the original CIL-stream method as
2144 * declared in cil_method. The later is used for verification.
2147 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2148 MonoGenericContext *context, MonoMethod **cil_method)
2151 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2152 mono_error_cleanup (&error);
2157 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2159 mono_error_init (error);
2161 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2165 return get_method_constrained (image, *cil_method, constrained_class, context, error);
2169 mono_free_method (MonoMethod *method)
2171 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2172 mono_profiler_method_free (method);
2174 /* FIXME: This hack will go away when the profiler will support freeing methods */
2175 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2178 if (method->signature) {
2180 * FIXME: This causes crashes because the types inside signatures and
2181 * locals are shared.
2183 /* mono_metadata_free_method_signature (method->signature); */
2184 /* g_free (method->signature); */
2187 if (method_is_dynamic (method)) {
2188 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2191 mono_marshal_free_dynamic_wrappers (method);
2193 mono_image_property_remove (method->klass->image, method);
2195 g_free ((char*)method->name);
2197 g_free ((char*)mw->header->code);
2198 for (i = 0; i < mw->header->num_locals; ++i)
2199 g_free (mw->header->locals [i]);
2200 g_free (mw->header->clauses);
2201 g_free (mw->header);
2203 g_free (mw->method_data);
2204 g_free (method->signature);
2210 mono_method_get_param_names (MonoMethod *method, const char **names)
2214 MonoTableInfo *methodt;
2215 MonoTableInfo *paramt;
2216 MonoMethodSignature *signature;
2219 if (method->is_inflated)
2220 method = ((MonoMethodInflated *) method)->declaring;
2222 signature = mono_method_signature (method);
2223 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2224 number of arguments and allocate a properly sized array. */
2225 if (signature == NULL)
2228 if (!signature->param_count)
2231 for (i = 0; i < signature->param_count; ++i)
2234 klass = method->klass;
2238 mono_class_init (klass);
2240 if (image_is_dynamic (klass->image)) {
2241 MonoReflectionMethodAux *method_aux =
2242 (MonoReflectionMethodAux *)g_hash_table_lookup (
2243 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2244 if (method_aux && method_aux->param_names) {
2245 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2246 if (method_aux->param_names [i + 1])
2247 names [i] = method_aux->param_names [i + 1];
2252 if (method->wrapper_type) {
2253 char **pnames = NULL;
2255 mono_image_lock (klass->image);
2256 if (klass->image->wrapper_param_names)
2257 pnames = (char **)g_hash_table_lookup (klass->image->wrapper_param_names, method);
2258 mono_image_unlock (klass->image);
2261 for (i = 0; i < signature->param_count; ++i)
2262 names [i] = pnames [i];
2267 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2268 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2269 idx = mono_method_get_index (method);
2271 guint32 cols [MONO_PARAM_SIZE];
2274 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2276 if (idx < methodt->rows)
2277 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2279 lastp = paramt->rows + 1;
2280 for (i = param_index; i < lastp; ++i) {
2281 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2282 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2283 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2289 mono_method_get_param_token (MonoMethod *method, int index)
2291 MonoClass *klass = method->klass;
2292 MonoTableInfo *methodt;
2295 mono_class_init (klass);
2297 if (image_is_dynamic (klass->image))
2298 g_assert_not_reached ();
2300 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2301 idx = mono_method_get_index (method);
2303 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2307 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2309 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2316 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2319 MonoClass *klass = method->klass;
2320 MonoTableInfo *methodt;
2321 MonoTableInfo *paramt;
2322 MonoMethodSignature *signature;
2325 signature = mono_method_signature (method);
2326 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2328 for (i = 0; i < signature->param_count + 1; ++i)
2331 if (image_is_dynamic (method->klass->image)) {
2332 MonoReflectionMethodAux *method_aux =
2333 (MonoReflectionMethodAux *)g_hash_table_lookup (
2334 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2335 if (method_aux && method_aux->param_marshall) {
2336 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2337 for (i = 0; i < signature->param_count + 1; ++i)
2338 if (dyn_specs [i]) {
2339 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2340 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2341 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2342 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2348 mono_class_init (klass);
2350 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2351 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2352 idx = mono_method_get_index (method);
2354 guint32 cols [MONO_PARAM_SIZE];
2355 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2357 if (idx < methodt->rows)
2358 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2360 lastp = paramt->rows + 1;
2362 for (i = param_index; i < lastp; ++i) {
2363 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2365 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2367 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2369 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2378 mono_method_has_marshal_info (MonoMethod *method)
2381 MonoClass *klass = method->klass;
2382 MonoTableInfo *methodt;
2383 MonoTableInfo *paramt;
2386 if (image_is_dynamic (method->klass->image)) {
2387 MonoReflectionMethodAux *method_aux =
2388 (MonoReflectionMethodAux *)g_hash_table_lookup (
2389 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2390 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2392 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2399 mono_class_init (klass);
2401 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2402 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2403 idx = mono_method_get_index (method);
2405 guint32 cols [MONO_PARAM_SIZE];
2406 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2408 if (idx + 1 < methodt->rows)
2409 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2411 lastp = paramt->rows + 1;
2413 for (i = param_index; i < lastp; ++i) {
2414 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2416 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2425 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2428 g_assert (method != NULL);
2429 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2431 if (method->is_inflated)
2432 method = ((MonoMethodInflated *) method)->declaring;
2433 data = (void **)((MonoMethodWrapper *)method)->method_data;
2434 g_assert (data != NULL);
2435 g_assert (id <= GPOINTER_TO_UINT (*data));
2442 } StackWalkUserData;
2445 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2447 StackWalkUserData *d = (StackWalkUserData *)data;
2449 switch (frame->type) {
2450 case FRAME_TYPE_DEBUGGER_INVOKE:
2451 case FRAME_TYPE_MANAGED_TO_NATIVE:
2452 case FRAME_TYPE_TRAMPOLINE:
2454 case FRAME_TYPE_MANAGED:
2455 g_assert (frame->ji);
2456 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2459 g_assert_not_reached ();
2465 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2467 StackWalkUserData ud = { func, user_data };
2468 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2472 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2474 StackWalkUserData ud = { func, user_data };
2475 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2479 MonoStackWalkAsyncSafe func;
2481 } AsyncStackWalkUserData;
2485 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2487 AsyncStackWalkUserData *d = (AsyncStackWalkUserData *)data;
2489 switch (frame->type) {
2490 case FRAME_TYPE_DEBUGGER_INVOKE:
2491 case FRAME_TYPE_MANAGED_TO_NATIVE:
2492 case FRAME_TYPE_TRAMPOLINE:
2494 case FRAME_TYPE_MANAGED:
2497 if (frame->ji->async) {
2498 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2500 return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2504 g_assert_not_reached ();
2511 * mono_stack_walk_async_safe:
2513 * Async safe version callable from signal handlers.
2516 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2519 AsyncStackWalkUserData ud = { func, user_data };
2521 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2522 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2526 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2528 MonoMethod **dest = (MonoMethod **)data;
2530 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2536 mono_method_get_last_managed (void)
2538 MonoMethod *m = NULL;
2539 mono_stack_walk_no_il (last_managed, &m);
2543 static gboolean loader_lock_track_ownership = FALSE;
2548 * See docs/thread-safety.txt for the locking strategy.
2551 mono_loader_lock (void)
2553 mono_locks_coop_acquire (&loader_mutex, LoaderLock);
2554 if (G_UNLIKELY (loader_lock_track_ownership)) {
2555 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));
2560 mono_loader_unlock (void)
2562 mono_locks_coop_release (&loader_mutex, LoaderLock);
2563 if (G_UNLIKELY (loader_lock_track_ownership)) {
2564 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));
2569 * mono_loader_lock_track_ownership:
2571 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2572 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2573 * thread owns the loader lock.
2576 mono_loader_lock_track_ownership (gboolean track)
2578 loader_lock_track_ownership = track;
2582 * mono_loader_lock_is_owned_by_self:
2584 * Return whenever the current thread owns the loader lock.
2585 * This is useful to avoid blocking operations while holding the loader lock.
2588 mono_loader_lock_is_owned_by_self (void)
2590 g_assert (loader_lock_track_ownership);
2592 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2596 * mono_loader_lock_if_inited:
2598 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2599 * be used in runtime initialization code which can be executed before mono_loader_init ().
2602 mono_loader_lock_if_inited (void)
2604 if (loader_lock_inited)
2605 mono_loader_lock ();
2609 mono_loader_unlock_if_inited (void)
2611 if (loader_lock_inited)
2612 mono_loader_unlock ();
2616 * mono_method_signature:
2618 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2620 MonoMethodSignature*
2621 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2626 gboolean can_cache_signature;
2627 MonoGenericContainer *container;
2628 MonoMethodSignature *signature = NULL, *sig2;
2631 /* We need memory barriers below because of the double-checked locking pattern */
2633 mono_error_init (error);
2636 return m->signature;
2638 img = m->klass->image;
2640 if (m->is_inflated) {
2641 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2642 /* the lock is recursive */
2643 signature = mono_method_signature (imethod->declaring);
2644 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2645 if (!mono_error_ok (error))
2648 inflated_signatures_size += mono_metadata_signature_size (signature);
2650 mono_image_lock (img);
2652 mono_memory_barrier ();
2654 m->signature = signature;
2656 mono_image_unlock (img);
2658 return m->signature;
2661 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2662 idx = mono_metadata_token_index (m->token);
2664 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2666 g_assert (!m->klass->generic_class);
2667 container = mono_method_get_generic_container (m);
2669 container = m->klass->generic_container;
2671 /* Generic signatures depend on the container so they cannot be cached */
2672 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2673 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2675 /* If the method has parameter attributes, that can modify the signature */
2676 if (mono_metadata_method_has_param_attrs (img, idx))
2677 can_cache_signature = FALSE;
2679 if (can_cache_signature) {
2680 mono_image_lock (img);
2681 signature = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2682 mono_image_unlock (img);
2686 const char *sig_body;
2687 /*TODO we should cache the failure result somewhere*/
2688 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2691 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2693 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2697 if (can_cache_signature) {
2698 mono_image_lock (img);
2699 sig2 = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2701 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2702 mono_image_unlock (img);
2705 signatures_size += mono_metadata_signature_size (signature);
2708 /* Verify metadata consistency */
2709 if (signature->generic_param_count) {
2710 if (!container || !container->is_method) {
2711 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);
2714 if (container->type_argc != signature->generic_param_count) {
2715 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);
2718 } else if (container && container->is_method && container->type_argc) {
2719 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);
2722 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2723 signature->pinvoke = 1;
2724 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2725 MonoCallConvention conv = (MonoCallConvention)0;
2726 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2727 signature->pinvoke = 1;
2729 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2730 case 0: /* no call conv, so using default */
2731 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2732 conv = MONO_CALL_DEFAULT;
2734 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2737 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2738 conv = MONO_CALL_STDCALL;
2740 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2741 conv = MONO_CALL_THISCALL;
2743 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2744 conv = MONO_CALL_FASTCALL;
2746 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2747 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2749 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);
2752 signature->call_convention = conv;
2755 mono_image_lock (img);
2757 mono_memory_barrier ();
2759 m->signature = signature;
2761 mono_image_unlock (img);
2763 return m->signature;
2767 * mono_method_signature:
2769 * Return the signature of the method M. On failure, returns NULL.
2771 MonoMethodSignature*
2772 mono_method_signature (MonoMethod *m)
2775 MonoMethodSignature *sig;
2777 sig = mono_method_signature_checked (m, &error);
2779 char *type_name = mono_type_get_full_name (m->klass);
2780 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2782 mono_error_cleanup (&error);
2789 mono_method_get_name (MonoMethod *method)
2791 return method->name;
2795 mono_method_get_class (MonoMethod *method)
2797 return method->klass;
2801 mono_method_get_token (MonoMethod *method)
2803 return method->token;
2807 mono_method_get_header_checked (MonoMethod *method, MonoError *error)
2813 MonoGenericContainer *container;
2815 mono_error_init (error);
2816 img = method->klass->image;
2818 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)) {
2819 mono_error_set_bad_image (error, img, "Method has no body");
2823 if (method->is_inflated) {
2824 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2825 MonoMethodHeader *header, *iheader;
2827 header = mono_method_get_header_checked (imethod->declaring, error);
2831 iheader = inflate_generic_header (header, mono_method_get_context (method), error);
2832 mono_metadata_free_mh (header);
2840 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2841 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2842 g_assert (mw->header);
2847 * We don't need locks here: the new header is allocated from malloc memory
2848 * and is not stored anywhere in the runtime, the user needs to free it.
2850 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2851 idx = mono_metadata_token_index (method->token);
2852 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2854 if (!mono_verifier_verify_method_header (img, rva, NULL)) {
2855 mono_error_set_bad_image (error, img, "Invalid method header, failed verification");
2859 loc = mono_image_rva_map (img, rva);
2861 mono_error_set_bad_image (error, img, "Method has zero rva");
2866 * When parsing the types of local variables, we must pass any container available
2867 * to ensure that both VAR and MVAR will get the right owner.
2869 container = mono_method_get_generic_container (method);
2871 container = method->klass->generic_container;
2872 return mono_metadata_parse_mh_full (img, container, (const char *)loc, error);
2876 mono_method_get_header (MonoMethod *method)
2879 MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
2880 mono_error_cleanup (&error);
2886 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2889 *iflags = method->iflags;
2890 return method->flags;
2894 * Find the method index in the metadata methodDef table.
2897 mono_method_get_index (MonoMethod *method)
2899 MonoClass *klass = method->klass;
2903 /* constructed array methods are not in the MethodDef table */
2907 return mono_metadata_token_index (method->token);
2909 mono_class_setup_methods (klass);
2910 if (mono_class_has_failure (klass))
2912 for (i = 0; i < klass->method.count; ++i) {
2913 if (method == klass->methods [i]) {
2914 if (klass->image->uncompressed_metadata)
2915 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2917 return klass->method.first + i + 1;