2 * loader.c: Image Loader
5 * Paolo Molaro (lupus@ximian.com)
6 * Miguel de Icaza (miguel@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 * This file is used by the interpreter and the JIT engine to locate
14 * assemblies. Used to load AssemblyRef and later to resolve various
18 * This should keep track of the assembly versions that we are loading.
26 #include <mono/metadata/metadata.h>
27 #include <mono/metadata/image.h>
28 #include <mono/metadata/assembly.h>
29 #include <mono/metadata/tokentype.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/metadata-internals.h>
32 #include <mono/metadata/loader.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/debug-helpers.h>
35 #include <mono/metadata/reflection.h>
36 #include <mono/metadata/profiler.h>
37 #include <mono/metadata/profiler-private.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/marshal.h>
40 #include <mono/metadata/lock-tracer.h>
41 #include <mono/metadata/verify-internals.h>
42 #include <mono/utils/mono-logger-internal.h>
43 #include <mono/utils/mono-dl.h>
44 #include <mono/utils/mono-membar.h>
45 #include <mono/utils/mono-counters.h>
46 #include <mono/utils/mono-error-internals.h>
47 #include <mono/utils/mono-tls.h>
49 MonoDefaults mono_defaults;
52 * This lock protects the hash tables inside MonoImage used by the metadata
53 * loading functions in class.c and loader.c.
55 * See domain-internals.h for locking policy in combination with the
58 static CRITICAL_SECTION loader_mutex;
59 static gboolean loader_lock_inited;
62 static guint32 inflated_signatures_size;
63 static guint32 memberref_sig_cache_size;
64 static guint32 methods_size;
65 static guint32 signatures_size;
68 * This TLS variable contains the last type load error encountered by the loader.
70 MonoNativeTlsKey loader_error_thread_id;
73 * This TLS variable holds how many times the current thread has acquired the loader
76 MonoNativeTlsKey loader_lock_nest_id;
78 static void dllmap_cleanup (void);
83 static gboolean inited;
86 InitializeCriticalSection (&loader_mutex);
87 loader_lock_inited = TRUE;
89 mono_native_tls_alloc (&loader_error_thread_id, NULL);
90 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
92 mono_counters_register ("Inflated signatures size",
93 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
94 mono_counters_register ("Memberref signature cache size",
95 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
96 mono_counters_register ("MonoMethod size",
97 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
98 mono_counters_register ("MonoMethodSignature size",
99 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
106 mono_loader_cleanup (void)
110 mono_native_tls_free (loader_error_thread_id);
111 mono_native_tls_free (loader_lock_nest_id);
113 DeleteCriticalSection (&loader_mutex);
114 loader_lock_inited = FALSE;
118 * Handling of type load errors should be done as follows:
120 * If something could not be loaded, the loader should call one of the
121 * mono_loader_set_error_XXX functions ()
122 * with the appropriate arguments, then return NULL to report the failure. The error
123 * should be propagated until it reaches code which can throw managed exceptions. At that
124 * point, an exception should be thrown based on the information returned by
125 * mono_loader_get_last_error (). Then the error should be cleared by calling
126 * mono_loader_clear_error ().
130 set_loader_error (MonoLoaderError *error)
132 mono_native_tls_set_value (loader_error_thread_id, error);
136 * mono_loader_set_error_assembly_load:
138 * Set the loader error for this thread.
141 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
143 MonoLoaderError *error;
145 if (mono_loader_get_last_error ())
148 error = g_new0 (MonoLoaderError, 1);
149 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
150 error->assembly_name = g_strdup (assembly_name);
151 error->ref_only = ref_only;
154 * This is not strictly needed, but some (most) of the loader code still
155 * can't deal with load errors, and this message is more helpful than an
159 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);
161 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
163 set_loader_error (error);
167 * mono_loader_set_error_type_load:
169 * Set the loader error for this thread.
172 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
174 MonoLoaderError *error;
176 if (mono_loader_get_last_error ())
179 error = g_new0 (MonoLoaderError, 1);
180 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
181 error->class_name = g_strdup (class_name);
182 error->assembly_name = g_strdup (assembly_name);
185 * This is not strictly needed, but some (most) of the loader code still
186 * can't deal with load errors, and this message is more helpful than an
189 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
191 set_loader_error (error);
195 * mono_loader_set_error_method_load:
197 * Set the loader error for this thread. MEMBER_NAME should point to a string
201 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
203 MonoLoaderError *error;
205 /* FIXME: Store the signature as well */
206 if (mono_loader_get_last_error ())
209 error = g_new0 (MonoLoaderError, 1);
210 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
211 error->class_name = g_strdup (class_name);
212 error->member_name = member_name;
214 set_loader_error (error);
218 * mono_loader_set_error_field_load:
220 * Set the loader error for this thread. MEMBER_NAME should point to a string
224 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
226 MonoLoaderError *error;
228 /* FIXME: Store the signature as well */
229 if (mono_loader_get_last_error ())
232 error = g_new0 (MonoLoaderError, 1);
233 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
234 error->klass = klass;
235 error->member_name = member_name;
237 set_loader_error (error);
241 * mono_loader_set_error_bad_image:
243 * Set the loader error for this thread.
246 mono_loader_set_error_bad_image (char *msg)
248 MonoLoaderError *error;
250 if (mono_loader_get_last_error ())
253 error = g_new0 (MonoLoaderError, 1);
254 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
257 set_loader_error (error);
262 * mono_loader_get_last_error:
264 * Returns information about the last type load exception encountered by the loader, or
265 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
268 mono_loader_get_last_error (void)
270 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
274 * mono_loader_clear_error:
276 * Disposes any loader error messages on this thread
279 mono_loader_clear_error (void)
281 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
284 g_free (ex->class_name);
285 g_free (ex->assembly_name);
289 mono_native_tls_set_value (loader_error_thread_id, NULL);
294 * mono_loader_error_prepare_exception:
295 * @error: The MonoLoaderError to turn into an exception
297 * This turns a MonoLoaderError into an exception that can be thrown
298 * and resets the Mono Loader Error state during this process.
302 mono_loader_error_prepare_exception (MonoLoaderError *error)
304 MonoException *ex = NULL;
306 switch (error->exception_type) {
307 case MONO_EXCEPTION_TYPE_LOAD: {
308 char *cname = g_strdup (error->class_name);
309 char *aname = g_strdup (error->assembly_name);
310 MonoString *class_name;
312 mono_loader_clear_error ();
314 class_name = mono_string_new (mono_domain_get (), cname);
316 ex = mono_get_exception_type_load (class_name, aname);
321 case MONO_EXCEPTION_MISSING_METHOD: {
322 char *cname = g_strdup (error->class_name);
323 char *aname = g_strdup (error->member_name);
325 mono_loader_clear_error ();
326 ex = mono_get_exception_missing_method (cname, aname);
332 case MONO_EXCEPTION_MISSING_FIELD: {
334 char *cmembername = g_strdup (error->member_name);
336 class_name = mono_type_get_full_name (error->klass);
338 class_name = g_strdup ("");
340 mono_loader_clear_error ();
342 ex = mono_get_exception_missing_field (class_name, cmembername);
344 g_free (cmembername);
348 case MONO_EXCEPTION_FILE_NOT_FOUND: {
353 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);
355 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
356 filename = g_strdup (error->assembly_name);
357 /* Has to call this before calling anything which might call mono_class_init () */
358 mono_loader_clear_error ();
359 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
365 case MONO_EXCEPTION_BAD_IMAGE: {
366 char *msg = g_strdup (error->msg);
367 mono_loader_clear_error ();
368 ex = mono_get_exception_bad_image_format (msg);
374 g_assert_not_reached ();
381 * find_cached_memberref_sig:
383 * Return a cached copy of the memberref signature identified by SIG_IDX.
384 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
385 * A cache is needed since the type/signature parsing routines allocate everything
386 * from a mempool, so without a cache, multiple requests for the same signature would
387 * lead to unbounded memory growth. For normal methods/fields this is not a problem
388 * since the resulting methods/fields are cached, but inflated methods/fields cannot
390 * LOCKING: Acquires the loader lock.
393 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
398 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
399 mono_loader_unlock ();
405 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
410 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
412 /* Somebody got in before us */
416 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
417 /* An approximation based on glib 2.18 */
418 memberref_sig_cache_size += sizeof (gpointer) * 4;
421 mono_loader_unlock ();
426 static MonoClassField*
427 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
428 MonoGenericContext *context)
431 MonoClassField *field;
432 MonoTableInfo *tables = image->tables;
435 guint32 nindex, class, class_table;
438 guint32 idx = mono_metadata_token_index (token);
440 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
441 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
442 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
444 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
446 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
447 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
452 case MONO_MEMBERREF_PARENT_TYPEDEF:
453 class_table = MONO_TOKEN_TYPE_DEF;
454 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
456 case MONO_MEMBERREF_PARENT_TYPEREF:
457 class_table = MONO_TOKEN_TYPE_REF;
458 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
460 case MONO_MEMBERREF_PARENT_TYPESPEC:
461 class_table = MONO_TOKEN_TYPE_SPEC;
462 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
465 /*FIXME this must set a loader error!*/
466 g_warning ("field load from %x", class);
471 char *name = mono_class_name_from_token (image, class_table | nindex);
472 g_warning ("Missing field %s in class %s (type token %d)", fname, name, class_table | nindex);
473 mono_loader_set_error_type_load (name, image->assembly_name);
478 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
479 mono_metadata_decode_blob_size (ptr, &ptr);
480 /* we may want to check the signature here... */
483 g_warning ("Bad field signature class token %08x field name %s token %08x", class, fname, token);
484 mono_loader_set_error_field_load (klass, fname);
487 /* FIXME: This needs a cache, especially for generic instances, since
488 * mono_metadata_parse_type () allocates everything from a mempool.
490 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
492 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
493 if (sig_type == NULL) {
494 mono_loader_set_error_field_load (klass, fname);
497 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
500 mono_class_init (klass); /*FIXME is this really necessary?*/
503 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
506 mono_loader_set_error_field_load (klass, fname);
512 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
513 MonoGenericContext *context)
517 MonoClassField *field;
519 if (image->dynamic) {
520 MonoClassField *result;
521 MonoClass *handle_class;
524 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
525 // This checks the memberref type as well
526 if (!result || handle_class != mono_defaults.fieldhandle_class) {
527 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field token 0x%08x on image %s.", token, image->name));
530 *retklass = result->parent;
535 if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
536 *retklass = field->parent;
537 mono_loader_unlock ();
540 mono_loader_unlock ();
542 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
543 field = field_from_memberref (image, token, retklass, context);
545 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
548 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
554 field = mono_class_get_field (k, token);
558 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
559 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
560 mono_loader_unlock ();
565 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
569 if (sig1->hasthis != sig2->hasthis ||
570 sig1->sentinelpos != sig2->sentinelpos)
573 for (i = 0; i < sig1->sentinelpos; i++) {
574 MonoType *p1 = sig1->params[i];
575 MonoType *p2 = sig2->params[i];
577 /*if (p1->attrs != p2->attrs)
580 if (!mono_metadata_type_equal (p1, p2))
584 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
590 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
591 MonoMethodSignature *sig, MonoClass *from_class)
595 /* Search directly in the metadata to avoid calling setup_methods () */
597 /* FIXME: !from_class->generic_class condition causes test failures. */
598 if (klass->type_token && !klass->image->dynamic && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
599 for (i = 0; i < klass->method.count; ++i) {
600 guint32 cols [MONO_METHOD_SIZE];
603 MonoMethodSignature *other_sig;
605 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
607 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
609 if (!((fqname && !strcmp (m_name, fqname)) ||
610 (qname && !strcmp (m_name, qname)) ||
611 (name && !strcmp (m_name, name))))
614 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
616 other_sig = mono_method_signature (method);
617 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
623 mono_class_setup_methods (klass);
625 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
626 See mono/tests/generic-type-load-exception.2.il
627 FIXME we should better report this error to the caller
631 for (i = 0; i < klass->method.count; ++i) {
632 MonoMethod *m = klass->methods [i];
633 MonoMethodSignature *msig;
635 /* We must cope with failing to load some of the types. */
639 if (!((fqname && !strcmp (m->name, fqname)) ||
640 (qname && !strcmp (m->name, qname)) ||
641 (name && !strcmp (m->name, name))))
643 msig = mono_method_signature (m);
647 if (sig->call_convention == MONO_CALL_VARARG) {
648 if (mono_metadata_signature_vararg_match (sig, msig))
651 if (mono_metadata_signature_equal (sig, msig))
656 if (i < klass->method.count)
657 return mono_class_get_method_by_index (from_class, i);
662 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
665 char *qname, *fqname, *class_name;
666 gboolean is_interface;
667 MonoMethod *result = NULL;
669 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
672 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
674 qname = g_strconcat (class_name, ".", name, NULL);
675 if (ic->name_space && ic->name_space [0])
676 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
680 class_name = qname = fqname = NULL;
683 g_assert (from_class);
684 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
688 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
692 * This happens when we fail to lazily load the interfaces of one of the types.
693 * On such case we can't just bail out since user code depends on us trying harder.
695 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
696 in_class = in_class->parent;
697 from_class = from_class->parent;
701 for (i = 0; i < in_class->interface_offsets_count; i++) {
702 MonoClass *in_ic = in_class->interfaces_packed [i];
703 MonoClass *from_ic = from_class->interfaces_packed [i];
704 char *ic_qname, *ic_fqname, *ic_class_name;
706 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
707 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
708 if (in_ic->name_space && in_ic->name_space [0])
709 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
713 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic);
714 g_free (ic_class_name);
721 in_class = in_class->parent;
722 from_class = from_class->parent;
724 g_assert (!in_class == !from_class);
727 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
736 static MonoMethodSignature*
737 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
739 MonoMethodSignature *res;
743 mono_error_init (error);
747 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
748 res->param_count = sig->param_count;
749 res->sentinelpos = -1;
750 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
751 if (!mono_error_ok (error))
753 is_open = mono_class_is_open_constructed_type (res->ret);
754 for (i = 0; i < sig->param_count; ++i) {
755 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
756 if (!mono_error_ok (error))
760 is_open = mono_class_is_open_constructed_type (res->params [i]);
762 res->hasthis = sig->hasthis;
763 res->explicit_this = sig->explicit_this;
764 res->call_convention = sig->call_convention;
765 res->pinvoke = sig->pinvoke;
766 res->generic_param_count = sig->generic_param_count;
767 res->sentinelpos = sig->sentinelpos;
768 res->has_type_parameters = is_open;
769 res->is_inflated = 1;
774 mono_metadata_free_type (res->ret);
775 for (i = 0; i < sig->param_count; ++i) {
777 mono_metadata_free_type (res->params [i]);
783 static MonoMethodHeader*
784 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
786 MonoMethodHeader *res;
788 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
789 res->code = header->code;
790 res->code_size = header->code_size;
791 res->max_stack = header->max_stack;
792 res->num_clauses = header->num_clauses;
793 res->init_locals = header->init_locals;
794 res->num_locals = header->num_locals;
795 res->clauses = header->clauses;
796 for (i = 0; i < header->num_locals; ++i)
797 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
798 if (res->num_clauses) {
799 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
800 for (i = 0; i < header->num_clauses; ++i) {
801 MonoExceptionClause *clause = &res->clauses [i];
802 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
804 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
811 * token is the method_ref/def/spec token used in a call IL instruction.
814 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
816 int table = mono_metadata_token_table (token);
817 int idx = mono_metadata_token_index (token);
819 guint32 cols [MONO_MEMBERREF_SIZE];
820 MonoMethodSignature *sig;
823 /* !table is for wrappers: we should really assign their own token to them */
824 if (!table || table == MONO_TABLE_METHOD)
825 return mono_method_signature (method);
827 if (table == MONO_TABLE_METHODSPEC) {
828 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
829 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
832 return mono_method_signature (method);
835 if (method->klass->generic_class)
836 return mono_method_signature (method);
838 if (image->dynamic) {
839 sig = mono_reflection_lookup_signature (image, method, token);
841 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
842 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
844 sig = find_cached_memberref_sig (image, sig_idx);
846 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
847 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
848 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
850 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
854 ptr = mono_metadata_blob_heap (image, sig_idx);
855 mono_metadata_decode_blob_size (ptr, &ptr);
856 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
859 sig = cache_memberref_sig (image, sig_idx, sig);
861 /* FIXME: we probably should verify signature compat in the dynamic case too*/
862 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
863 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
864 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
866 mono_loader_set_error_bad_image (g_strdup_printf ("Incompatible method signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
874 MonoMethodSignature *cached;
876 /* This signature is not owned by a MonoMethod, so need to cache */
877 sig = inflate_generic_signature_checked (image, sig, context, &error);
878 if (!mono_error_ok (&error)) {/*XXX bubble up this and kill one use of loader errors */
879 mono_loader_set_error_bad_image (g_strdup_printf ("Could not inflate signature %s", mono_error_get_message (&error)));
880 mono_error_cleanup (&error);
884 cached = mono_metadata_get_inflated_signature (sig, context);
886 mono_metadata_free_inflated_signature (sig);
888 inflated_signatures_size += mono_metadata_signature_size (cached);
896 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
898 return mono_method_get_signature_full (method, image, token, NULL);
901 /* this is only for the typespec array methods */
903 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
907 mono_class_setup_methods (klass);
908 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
909 for (i = 0; i < klass->method.count; ++i) {
910 MonoMethod *method = klass->methods [i];
911 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
918 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
919 gboolean *used_context)
921 MonoClass *klass = NULL;
922 MonoMethod *method = NULL;
923 MonoTableInfo *tables = image->tables;
925 guint32 nindex, class, sig_idx;
927 MonoMethodSignature *sig;
930 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
931 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
932 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
933 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
934 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
936 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
939 * Whether we actually used the `typespec_context' or not.
940 * This is used to tell our caller whether or not it's safe to insert the returned
941 * method into a cache.
944 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
947 case MONO_MEMBERREF_PARENT_TYPEREF:
948 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
950 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
951 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
952 mono_loader_set_error_type_load (name, image->assembly_name);
957 case MONO_MEMBERREF_PARENT_TYPESPEC:
959 * Parse the TYPESPEC in the parent's context.
961 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
963 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
964 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
965 mono_loader_set_error_type_load (name, image->assembly_name);
970 case MONO_MEMBERREF_PARENT_TYPEDEF:
971 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
973 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
974 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
975 mono_loader_set_error_type_load (name, image->assembly_name);
980 case MONO_MEMBERREF_PARENT_METHODDEF:
981 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
985 /* This message leaks */
986 char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
987 mono_loader_set_error_method_load ("", message);
993 mono_class_init (klass);
995 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
997 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
998 mono_loader_set_error_method_load (klass->name, mname);
1002 ptr = mono_metadata_blob_heap (image, sig_idx);
1003 mono_metadata_decode_blob_size (ptr, &ptr);
1005 sig = find_cached_memberref_sig (image, sig_idx);
1007 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
1011 sig = cache_memberref_sig (image, sig_idx, sig);
1015 case MONO_MEMBERREF_PARENT_TYPEREF:
1016 case MONO_MEMBERREF_PARENT_TYPEDEF:
1017 method = find_method (klass, NULL, mname, sig, klass);
1020 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1023 type = &klass->byval_arg;
1025 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1026 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1027 method = find_method (in_class, NULL, mname, sig, klass);
1031 /* we're an array and we created these methods already in klass in mono_class_init () */
1032 method = mono_method_search_in_array_class (klass, mname, sig);
1036 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
1037 g_assert_not_reached ();
1041 char *msig = mono_signature_get_desc (sig, FALSE);
1042 char * class_name = mono_type_get_name (&klass->byval_arg);
1043 GString *s = g_string_new (mname);
1044 if (sig->generic_param_count)
1045 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1046 g_string_append_printf (s, "(%s)", msig);
1048 msig = g_string_free (s, FALSE);
1051 "Missing method %s::%s in assembly %s, referenced in assembly %s",
1052 class_name, msig, klass->image->name, image->name);
1053 mono_loader_set_error_method_load (class_name, mname);
1055 g_free (class_name);
1062 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
1067 MonoTableInfo *tables = image->tables;
1068 MonoGenericContext new_context;
1069 MonoGenericInst *inst;
1071 guint32 cols [MONO_METHODSPEC_SIZE];
1072 guint32 token, nindex, param_count;
1074 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1075 token = cols [MONO_METHODSPEC_METHOD];
1076 nindex = token >> MONO_METHODDEFORREF_BITS;
1078 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL))
1081 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1083 mono_metadata_decode_value (ptr, &ptr);
1085 param_count = mono_metadata_decode_value (ptr, &ptr);
1086 g_assert (param_count);
1088 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1092 if (context && inst->is_open) {
1093 inst = mono_metadata_inflate_generic_inst (inst, context, &error);
1094 if (!mono_error_ok (&error)) {
1095 mono_error_cleanup (&error); /*FIXME don't swallow error message.*/
1100 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
1101 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
1103 method = method_from_memberref (image, nindex, context, NULL);
1108 klass = method->klass;
1110 if (klass->generic_class) {
1111 g_assert (method->is_inflated);
1112 method = ((MonoMethodInflated *) method)->declaring;
1115 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1116 new_context.method_inst = inst;
1118 return mono_class_inflate_generic_method_full (method, klass, &new_context);
1121 struct _MonoDllMap {
1129 static MonoDllMap *global_dll_map;
1132 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1140 mono_loader_lock ();
1143 * we use the first entry we find that matches, since entries from
1144 * the config file are prepended to the list and we document that the
1145 * later entries win.
1147 for (; dll_map; dll_map = dll_map->next) {
1148 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1149 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1151 } else if (strcmp (dll_map->dll, dll)) {
1154 if (!found && dll_map->target) {
1155 *rdll = dll_map->target;
1157 /* we don't quit here, because we could find a full
1158 * entry that matches also function and that has priority.
1161 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1162 *rfunc = dll_map->target_func;
1167 mono_loader_unlock ();
1172 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1175 if (assembly && assembly->dll_map) {
1176 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1180 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1184 * mono_dllmap_insert:
1185 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1186 * @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
1187 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1188 * @tdll: The name of the library to map the specified @dll if it matches.
1189 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1191 * LOCKING: Acquires the loader lock.
1193 * This function is used to programatically add DllImport remapping in either
1194 * a specific assembly, or as a global remapping. This is done by remapping
1195 * references in a DllImport attribute from the @dll library name into the @tdll
1196 * name. If the @dll name contains the prefix "i:", the comparison of the
1197 * library name is done without case sensitivity.
1199 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1200 * or the name of the function as determined by DllImport. If you pass @func, you
1201 * must also pass @tfunc which is the name of the target function to invoke on a match.
1204 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1206 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1207 * the contents of relocated_demo_path for all assemblies in the Mono process.
1209 * NOTE: This can be called before the runtime is initialized, for example from
1210 * mono_config_parse ().
1213 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1217 mono_loader_init ();
1219 mono_loader_lock ();
1222 entry = g_malloc0 (sizeof (MonoDllMap));
1223 entry->dll = dll? g_strdup (dll): NULL;
1224 entry->target = tdll? g_strdup (tdll): NULL;
1225 entry->func = func? g_strdup (func): NULL;
1226 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1227 entry->next = global_dll_map;
1228 global_dll_map = entry;
1230 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1231 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1232 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1233 entry->func = func? mono_image_strdup (assembly, func): NULL;
1234 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1235 entry->next = assembly->dll_map;
1236 assembly->dll_map = entry;
1239 mono_loader_unlock ();
1243 free_dllmap (MonoDllMap *map)
1246 MonoDllMap *next = map->next;
1249 g_free (map->target);
1251 g_free (map->target_func);
1258 dllmap_cleanup (void)
1260 free_dllmap (global_dll_map);
1261 global_dll_map = NULL;
1264 static GHashTable *global_module_map;
1267 cached_module_load (const char *name, int flags, char **err)
1273 mono_loader_lock ();
1274 if (!global_module_map)
1275 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1276 res = g_hash_table_lookup (global_module_map, name);
1278 mono_loader_unlock ();
1281 res = mono_dl_open (name, flags, err);
1283 g_hash_table_insert (global_module_map, g_strdup (name), res);
1284 mono_loader_unlock ();
1288 static MonoDl *internal_module;
1291 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1293 MonoImage *image = method->klass->image;
1294 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1295 MonoTableInfo *tables = image->tables;
1296 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1297 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1298 guint32 im_cols [MONO_IMPLMAP_SIZE];
1299 guint32 scope_token;
1300 const char *import = NULL;
1301 const char *orig_scope;
1302 const char *new_scope;
1304 char *full_name, *file_name, *found_name = NULL;
1306 MonoDl *module = NULL;
1307 gboolean cached = FALSE;
1309 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1317 return piinfo->addr;
1319 if (method->klass->image->dynamic) {
1320 MonoReflectionMethodAux *method_aux =
1321 g_hash_table_lookup (
1322 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1326 import = method_aux->dllentry;
1327 orig_scope = method_aux->dll;
1330 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1333 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1335 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1338 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1339 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1340 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1341 orig_scope = mono_metadata_string_heap (image, scope_token);
1344 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1347 mono_loader_lock ();
1348 if (!image->pinvoke_scopes) {
1349 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1350 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1352 module = g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1353 found_name = g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1354 mono_loader_unlock ();
1358 found_name = g_strdup (found_name);
1362 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1363 "DllImport attempting to load: '%s'.", new_scope);
1365 /* we allow a special name to dlopen from the running process namespace */
1366 if (strcmp (new_scope, "__Internal") == 0){
1367 if (internal_module == NULL)
1368 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1369 module = internal_module;
1374 * Try loading the module using a variety of names
1376 for (i = 0; i < 4; ++i) {
1379 /* Try the original name */
1380 file_name = g_strdup (new_scope);
1383 /* Try trimming the .dll extension */
1384 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1385 file_name = g_strdup (new_scope);
1386 file_name [strlen (new_scope) - 4] = '\0';
1392 if (strstr (new_scope, "lib") != new_scope) {
1393 file_name = g_strdup_printf ("lib%s", new_scope);
1399 #ifndef TARGET_WIN32
1400 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1401 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1402 !g_ascii_strcasecmp ("user32", new_scope) ||
1403 !g_ascii_strcasecmp ("kernel", new_scope)) {
1404 file_name = g_strdup ("libMonoSupportW.so");
1408 #ifndef TARGET_WIN32
1413 if (!module && g_path_is_absolute (file_name)) {
1414 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1416 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1417 "DllImport error loading library '%s': '%s'.",
1418 file_name, error_msg);
1421 found_name = g_strdup (file_name);
1427 char *mdirname = g_path_get_dirname (image->name);
1428 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1429 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1431 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1432 "DllImport error loading library '%s': '%s'.",
1433 full_name, error_msg);
1436 found_name = g_strdup (full_name);
1447 while ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {
1448 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1450 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1451 "DllImport error loading library '%s': '%s'.",
1452 full_name, error_msg);
1455 found_name = g_strdup (full_name);
1464 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1466 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1467 "DllImport error loading library '%s': '%s'.",
1468 file_name, error_msg);
1470 found_name = g_strdup (file_name);
1481 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1482 "DllImport unable to load library '%s'.",
1487 *exc_class = "DllNotFoundException";
1488 *exc_arg = new_scope;
1494 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1495 "DllImport loaded library '%s'.", found_name);
1496 mono_loader_lock ();
1497 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1498 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1499 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1501 mono_loader_unlock ();
1504 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1505 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1506 g_free (found_name);
1509 if (import && import [0] == '#' && isdigit (import [1])) {
1513 id = strtol (import + 1, &end, 10);
1514 if (id > 0 && *end == '\0')
1518 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1519 "Searching for '%s'.", import);
1521 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1522 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1524 char *mangled_name = NULL, *mangled_name2 = NULL;
1527 int mangle_param_count;
1533 * Search using a variety of mangled names
1535 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1536 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1537 gboolean need_param_count = FALSE;
1539 if (mangle_stdcall > 0)
1540 need_param_count = TRUE;
1542 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1547 mangled_name = (char*)import;
1548 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1549 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1550 /* Try the mangled name first */
1551 if (mangle_charset == 0)
1552 mangled_name = g_strconcat (import, "W", NULL);
1554 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1556 if (mangle_charset == 0)
1557 mangled_name = g_strconcat (import, "W", NULL);
1559 /* Try the mangled name last */
1560 if (mangle_charset == 1)
1561 mangled_name = g_strconcat (import, "A", NULL);
1564 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1566 /* Try the mangled name last */
1567 if (mangle_charset == 1)
1568 mangled_name = g_strconcat (import, "A", NULL);
1573 if (mangle_param_count == 0)
1574 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1576 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1577 param_count = mangle_param_count;
1579 /* Try the stdcall mangled name */
1581 * gcc under windows creates mangled names without the underscore, but MS.NET
1582 * doesn't support it, so we doesn't support it either.
1584 if (mangle_stdcall == 1)
1585 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1587 mangled_name2 = mangled_name;
1589 mangled_name2 = mangled_name;
1592 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1593 "Probing '%s'.", mangled_name2);
1595 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1600 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1601 "Found as '%s'.", mangled_name2);
1603 if (mangled_name != mangled_name2)
1604 g_free (mangled_name2);
1605 if (mangled_name != import)
1606 g_free (mangled_name);
1612 if (!piinfo->addr) {
1615 *exc_class = "EntryPointNotFoundException";
1620 return piinfo->addr;
1624 * LOCKING: assumes the loader lock to be taken.
1627 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1628 MonoGenericContext *context, gboolean *used_context)
1631 int table = mono_metadata_token_table (token);
1632 int idx = mono_metadata_token_index (token);
1633 MonoTableInfo *tables = image->tables;
1634 MonoGenericContainer *generic_container = NULL, *container = NULL;
1635 const char *sig = NULL;
1637 guint32 cols [MONO_TYPEDEF_SIZE];
1639 if (image->dynamic) {
1640 MonoClass *handle_class;
1642 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1643 // This checks the memberref type as well
1644 if (result && handle_class != mono_defaults.methodhandle_class) {
1645 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1651 if (table != MONO_TABLE_METHOD) {
1652 if (table == MONO_TABLE_METHODSPEC) {
1653 if (used_context) *used_context = TRUE;
1654 return method_from_methodspec (image, context, idx);
1656 if (table != MONO_TABLE_MEMBERREF) {
1657 g_warning ("got wrong token: 0x%08x\n", token);
1658 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1661 return method_from_memberref (image, idx, context, used_context);
1664 if (used_context) *used_context = FALSE;
1666 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1667 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1671 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1673 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1674 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1675 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1677 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1678 methods_size += sizeof (MonoMethod);
1681 mono_stats.method_count ++;
1683 if (!klass) { /*FIXME put this before the image alloc*/
1684 guint32 type = mono_metadata_typedef_from_method (image, token);
1687 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1693 result->klass = klass;
1694 result->flags = cols [2];
1695 result->iflags = cols [1];
1696 result->token = token;
1697 result->name = mono_metadata_string_heap (image, cols [3]);
1699 if (!sig) /* already taken from the methodref */
1700 sig = mono_metadata_blob_heap (image, cols [4]);
1701 size = mono_metadata_decode_blob_size (sig, &sig);
1703 container = klass->generic_container;
1706 * load_generic_params does a binary search so only call it if the method
1710 generic_container = mono_metadata_load_generic_params (image, token, container);
1711 if (generic_container) {
1712 result->is_generic = TRUE;
1713 generic_container->owner.method = result;
1714 /*FIXME put this before the image alloc*/
1715 if (!mono_metadata_load_generic_param_constraints_full (image, token, generic_container))
1718 container = generic_container;
1721 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1722 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1723 result->string_ctor = 1;
1724 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1725 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1728 /* IJW is P/Invoke with a predefined function pointer. */
1729 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1730 piinfo->addr = mono_image_rva_map (image, cols [0]);
1731 g_assert (piinfo->addr);
1734 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1735 /* Native methods can have no map. */
1736 if (piinfo->implmap_idx)
1737 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1740 if (generic_container)
1741 mono_method_set_generic_container (result, generic_container);
1747 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1749 return mono_get_method_full (image, token, klass, NULL);
1753 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1754 MonoGenericContext *context)
1757 gboolean used_context = FALSE;
1759 /* We do everything inside the lock to prevent creation races */
1761 mono_image_lock (image);
1763 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1764 if (!image->method_cache)
1765 image->method_cache = g_hash_table_new (NULL, NULL);
1766 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1768 if (!image->methodref_cache)
1769 image->methodref_cache = g_hash_table_new (NULL, NULL);
1770 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1772 mono_image_unlock (image);
1777 result = mono_get_method_from_token (image, token, klass, context, &used_context);
1781 mono_image_lock (image);
1782 if (!used_context && !result->is_inflated) {
1783 MonoMethod *result2;
1784 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1785 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1787 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1790 mono_image_unlock (image);
1794 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1795 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1797 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1800 mono_image_unlock (image);
1806 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context)
1809 MonoClass *ic = NULL;
1810 MonoGenericContext *method_context = NULL;
1811 MonoMethodSignature *sig, *original_sig;
1813 mono_class_init (constrained_class);
1814 original_sig = sig = mono_method_signature (method);
1819 if (method->is_inflated && sig->generic_param_count) {
1820 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1821 sig = mono_method_signature (imethod->declaring); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1822 method_context = mono_method_get_context (method);
1826 * We must inflate the signature with the class instantiation to work on
1827 * cases where a class inherit from a generic type and the override replaces
1828 * any type argument which a concrete type. See #325283.
1830 if (method_context->class_inst) {
1832 MonoGenericContext ctx;
1833 ctx.method_inst = NULL;
1834 ctx.class_inst = method_context->class_inst;
1835 /*Fixme, property propagate this error*/
1836 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, &error);
1837 if (!mono_error_ok (&error)) {
1838 mono_error_cleanup (&error);
1844 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1847 result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1848 if (sig != original_sig)
1849 mono_metadata_free_inflated_signature (sig);
1852 char *m = mono_method_full_name (method, 1);
1853 g_warning ("Missing method %s.%s.%s in assembly %s method %s", method->klass->name_space,
1854 method->klass->name, method->name, image->name, m);
1860 result = mono_class_inflate_generic_method (result, method_context);
1866 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
1867 MonoGenericContext *context)
1873 mono_loader_lock ();
1875 result = get_method_constrained (image, method, constrained_class, context);
1877 mono_loader_unlock ();
1881 * mono_get_method_constrained:
1883 * This is used when JITing the `constrained.' opcode.
1885 * This returns two values: the contrained method, which has been inflated
1886 * as the function return value; And the original CIL-stream method as
1887 * declared in cil_method. The later is used for verification.
1890 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1891 MonoGenericContext *context, MonoMethod **cil_method)
1895 mono_loader_lock ();
1897 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL);
1899 mono_loader_unlock ();
1903 result = get_method_constrained (image, *cil_method, constrained_class, context);
1905 mono_loader_unlock ();
1910 mono_free_method (MonoMethod *method)
1912 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1913 mono_profiler_method_free (method);
1915 /* FIXME: This hack will go away when the profiler will support freeing methods */
1916 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1919 if (method->signature) {
1921 * FIXME: This causes crashes because the types inside signatures and
1922 * locals are shared.
1924 /* mono_metadata_free_method_signature (method->signature); */
1925 /* g_free (method->signature); */
1928 if (method->dynamic) {
1929 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1932 mono_marshal_free_dynamic_wrappers (method);
1934 mono_image_property_remove (method->klass->image, method);
1936 g_free ((char*)method->name);
1938 g_free ((char*)mw->header->code);
1939 for (i = 0; i < mw->header->num_locals; ++i)
1940 g_free (mw->header->locals [i]);
1941 g_free (mw->header->clauses);
1942 g_free (mw->header);
1944 g_free (mw->method_data);
1945 g_free (method->signature);
1951 mono_method_get_param_names (MonoMethod *method, const char **names)
1955 MonoTableInfo *methodt;
1956 MonoTableInfo *paramt;
1957 MonoMethodSignature *signature;
1960 if (method->is_inflated)
1961 method = ((MonoMethodInflated *) method)->declaring;
1963 signature = mono_method_signature (method);
1964 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
1965 number of arguments and allocate a properly sized array. */
1966 if (signature == NULL)
1969 if (!signature->param_count)
1972 for (i = 0; i < signature->param_count; ++i)
1975 klass = method->klass;
1979 mono_class_init (klass);
1981 if (klass->image->dynamic) {
1982 MonoReflectionMethodAux *method_aux =
1983 g_hash_table_lookup (
1984 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1985 if (method_aux && method_aux->param_names) {
1986 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1987 if (method_aux->param_names [i + 1])
1988 names [i] = method_aux->param_names [i + 1];
1993 if (method->wrapper_type) {
1994 char **pnames = NULL;
1996 mono_image_lock (klass->image);
1997 if (klass->image->wrapper_param_names)
1998 pnames = g_hash_table_lookup (klass->image->wrapper_param_names, method);
1999 mono_image_unlock (klass->image);
2002 for (i = 0; i < signature->param_count; ++i)
2003 names [i] = pnames [i];
2008 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2009 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2010 idx = mono_method_get_index (method);
2012 guint32 cols [MONO_PARAM_SIZE];
2015 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2017 if (idx < methodt->rows)
2018 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2020 lastp = paramt->rows + 1;
2021 for (i = param_index; i < lastp; ++i) {
2022 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2023 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2024 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2030 mono_method_get_param_token (MonoMethod *method, int index)
2032 MonoClass *klass = method->klass;
2033 MonoTableInfo *methodt;
2036 mono_class_init (klass);
2038 if (klass->image->dynamic) {
2039 g_assert_not_reached ();
2042 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2043 idx = mono_method_get_index (method);
2045 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2049 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2051 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2058 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2061 MonoClass *klass = method->klass;
2062 MonoTableInfo *methodt;
2063 MonoTableInfo *paramt;
2064 MonoMethodSignature *signature;
2067 signature = mono_method_signature (method);
2068 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2070 for (i = 0; i < signature->param_count + 1; ++i)
2073 if (method->klass->image->dynamic) {
2074 MonoReflectionMethodAux *method_aux =
2075 g_hash_table_lookup (
2076 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2077 if (method_aux && method_aux->param_marshall) {
2078 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2079 for (i = 0; i < signature->param_count + 1; ++i)
2080 if (dyn_specs [i]) {
2081 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2082 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2083 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2084 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2090 mono_class_init (klass);
2092 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2093 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2094 idx = mono_method_get_index (method);
2096 guint32 cols [MONO_PARAM_SIZE];
2097 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2099 if (idx < methodt->rows)
2100 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2102 lastp = paramt->rows + 1;
2104 for (i = param_index; i < lastp; ++i) {
2105 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2107 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2109 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2111 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2120 mono_method_has_marshal_info (MonoMethod *method)
2123 MonoClass *klass = method->klass;
2124 MonoTableInfo *methodt;
2125 MonoTableInfo *paramt;
2128 if (method->klass->image->dynamic) {
2129 MonoReflectionMethodAux *method_aux =
2130 g_hash_table_lookup (
2131 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2132 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2134 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2141 mono_class_init (klass);
2143 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2144 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2145 idx = mono_method_get_index (method);
2147 guint32 cols [MONO_PARAM_SIZE];
2148 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2150 if (idx + 1 < methodt->rows)
2151 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2153 lastp = paramt->rows + 1;
2155 for (i = param_index; i < lastp; ++i) {
2156 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2158 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2167 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2170 g_assert (method != NULL);
2171 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2173 if (method->is_inflated)
2174 method = ((MonoMethodInflated *) method)->declaring;
2175 data = ((MonoMethodWrapper *)method)->method_data;
2176 g_assert (data != NULL);
2177 g_assert (id <= GPOINTER_TO_UINT (*data));
2184 } StackWalkUserData;
2187 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2189 StackWalkUserData *d = data;
2191 switch (frame->type) {
2192 case FRAME_TYPE_DEBUGGER_INVOKE:
2193 case FRAME_TYPE_MANAGED_TO_NATIVE:
2195 case FRAME_TYPE_MANAGED:
2196 g_assert (frame->ji);
2197 return d->func (frame->ji->method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2200 g_assert_not_reached ();
2206 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2208 StackWalkUserData ud = { func, user_data };
2209 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2213 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2215 StackWalkUserData ud = { func, user_data };
2216 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2220 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2222 MonoMethod **dest = data;
2224 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2230 mono_method_get_last_managed (void)
2232 MonoMethod *m = NULL;
2233 mono_stack_walk_no_il (last_managed, &m);
2237 static gboolean loader_lock_track_ownership = FALSE;
2242 * See docs/thread-safety.txt for the locking strategy.
2245 mono_loader_lock (void)
2247 mono_locks_acquire (&loader_mutex, LoaderLock);
2248 if (G_UNLIKELY (loader_lock_track_ownership)) {
2249 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));
2254 mono_loader_unlock (void)
2256 mono_locks_release (&loader_mutex, LoaderLock);
2257 if (G_UNLIKELY (loader_lock_track_ownership)) {
2258 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));
2263 * mono_loader_lock_track_ownership:
2265 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2266 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2267 * thread owns the loader lock.
2270 mono_loader_lock_track_ownership (gboolean track)
2272 loader_lock_track_ownership = track;
2276 * mono_loader_lock_is_owned_by_self:
2278 * Return whenever the current thread owns the loader lock.
2279 * This is useful to avoid blocking operations while holding the loader lock.
2282 mono_loader_lock_is_owned_by_self (void)
2284 g_assert (loader_lock_track_ownership);
2286 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2290 * mono_loader_lock_if_inited:
2292 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2293 * be used in runtime initialization code which can be executed before mono_loader_init ().
2296 mono_loader_lock_if_inited (void)
2298 if (loader_lock_inited)
2299 mono_loader_lock ();
2303 mono_loader_unlock_if_inited (void)
2305 if (loader_lock_inited)
2306 mono_loader_unlock ();
2310 * mono_method_signature:
2312 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2314 MonoMethodSignature*
2315 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2321 gboolean can_cache_signature;
2322 MonoGenericContainer *container;
2323 MonoMethodSignature *signature = NULL;
2326 /* We need memory barriers below because of the double-checked locking pattern */
2328 mono_error_init (error);
2331 return m->signature;
2333 mono_loader_lock ();
2336 mono_loader_unlock ();
2337 return m->signature;
2340 if (m->is_inflated) {
2341 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2342 /* the lock is recursive */
2343 signature = mono_method_signature (imethod->declaring);
2344 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2345 if (!mono_error_ok (error)) {
2346 mono_loader_unlock ();
2350 inflated_signatures_size += mono_metadata_signature_size (signature);
2352 mono_memory_barrier ();
2353 m->signature = signature;
2354 mono_loader_unlock ();
2355 return m->signature;
2358 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2359 idx = mono_metadata_token_index (m->token);
2360 img = m->klass->image;
2362 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2364 g_assert (!m->klass->generic_class);
2365 container = mono_method_get_generic_container (m);
2367 container = m->klass->generic_container;
2369 /* Generic signatures depend on the container so they cannot be cached */
2370 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2371 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2373 /* If the method has parameter attributes, that can modify the signature */
2374 if (mono_metadata_method_has_param_attrs (img, idx))
2375 can_cache_signature = FALSE;
2377 if (can_cache_signature)
2378 signature = g_hash_table_lookup (img->method_signatures, sig);
2381 const char *sig_body;
2382 /*TODO we should cache the failure result somewhere*/
2383 if (!mono_verifier_verify_method_signature (img, sig_offset, error)) {
2384 mono_loader_unlock ();
2388 size = mono_metadata_decode_blob_size (sig, &sig_body);
2390 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
2392 mono_loader_clear_error ();
2393 mono_loader_unlock ();
2394 mono_error_set_method_load (error, m->klass, m->name, "");
2398 if (can_cache_signature)
2399 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2401 signatures_size += mono_metadata_signature_size (signature);
2404 /* Verify metadata consistency */
2405 if (signature->generic_param_count) {
2406 if (!container || !container->is_method) {
2407 mono_loader_unlock ();
2408 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);
2411 if (container->type_argc != signature->generic_param_count) {
2412 mono_loader_unlock ();
2413 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);
2416 } else if (container && container->is_method && container->type_argc) {
2417 mono_loader_unlock ();
2418 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);
2421 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2422 signature->pinvoke = 1;
2423 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2424 MonoCallConvention conv = 0;
2425 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2426 signature->pinvoke = 1;
2428 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2429 case 0: /* no call conv, so using default */
2430 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2431 conv = MONO_CALL_DEFAULT;
2433 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2436 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2437 conv = MONO_CALL_STDCALL;
2439 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2440 conv = MONO_CALL_THISCALL;
2442 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2443 conv = MONO_CALL_FASTCALL;
2445 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2446 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2448 mono_loader_unlock ();
2449 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);
2452 signature->call_convention = conv;
2455 mono_memory_barrier ();
2456 m->signature = signature;
2458 mono_loader_unlock ();
2459 return m->signature;
2463 * mono_method_signature:
2465 * Return the signature of the method M. On failure, returns NULL.
2467 MonoMethodSignature*
2468 mono_method_signature (MonoMethod *m)
2471 MonoMethodSignature *sig;
2473 sig = mono_method_signature_checked (m, &error);
2475 char *type_name = mono_type_get_full_name (m->klass);
2476 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2478 mono_error_cleanup (&error);
2485 mono_method_get_name (MonoMethod *method)
2487 return method->name;
2491 mono_method_get_class (MonoMethod *method)
2493 return method->klass;
2497 mono_method_get_token (MonoMethod *method)
2499 return method->token;
2503 mono_method_get_header (MonoMethod *method)
2509 MonoMethodHeader *header;
2511 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))
2514 if (method->is_inflated) {
2515 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2516 MonoMethodHeader *header;
2518 mono_loader_lock ();
2520 if (imethod->header) {
2521 mono_loader_unlock ();
2522 return imethod->header;
2525 header = mono_method_get_header (imethod->declaring);
2527 mono_loader_unlock ();
2531 imethod->header = inflate_generic_header (header, mono_method_get_context (method));
2532 mono_loader_unlock ();
2533 mono_metadata_free_mh (header);
2534 return imethod->header;
2537 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2538 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2539 g_assert (mw->header);
2544 * We don't need locks here: the new header is allocated from malloc memory
2545 * and is not stored anywhere in the runtime, the user needs to free it.
2547 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2548 idx = mono_metadata_token_index (method->token);
2549 img = method->klass->image;
2550 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2552 if (!mono_verifier_verify_method_header (img, rva, NULL))
2555 loc = mono_image_rva_map (img, rva);
2559 header = mono_metadata_parse_mh_full (img, mono_method_get_generic_container (method), loc);
2565 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2568 *iflags = method->iflags;
2569 return method->flags;
2573 * Find the method index in the metadata methodDef table.
2576 mono_method_get_index (MonoMethod *method) {
2577 MonoClass *klass = method->klass;
2581 /* constructed array methods are not in the MethodDef table */
2585 return mono_metadata_token_index (method->token);
2587 mono_class_setup_methods (klass);
2588 if (klass->exception_type)
2590 for (i = 0; i < klass->method.count; ++i) {
2591 if (method == klass->methods [i]) {
2592 if (klass->image->uncompressed_metadata)
2593 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2595 return klass->method.first + i + 1;