2 * loader.c: Image Loader
5 * Paolo Molaro (lupus@ximian.com)
6 * Miguel de Icaza (miguel@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 * This file is used by the interpreter and the JIT engine to locate
14 * assemblies. Used to load AssemblyRef and later to resolve various
18 * This should keep track of the assembly versions that we are loading.
20 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
27 #include <mono/metadata/metadata.h>
28 #include <mono/metadata/image.h>
29 #include <mono/metadata/assembly.h>
30 #include <mono/metadata/tokentype.h>
31 #include <mono/metadata/tabledefs.h>
32 #include <mono/metadata/metadata-internals.h>
33 #include <mono/metadata/loader.h>
34 #include <mono/metadata/class-internals.h>
35 #include <mono/metadata/debug-helpers.h>
36 #include <mono/metadata/reflection.h>
37 #include <mono/metadata/profiler.h>
38 #include <mono/metadata/profiler-private.h>
39 #include <mono/metadata/exception.h>
40 #include <mono/metadata/marshal.h>
41 #include <mono/metadata/lock-tracer.h>
42 #include <mono/metadata/verify-internals.h>
43 #include <mono/utils/mono-logger-internals.h>
44 #include <mono/utils/mono-dl.h>
45 #include <mono/utils/mono-membar.h>
46 #include <mono/utils/mono-counters.h>
47 #include <mono/utils/mono-error-internals.h>
48 #include <mono/utils/mono-tls.h>
49 #include <mono/utils/mono-path.h>
51 MonoDefaults mono_defaults;
54 * This lock protects the hash tables inside MonoImage used by the metadata
55 * loading functions in class.c and loader.c.
57 * See domain-internals.h for locking policy in combination with the
60 static MonoCoopMutex loader_mutex;
61 static mono_mutex_t global_loader_data_mutex;
62 static gboolean loader_lock_inited;
65 static guint32 inflated_signatures_size;
66 static guint32 memberref_sig_cache_size;
67 static guint32 methods_size;
68 static guint32 signatures_size;
71 * This TLS variable holds how many times the current thread has acquired the loader
74 MonoNativeTlsKey loader_lock_nest_id;
76 static void dllmap_cleanup (void);
80 global_loader_data_lock (void)
82 mono_locks_os_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
86 global_loader_data_unlock (void)
88 mono_locks_os_release (&global_loader_data_mutex, LoaderGlobalDataLock);
94 static gboolean inited;
97 mono_coop_mutex_init_recursive (&loader_mutex);
98 mono_os_mutex_init_recursive (&global_loader_data_mutex);
99 loader_lock_inited = TRUE;
101 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
103 mono_counters_init ();
104 mono_counters_register ("Inflated signatures size",
105 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
106 mono_counters_register ("Memberref signature cache size",
107 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
108 mono_counters_register ("MonoMethod size",
109 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
110 mono_counters_register ("MonoMethodSignature size",
111 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
118 mono_loader_cleanup (void)
122 mono_native_tls_free (loader_lock_nest_id);
124 mono_coop_mutex_destroy (&loader_mutex);
125 mono_os_mutex_destroy (&global_loader_data_mutex);
126 loader_lock_inited = FALSE;
130 * find_cached_memberref_sig:
132 * Return a cached copy of the memberref signature identified by SIG_IDX.
133 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
134 * A cache is needed since the type/signature parsing routines allocate everything
135 * from a mempool, so without a cache, multiple requests for the same signature would
136 * lead to unbounded memory growth. For normal methods/fields this is not a problem
137 * since the resulting methods/fields are cached, but inflated methods/fields cannot
139 * LOCKING: Acquires the loader lock.
142 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
146 mono_image_lock (image);
147 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
148 mono_image_unlock (image);
154 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
158 mono_image_lock (image);
159 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
161 /* Somebody got in before us */
165 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
166 /* An approximation based on glib 2.18 */
167 memberref_sig_cache_size += sizeof (gpointer) * 4;
169 mono_image_unlock (image);
174 static MonoClassField*
175 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
176 MonoGenericContext *context, MonoError *error)
178 MonoClass *klass = NULL;
179 MonoClassField *field;
180 MonoTableInfo *tables = image->tables;
183 guint32 nindex, class_index;
186 guint32 idx = mono_metadata_token_index (token);
188 mono_error_init (error);
190 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
191 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
192 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
194 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
196 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
197 mono_error_set_bad_image (error, image, "Bad field '%u' signature 0x%08x", class_index, token);
201 switch (class_index) {
202 case MONO_MEMBERREF_PARENT_TYPEDEF:
203 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
205 case MONO_MEMBERREF_PARENT_TYPEREF:
206 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
208 case MONO_MEMBERREF_PARENT_TYPESPEC:
209 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
212 mono_error_set_bad_image (error, image, "Bad field field '%u' signature 0x%08x", class_index, token);
218 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
219 mono_metadata_decode_blob_size (ptr, &ptr);
220 /* we may want to check the signature here... */
223 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class_index, fname, token);
227 /* FIXME: This needs a cache, especially for generic instances, since
228 * we ask mono_metadata_parse_type_checked () to allocates everything from a mempool.
229 * FIXME part2, mono_metadata_parse_type_checked actually allows for a transient type instead.
230 * FIXME part3, transient types are not 100% transient, so we need to take care of that first.
232 sig_type = (MonoType *)find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
234 MonoError inner_error;
235 sig_type = mono_metadata_parse_type_checked (image, NULL, 0, FALSE, ptr, &ptr, &inner_error);
236 if (sig_type == NULL) {
237 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));
238 mono_error_cleanup (&inner_error);
241 sig_type = (MonoType *)cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
244 mono_class_init (klass); /*FIXME is this really necessary?*/
247 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
250 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
257 * mono_field_from_token:
258 * @deprecated use the _checked variant
259 * Notes: runtime code MUST not use this function
262 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
265 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
266 g_assert (mono_error_ok (&error));
271 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
275 MonoClassField *field;
277 mono_error_init (error);
279 if (image_is_dynamic (image)) {
280 MonoClassField *result;
281 MonoClass *handle_class;
284 MonoError inner_error;
285 result = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, &inner_error);
286 mono_error_cleanup (&inner_error);
287 // This checks the memberref type as well
288 if (!result || handle_class != mono_defaults.fieldhandle_class) {
289 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
292 *retklass = result->parent;
296 if ((field = (MonoClassField *)mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
297 *retklass = field->parent;
301 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
302 field = field_from_memberref (image, token, retklass, context, error);
304 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
306 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
309 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
316 field = mono_class_get_field (k, token);
318 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
322 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container) {
323 mono_image_lock (image);
324 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
325 mono_image_unlock (image);
332 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
336 if (sig1->hasthis != sig2->hasthis ||
337 sig1->sentinelpos != sig2->sentinelpos)
340 for (i = 0; i < sig1->sentinelpos; i++) {
341 MonoType *p1 = sig1->params[i];
342 MonoType *p2 = sig2->params[i];
344 /*if (p1->attrs != p2->attrs)
347 if (!mono_metadata_type_equal (p1, p2))
351 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
357 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
358 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
362 /* Search directly in the metadata to avoid calling setup_methods () */
363 mono_error_init (error);
365 /* FIXME: !from_class->generic_class condition causes test failures. */
366 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
367 for (i = 0; i < klass->method.count; ++i) {
368 guint32 cols [MONO_METHOD_SIZE];
371 MonoMethodSignature *other_sig;
373 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
375 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
377 if (!((fqname && !strcmp (m_name, fqname)) ||
378 (qname && !strcmp (m_name, qname)) ||
379 (name && !strcmp (m_name, name))))
382 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
383 if (!mono_error_ok (error)) //bail out if we hit a loader error
386 other_sig = mono_method_signature_checked (method, error);
387 if (!mono_error_ok (error)) //bail out if we hit a loader error
389 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
395 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
397 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
398 See mono/tests/generic-type-load-exception.2.il
399 FIXME we should better report this error to the caller
401 if (!klass->methods || mono_class_has_failure (klass)) {
402 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
406 for (i = 0; i < klass->method.count; ++i) {
407 MonoMethod *m = klass->methods [i];
408 MonoMethodSignature *msig;
410 /* We must cope with failing to load some of the types. */
414 if (!((fqname && !strcmp (m->name, fqname)) ||
415 (qname && !strcmp (m->name, qname)) ||
416 (name && !strcmp (m->name, name))))
418 msig = mono_method_signature_checked (m, error);
419 if (!mono_error_ok (error)) //bail out if we hit a loader error
425 if (sig->call_convention == MONO_CALL_VARARG) {
426 if (mono_metadata_signature_vararg_match (sig, msig))
429 if (mono_metadata_signature_equal (sig, msig))
434 if (i < klass->method.count)
435 return mono_class_get_method_by_index (from_class, i);
440 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
443 char *qname, *fqname, *class_name;
444 gboolean is_interface;
445 MonoMethod *result = NULL;
446 MonoClass *initial_class = in_class;
448 mono_error_init (error);
449 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
452 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
454 qname = g_strconcat (class_name, ".", name, NULL);
455 if (ic->name_space && ic->name_space [0])
456 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
460 class_name = qname = fqname = NULL;
463 g_assert (from_class);
464 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
465 if (result || !mono_error_ok (error))
468 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
472 * This happens when we fail to lazily load the interfaces of one of the types.
473 * On such case we can't just bail out since user code depends on us trying harder.
475 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
476 in_class = in_class->parent;
477 from_class = from_class->parent;
481 for (i = 0; i < in_class->interface_offsets_count; i++) {
482 MonoClass *in_ic = in_class->interfaces_packed [i];
483 MonoClass *from_ic = from_class->interfaces_packed [i];
484 char *ic_qname, *ic_fqname, *ic_class_name;
486 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
487 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
488 if (in_ic->name_space && in_ic->name_space [0])
489 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
493 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
494 g_free (ic_class_name);
497 if (result || !mono_error_ok (error))
501 in_class = in_class->parent;
502 from_class = from_class->parent;
504 g_assert (!in_class == !from_class);
507 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
509 //we did not find the method
510 if (!result && mono_error_ok (error)) {
511 char *desc = mono_signature_get_desc (sig, FALSE);
512 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
523 static MonoMethodSignature*
524 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
526 MonoMethodSignature *res;
530 mono_error_init (error);
534 res = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
535 res->param_count = sig->param_count;
536 res->sentinelpos = -1;
537 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
538 if (!mono_error_ok (error))
540 is_open = mono_class_is_open_constructed_type (res->ret);
541 for (i = 0; i < sig->param_count; ++i) {
542 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
543 if (!mono_error_ok (error))
547 is_open = mono_class_is_open_constructed_type (res->params [i]);
549 res->hasthis = sig->hasthis;
550 res->explicit_this = sig->explicit_this;
551 res->call_convention = sig->call_convention;
552 res->pinvoke = sig->pinvoke;
553 res->generic_param_count = sig->generic_param_count;
554 res->sentinelpos = sig->sentinelpos;
555 res->has_type_parameters = is_open;
556 res->is_inflated = 1;
561 mono_metadata_free_type (res->ret);
562 for (i = 0; i < sig->param_count; ++i) {
564 mono_metadata_free_type (res->params [i]);
571 * mono_inflate_generic_signature:
573 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
576 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
578 MonoMethodSignature *res, *cached;
580 res = inflate_generic_signature_checked (NULL, sig, context, error);
581 if (!mono_error_ok (error))
583 cached = mono_metadata_get_inflated_signature (res, context);
585 mono_metadata_free_inflated_signature (res);
589 static MonoMethodHeader*
590 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context, MonoError *error)
592 size_t locals_size = sizeof (gpointer) * header->num_locals;
593 size_t clauses_size = header->num_clauses * sizeof (MonoExceptionClause);
594 size_t header_size = MONO_SIZEOF_METHOD_HEADER + locals_size + clauses_size;
595 MonoMethodHeader *res = (MonoMethodHeader *)g_malloc0 (header_size);
596 res->num_locals = header->num_locals;
597 res->clauses = (MonoExceptionClause *) &res->locals [res->num_locals] ;
598 memcpy (res->clauses, header->clauses, clauses_size);
600 res->code = header->code;
601 res->code_size = header->code_size;
602 res->max_stack = header->max_stack;
603 res->num_clauses = header->num_clauses;
604 res->init_locals = header->init_locals;
606 res->is_transient = TRUE;
608 mono_error_init (error);
610 for (int i = 0; i < header->num_locals; ++i) {
611 res->locals [i] = mono_class_inflate_generic_type_checked (header->locals [i], context, error);
615 if (res->num_clauses) {
616 for (int i = 0; i < header->num_clauses; ++i) {
617 MonoExceptionClause *clause = &res->clauses [i];
618 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
620 clause->data.catch_class = mono_class_inflate_generic_class_checked (clause->data.catch_class, context, error);
632 * token is the method_ref/def/spec token used in a call IL instruction.
633 * @deprecated use the _checked variant
634 * Notes: runtime code MUST not use this function
637 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
640 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
641 mono_error_cleanup (&error);
646 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
648 int table = mono_metadata_token_table (token);
649 int idx = mono_metadata_token_index (token);
651 guint32 cols [MONO_MEMBERREF_SIZE];
652 MonoMethodSignature *sig;
655 mono_error_init (error);
657 /* !table is for wrappers: we should really assign their own token to them */
658 if (!table || table == MONO_TABLE_METHOD)
659 return mono_method_signature_checked (method, error);
661 if (table == MONO_TABLE_METHODSPEC) {
662 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
663 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated) {
664 mono_error_set_bad_image (error, image, "Method is a pinvoke or open generic");
668 return mono_method_signature_checked (method, error);
671 if (method->klass->generic_class)
672 return mono_method_signature_checked (method, error);
674 if (image_is_dynamic (image)) {
675 sig = mono_reflection_lookup_signature (image, method, token, error);
679 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
680 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
682 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
684 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
685 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
686 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
688 //FIXME include the verification error
689 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
693 ptr = mono_metadata_blob_heap (image, sig_idx);
694 mono_metadata_decode_blob_size (ptr, &ptr);
696 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
700 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
702 /* FIXME: we probably should verify signature compat in the dynamic case too*/
703 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
704 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
705 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
707 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
713 MonoMethodSignature *cached;
715 /* This signature is not owned by a MonoMethod, so need to cache */
716 sig = inflate_generic_signature_checked (image, sig, context, error);
717 if (!mono_error_ok (error))
720 cached = mono_metadata_get_inflated_signature (sig, context);
722 mono_metadata_free_inflated_signature (sig);
724 inflated_signatures_size += mono_metadata_signature_size (cached);
728 g_assert (mono_error_ok (error));
733 * token is the method_ref/def/spec token used in a call IL instruction.
734 * @deprecated use the _checked variant
735 * Notes: runtime code MUST not use this function
738 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
741 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
742 mono_error_cleanup (&error);
746 /* this is only for the typespec array methods */
748 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
752 mono_class_setup_methods (klass);
753 g_assert (!mono_class_has_failure (klass)); /*FIXME this should not fail, right?*/
754 for (i = 0; i < klass->method.count; ++i) {
755 MonoMethod *method = klass->methods [i];
756 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
763 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
764 gboolean *used_context, MonoError *error)
766 MonoClass *klass = NULL;
767 MonoMethod *method = NULL;
768 MonoTableInfo *tables = image->tables;
770 guint32 nindex, class_index, sig_idx;
772 MonoMethodSignature *sig;
775 mono_error_init (error);
777 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
778 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
779 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
780 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
781 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
783 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
786 * Whether we actually used the `typespec_context' or not.
787 * This is used to tell our caller whether or not it's safe to insert the returned
788 * method into a cache.
791 *used_context = class_index == MONO_MEMBERREF_PARENT_TYPESPEC;
793 switch (class_index) {
794 case MONO_MEMBERREF_PARENT_TYPEREF:
795 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
799 case MONO_MEMBERREF_PARENT_TYPESPEC:
801 * Parse the TYPESPEC in the parent's context.
803 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
807 case MONO_MEMBERREF_PARENT_TYPEDEF:
808 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
812 case MONO_MEMBERREF_PARENT_METHODDEF: {
813 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
819 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class_index, nindex);
824 mono_class_init (klass);
826 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
828 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
829 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
833 ptr = mono_metadata_blob_heap (image, sig_idx);
834 mono_metadata_decode_blob_size (ptr, &ptr);
836 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
838 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
842 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
845 switch (class_index) {
846 case MONO_MEMBERREF_PARENT_TYPEREF:
847 case MONO_MEMBERREF_PARENT_TYPEDEF:
848 method = find_method (klass, NULL, mname, sig, klass, error);
851 case MONO_MEMBERREF_PARENT_TYPESPEC: {
854 type = &klass->byval_arg;
856 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
857 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
858 method = find_method (in_class, NULL, mname, sig, klass, error);
862 /* we're an array and we created these methods already in klass in mono_class_init () */
863 method = mono_method_search_in_array_class (klass, mname, sig);
867 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class_index, nindex);
871 if (!method && mono_error_ok (error)) {
872 char *msig = mono_signature_get_desc (sig, FALSE);
873 GString *s = g_string_new (mname);
874 if (sig->generic_param_count)
875 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
876 g_string_append_printf (s, "(%s)", msig);
878 msig = g_string_free (s, FALSE);
880 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
888 g_assert (!mono_error_ok (error));
893 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
897 MonoTableInfo *tables = image->tables;
898 MonoGenericContext new_context;
899 MonoGenericInst *inst;
901 guint32 cols [MONO_METHODSPEC_SIZE];
902 guint32 token, nindex, param_count;
904 mono_error_init (error);
906 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
907 token = cols [MONO_METHODSPEC_METHOD];
908 nindex = token >> MONO_METHODDEFORREF_BITS;
910 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
911 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
915 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
917 mono_metadata_decode_value (ptr, &ptr);
919 param_count = mono_metadata_decode_value (ptr, &ptr);
921 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr, error);
925 if (context && inst->is_open) {
926 inst = mono_metadata_inflate_generic_inst (inst, context, error);
927 if (!mono_error_ok (error))
931 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
932 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
936 method = method_from_memberref (image, nindex, context, NULL, error);
942 klass = method->klass;
944 if (klass->generic_class) {
945 g_assert (method->is_inflated);
946 method = ((MonoMethodInflated *) method)->declaring;
949 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
950 new_context.method_inst = inst;
952 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
964 static MonoDllMap *global_dll_map;
967 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
975 global_loader_data_lock ();
978 * we use the first entry we find that matches, since entries from
979 * the config file are prepended to the list and we document that the
982 for (; dll_map; dll_map = dll_map->next) {
983 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
984 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
986 } else if (strcmp (dll_map->dll, dll)) {
989 if (!found && dll_map->target) {
990 *rdll = dll_map->target;
992 /* we don't quit here, because we could find a full
993 * entry that matches also function and that has priority.
996 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
997 *rdll = dll_map->target;
998 *rfunc = dll_map->target_func;
1003 global_loader_data_unlock ();
1008 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1011 if (assembly && assembly->dll_map) {
1012 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1016 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1020 * mono_dllmap_insert:
1021 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1022 * @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
1023 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1024 * @tdll: The name of the library to map the specified @dll if it matches.
1025 * @tfunc: The name of the function that replaces the invocation. If NULL, it is replaced with a copy of @func.
1027 * LOCKING: Acquires the loader lock.
1029 * This function is used to programatically add DllImport remapping in either
1030 * a specific assembly, or as a global remapping. This is done by remapping
1031 * references in a DllImport attribute from the @dll library name into the @tdll
1032 * name. If the @dll name contains the prefix "i:", the comparison of the
1033 * library name is done without case sensitivity.
1035 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1036 * or the name of the function as determined by DllImport. If you pass @func, you
1037 * must also pass @tfunc which is the name of the target function to invoke on a match.
1040 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1042 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1043 * the contents of relocated_demo_path for all assemblies in the Mono process.
1045 * NOTE: This can be called before the runtime is initialized, for example from
1046 * mono_config_parse ().
1049 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1053 mono_loader_init ();
1056 entry = (MonoDllMap *)g_malloc0 (sizeof (MonoDllMap));
1057 entry->dll = dll? g_strdup (dll): NULL;
1058 entry->target = tdll? g_strdup (tdll): NULL;
1059 entry->func = func? g_strdup (func): NULL;
1060 entry->target_func = tfunc? g_strdup (tfunc): (func? g_strdup (func): NULL);
1062 global_loader_data_lock ();
1063 entry->next = global_dll_map;
1064 global_dll_map = entry;
1065 global_loader_data_unlock ();
1067 entry = (MonoDllMap *)mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1068 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1069 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1070 entry->func = func? mono_image_strdup (assembly, func): NULL;
1071 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): (func? mono_image_strdup (assembly, func): NULL);
1073 mono_image_lock (assembly);
1074 entry->next = assembly->dll_map;
1075 assembly->dll_map = entry;
1076 mono_image_unlock (assembly);
1081 free_dllmap (MonoDllMap *map)
1084 MonoDllMap *next = map->next;
1087 g_free (map->target);
1089 g_free (map->target_func);
1096 dllmap_cleanup (void)
1098 free_dllmap (global_dll_map);
1099 global_dll_map = NULL;
1102 static GHashTable *global_module_map;
1105 cached_module_load (const char *name, int flags, char **err)
1111 global_loader_data_lock ();
1112 if (!global_module_map)
1113 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1114 res = (MonoDl *)g_hash_table_lookup (global_module_map, name);
1116 global_loader_data_unlock ();
1119 res = mono_dl_open (name, flags, err);
1121 g_hash_table_insert (global_module_map, g_strdup (name), res);
1122 global_loader_data_unlock ();
1127 mono_loader_register_module (const char *name, MonoDl *module)
1129 if (!global_module_map)
1130 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1131 g_hash_table_insert (global_module_map, g_strdup (name), module);
1134 static MonoDl *internal_module;
1137 is_absolute_path (const char *path)
1139 #ifdef PLATFORM_MACOSX
1140 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1141 !strncmp (path, "@rpath/", 7))
1144 return g_path_is_absolute (path);
1148 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1150 MonoImage *image = method->klass->image;
1151 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1152 MonoTableInfo *tables = image->tables;
1153 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1154 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1155 guint32 im_cols [MONO_IMPLMAP_SIZE];
1156 guint32 scope_token;
1157 const char *import = NULL;
1158 const char *orig_scope;
1159 const char *new_scope;
1161 char *full_name, *file_name, *found_name = NULL;
1163 MonoDl *module = NULL;
1164 gboolean cached = FALSE;
1166 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1174 return piinfo->addr;
1176 if (image_is_dynamic (method->klass->image)) {
1177 MonoReflectionMethodAux *method_aux =
1178 (MonoReflectionMethodAux *)g_hash_table_lookup (
1179 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1183 import = method_aux->dllentry;
1184 orig_scope = method_aux->dll;
1187 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1190 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1192 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1195 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1196 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1197 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1198 orig_scope = mono_metadata_string_heap (image, scope_token);
1201 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1204 mono_image_lock (image);
1205 if (!image->pinvoke_scopes) {
1206 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1207 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1209 module = (MonoDl *)g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1210 found_name = (char *)g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1211 mono_image_unlock (image);
1215 found_name = g_strdup (found_name);
1219 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1220 "DllImport attempting to load: '%s'.", new_scope);
1222 /* we allow a special name to dlopen from the running process namespace */
1223 if (strcmp (new_scope, "__Internal") == 0){
1224 if (internal_module == NULL)
1225 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1226 module = internal_module;
1231 * Try loading the module using a variety of names
1233 for (i = 0; i < 5; ++i) {
1234 char *base_name = NULL, *dir_name = NULL;
1235 gboolean is_absolute = is_absolute_path (new_scope);
1239 /* Try the original name */
1240 file_name = g_strdup (new_scope);
1243 /* Try trimming the .dll extension */
1244 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1245 file_name = g_strdup (new_scope);
1246 file_name [strlen (new_scope) - 4] = '\0';
1253 dir_name = g_path_get_dirname (new_scope);
1254 base_name = g_path_get_basename (new_scope);
1255 if (strstr (base_name, "lib") != base_name) {
1256 char *tmp = g_strdup_printf ("lib%s", base_name);
1259 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1262 } else if (strstr (new_scope, "lib") != new_scope) {
1263 file_name = g_strdup_printf ("lib%s", new_scope);
1268 if (!is_absolute && mono_dl_get_system_dir ()) {
1269 dir_name = (char*)mono_dl_get_system_dir ();
1270 file_name = g_path_get_basename (new_scope);
1276 #ifndef TARGET_WIN32
1277 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1278 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1279 !g_ascii_strcasecmp ("user32", new_scope) ||
1280 !g_ascii_strcasecmp ("kernel", new_scope)) {
1281 file_name = g_strdup ("libMonoSupportW.so");
1285 #ifndef TARGET_WIN32
1292 dir_name = g_path_get_dirname (file_name);
1294 base_name = g_path_get_basename (file_name);
1297 if (!module && is_absolute) {
1298 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1300 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1301 "DllImport error loading library '%s': '%s'.",
1302 file_name, error_msg);
1305 found_name = g_strdup (file_name);
1309 if (!module && !is_absolute) {
1313 for (j = 0; j < 3; ++j) {
1318 mdirname = g_path_get_dirname (image->name);
1320 case 1: /* @executable_path@/../lib */
1324 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1326 char *base, *newbase;
1329 resolvedname = mono_path_resolve_symlinks (buf);
1331 base = g_path_get_dirname (resolvedname);
1332 newbase = g_path_get_dirname(base);
1333 mdirname = g_strdup_printf ("%s/lib", newbase);
1335 g_free (resolvedname);
1342 case 2: /* @executable_path@/../Libraries */
1346 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1348 char *base, *newbase;
1351 resolvedname = mono_path_resolve_symlinks (buf);
1353 base = g_path_get_dirname (resolvedname);
1354 newbase = g_path_get_dirname(base);
1355 mdirname = g_strdup_printf ("%s/Libraries", newbase);
1357 g_free (resolvedname);
1369 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1370 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1372 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1373 "DllImport error loading library '%s': '%s'.",
1374 full_name, error_msg);
1377 found_name = g_strdup (full_name);
1393 char *file_or_base = is_absolute ? base_name : file_name;
1394 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1395 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1397 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1398 "DllImport error loading library '%s': '%s'.",
1399 full_name, error_msg);
1402 found_name = g_strdup (full_name);
1411 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1413 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1414 "DllImport error loading library '%s': '%s'.",
1415 file_name, error_msg);
1417 found_name = g_strdup (file_name);
1432 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1433 "DllImport unable to load library '%s'.",
1438 *exc_class = "DllNotFoundException";
1439 *exc_arg = new_scope;
1445 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1446 "DllImport loaded library '%s'.", found_name);
1447 mono_image_lock (image);
1448 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1449 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1450 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1452 mono_image_unlock (image);
1455 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1456 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1457 g_free (found_name);
1460 if (import && import [0] == '#' && isdigit (import [1])) {
1464 id = strtol (import + 1, &end, 10);
1465 if (id > 0 && *end == '\0')
1469 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1470 "Searching for '%s'.", import);
1472 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1473 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1475 char *mangled_name = NULL, *mangled_name2 = NULL;
1478 int mangle_param_count;
1484 * Search using a variety of mangled names
1486 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1487 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1488 gboolean need_param_count = FALSE;
1490 if (mangle_stdcall > 0)
1491 need_param_count = TRUE;
1493 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1498 mangled_name = (char*)import;
1499 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1500 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1501 /* Try the mangled name first */
1502 if (mangle_charset == 0)
1503 mangled_name = g_strconcat (import, "W", NULL);
1505 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1507 if (mangle_charset == 0)
1508 mangled_name = g_strconcat (import, "W", NULL);
1510 /* Try the mangled name last */
1511 if (mangle_charset == 1)
1512 mangled_name = g_strconcat (import, "A", NULL);
1515 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1517 /* Try the mangled name last */
1518 if (mangle_charset == 1)
1519 mangled_name = g_strconcat (import, "A", NULL);
1524 if (mangle_param_count == 0)
1525 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1527 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1528 param_count = mangle_param_count;
1530 /* Try the stdcall mangled name */
1532 * gcc under windows creates mangled names without the underscore, but MS.NET
1533 * doesn't support it, so we doesn't support it either.
1535 if (mangle_stdcall == 1)
1536 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1538 mangled_name2 = mangled_name;
1540 mangled_name2 = mangled_name;
1543 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1544 "Probing '%s'.", mangled_name2);
1546 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1549 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1550 "Found as '%s'.", mangled_name2);
1552 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1553 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1558 if (mangled_name != mangled_name2)
1559 g_free (mangled_name2);
1560 if (mangled_name != import)
1561 g_free (mangled_name);
1567 if (!piinfo->addr) {
1570 *exc_class = "EntryPointNotFoundException";
1575 return piinfo->addr;
1579 * LOCKING: assumes the loader lock to be taken.
1582 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1583 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1586 int table = mono_metadata_token_table (token);
1587 int idx = mono_metadata_token_index (token);
1588 MonoTableInfo *tables = image->tables;
1589 MonoGenericContainer *generic_container = NULL, *container = NULL;
1590 const char *sig = NULL;
1591 guint32 cols [MONO_TYPEDEF_SIZE];
1593 mono_error_init (error);
1595 if (image_is_dynamic (image)) {
1596 MonoClass *handle_class;
1598 result = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, error);
1599 mono_error_assert_ok (error);
1601 // This checks the memberref type as well
1602 if (result && handle_class != mono_defaults.methodhandle_class) {
1603 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1609 if (table != MONO_TABLE_METHOD) {
1610 if (table == MONO_TABLE_METHODSPEC) {
1611 if (used_context) *used_context = TRUE;
1612 return method_from_methodspec (image, context, idx, error);
1614 if (table != MONO_TABLE_MEMBERREF) {
1615 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1618 return method_from_memberref (image, idx, context, used_context, error);
1621 if (used_context) *used_context = FALSE;
1623 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1624 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1629 guint32 type = mono_metadata_typedef_from_method (image, token);
1631 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1634 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1639 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1641 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1642 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1643 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1645 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1646 methods_size += sizeof (MonoMethod);
1649 mono_stats.method_count ++;
1652 result->klass = klass;
1653 result->flags = cols [2];
1654 result->iflags = cols [1];
1655 result->token = token;
1656 result->name = mono_metadata_string_heap (image, cols [3]);
1658 if (!sig) /* already taken from the methodref */
1659 sig = mono_metadata_blob_heap (image, cols [4]);
1660 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1662 container = klass->generic_container;
1665 * load_generic_params does a binary search so only call it if the method
1669 generic_container = mono_metadata_load_generic_params (image, token, container);
1671 if (generic_container) {
1672 result->is_generic = TRUE;
1673 generic_container->owner.method = result;
1674 generic_container->is_anonymous = FALSE; // Method is now known, container is no longer anonymous
1675 /*FIXME put this before the image alloc*/
1676 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1679 container = generic_container;
1682 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1683 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1684 result->string_ctor = 1;
1685 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1686 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1689 /* IJW is P/Invoke with a predefined function pointer. */
1690 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1691 piinfo->addr = mono_image_rva_map (image, cols [0]);
1692 g_assert (piinfo->addr);
1695 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1696 /* Native methods can have no map. */
1697 if (piinfo->implmap_idx)
1698 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1701 if (generic_container)
1702 mono_method_set_generic_container (result, generic_container);
1708 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1711 MonoMethod *result = mono_get_method_checked (image, token, klass, NULL, &error);
1712 mono_error_cleanup (&error);
1717 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1718 MonoGenericContext *context)
1721 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
1722 mono_error_cleanup (&error);
1727 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
1729 MonoMethod *result = NULL;
1730 gboolean used_context = FALSE;
1732 /* We do everything inside the lock to prevent creation races */
1734 mono_error_init (error);
1736 mono_image_lock (image);
1738 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1739 if (!image->method_cache)
1740 image->method_cache = g_hash_table_new (NULL, NULL);
1741 result = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1742 } else if (!image_is_dynamic (image)) {
1743 if (!image->methodref_cache)
1744 image->methodref_cache = g_hash_table_new (NULL, NULL);
1745 result = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1747 mono_image_unlock (image);
1753 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
1757 mono_image_lock (image);
1758 if (!used_context && !result->is_inflated) {
1759 MonoMethod *result2 = NULL;
1761 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1762 result2 = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1763 else if (!image_is_dynamic (image))
1764 result2 = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1767 mono_image_unlock (image);
1771 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1772 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1773 else if (!image_is_dynamic (image))
1774 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1777 mono_image_unlock (image);
1783 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
1786 MonoClass *ic = NULL;
1787 MonoGenericContext *method_context = NULL;
1788 MonoMethodSignature *sig, *original_sig;
1790 mono_error_init (error);
1792 mono_class_init (constrained_class);
1793 original_sig = sig = mono_method_signature_checked (method, error);
1798 if (method->is_inflated && sig->generic_param_count) {
1799 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1800 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1803 method_context = mono_method_get_context (method);
1807 * We must inflate the signature with the class instantiation to work on
1808 * cases where a class inherit from a generic type and the override replaces
1809 * any type argument which a concrete type. See #325283.
1811 if (method_context->class_inst) {
1812 MonoGenericContext ctx;
1813 ctx.method_inst = NULL;
1814 ctx.class_inst = method_context->class_inst;
1815 /*Fixme, property propagate this error*/
1816 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
1822 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1825 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
1826 if (sig != original_sig)
1827 mono_metadata_free_inflated_signature (sig);
1832 if (method_context) {
1833 result = mono_class_inflate_generic_method_checked (result, method_context, error);
1842 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
1843 MonoGenericContext *context, MonoError *error)
1847 return get_method_constrained (image, method, constrained_class, context, error);
1851 * mono_get_method_constrained:
1853 * This is used when JITing the `constrained.' opcode.
1855 * This returns two values: the contrained method, which has been inflated
1856 * as the function return value; And the original CIL-stream method as
1857 * declared in cil_method. The later is used for verification.
1860 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1861 MonoGenericContext *context, MonoMethod **cil_method)
1864 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
1865 mono_error_cleanup (&error);
1870 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
1872 mono_error_init (error);
1874 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
1878 return get_method_constrained (image, *cil_method, constrained_class, context, error);
1882 mono_free_method (MonoMethod *method)
1884 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1885 mono_profiler_method_free (method);
1887 /* FIXME: This hack will go away when the profiler will support freeing methods */
1888 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1891 if (method->signature) {
1893 * FIXME: This causes crashes because the types inside signatures and
1894 * locals are shared.
1896 /* mono_metadata_free_method_signature (method->signature); */
1897 /* g_free (method->signature); */
1900 if (method_is_dynamic (method)) {
1901 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1904 mono_marshal_free_dynamic_wrappers (method);
1906 mono_image_property_remove (method->klass->image, method);
1908 g_free ((char*)method->name);
1910 g_free ((char*)mw->header->code);
1911 for (i = 0; i < mw->header->num_locals; ++i)
1912 g_free (mw->header->locals [i]);
1913 g_free (mw->header->clauses);
1914 g_free (mw->header);
1916 g_free (mw->method_data);
1917 g_free (method->signature);
1923 mono_method_get_param_names (MonoMethod *method, const char **names)
1927 MonoTableInfo *methodt;
1928 MonoTableInfo *paramt;
1929 MonoMethodSignature *signature;
1932 if (method->is_inflated)
1933 method = ((MonoMethodInflated *) method)->declaring;
1935 signature = mono_method_signature (method);
1936 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
1937 number of arguments and allocate a properly sized array. */
1938 if (signature == NULL)
1941 if (!signature->param_count)
1944 for (i = 0; i < signature->param_count; ++i)
1947 klass = method->klass;
1951 mono_class_init (klass);
1953 if (image_is_dynamic (klass->image)) {
1954 MonoReflectionMethodAux *method_aux =
1955 (MonoReflectionMethodAux *)g_hash_table_lookup (
1956 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1957 if (method_aux && method_aux->param_names) {
1958 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1959 if (method_aux->param_names [i + 1])
1960 names [i] = method_aux->param_names [i + 1];
1965 if (method->wrapper_type) {
1966 char **pnames = NULL;
1968 mono_image_lock (klass->image);
1969 if (klass->image->wrapper_param_names)
1970 pnames = (char **)g_hash_table_lookup (klass->image->wrapper_param_names, method);
1971 mono_image_unlock (klass->image);
1974 for (i = 0; i < signature->param_count; ++i)
1975 names [i] = pnames [i];
1980 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1981 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1982 idx = mono_method_get_index (method);
1984 guint32 cols [MONO_PARAM_SIZE];
1987 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1989 if (idx < methodt->rows)
1990 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1992 lastp = paramt->rows + 1;
1993 for (i = param_index; i < lastp; ++i) {
1994 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1995 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
1996 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2002 mono_method_get_param_token (MonoMethod *method, int index)
2004 MonoClass *klass = method->klass;
2005 MonoTableInfo *methodt;
2008 mono_class_init (klass);
2010 if (image_is_dynamic (klass->image))
2011 g_assert_not_reached ();
2013 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2014 idx = mono_method_get_index (method);
2016 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2020 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2022 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2029 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2032 MonoClass *klass = method->klass;
2033 MonoTableInfo *methodt;
2034 MonoTableInfo *paramt;
2035 MonoMethodSignature *signature;
2038 signature = mono_method_signature (method);
2039 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2041 for (i = 0; i < signature->param_count + 1; ++i)
2044 if (image_is_dynamic (method->klass->image)) {
2045 MonoReflectionMethodAux *method_aux =
2046 (MonoReflectionMethodAux *)g_hash_table_lookup (
2047 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2048 if (method_aux && method_aux->param_marshall) {
2049 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2050 for (i = 0; i < signature->param_count + 1; ++i)
2051 if (dyn_specs [i]) {
2052 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2053 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2054 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2055 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2061 mono_class_init (klass);
2063 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2064 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2065 idx = mono_method_get_index (method);
2067 guint32 cols [MONO_PARAM_SIZE];
2068 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2070 if (idx < methodt->rows)
2071 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2073 lastp = paramt->rows + 1;
2075 for (i = param_index; i < lastp; ++i) {
2076 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2078 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2080 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2082 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2091 mono_method_has_marshal_info (MonoMethod *method)
2094 MonoClass *klass = method->klass;
2095 MonoTableInfo *methodt;
2096 MonoTableInfo *paramt;
2099 if (image_is_dynamic (method->klass->image)) {
2100 MonoReflectionMethodAux *method_aux =
2101 (MonoReflectionMethodAux *)g_hash_table_lookup (
2102 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2103 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2105 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2112 mono_class_init (klass);
2114 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2115 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2116 idx = mono_method_get_index (method);
2118 guint32 cols [MONO_PARAM_SIZE];
2119 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2121 if (idx + 1 < methodt->rows)
2122 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2124 lastp = paramt->rows + 1;
2126 for (i = param_index; i < lastp; ++i) {
2127 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2129 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2138 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2141 g_assert (method != NULL);
2142 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2144 data = (void **)((MonoMethodWrapper *)method)->method_data;
2145 g_assert (data != NULL);
2146 g_assert (id <= GPOINTER_TO_UINT (*data));
2153 } StackWalkUserData;
2156 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2158 StackWalkUserData *d = (StackWalkUserData *)data;
2160 switch (frame->type) {
2161 case FRAME_TYPE_DEBUGGER_INVOKE:
2162 case FRAME_TYPE_MANAGED_TO_NATIVE:
2163 case FRAME_TYPE_TRAMPOLINE:
2165 case FRAME_TYPE_MANAGED:
2166 g_assert (frame->ji);
2167 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2170 g_assert_not_reached ();
2176 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2178 StackWalkUserData ud = { func, user_data };
2179 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2183 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2185 StackWalkUserData ud = { func, user_data };
2186 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2190 MonoStackWalkAsyncSafe func;
2192 } AsyncStackWalkUserData;
2196 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2198 AsyncStackWalkUserData *d = (AsyncStackWalkUserData *)data;
2200 switch (frame->type) {
2201 case FRAME_TYPE_DEBUGGER_INVOKE:
2202 case FRAME_TYPE_MANAGED_TO_NATIVE:
2203 case FRAME_TYPE_TRAMPOLINE:
2205 case FRAME_TYPE_MANAGED:
2208 if (frame->ji->async) {
2209 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2211 return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2215 g_assert_not_reached ();
2222 * mono_stack_walk_async_safe:
2224 * Async safe version callable from signal handlers.
2227 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2230 AsyncStackWalkUserData ud = { func, user_data };
2232 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2233 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, &ctx, MONO_UNWIND_SIGNAL_SAFE, &ud);
2237 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2239 MonoMethod **dest = (MonoMethod **)data;
2241 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2247 mono_method_get_last_managed (void)
2249 MonoMethod *m = NULL;
2250 mono_stack_walk_no_il (last_managed, &m);
2254 static gboolean loader_lock_track_ownership = FALSE;
2259 * See docs/thread-safety.txt for the locking strategy.
2262 mono_loader_lock (void)
2264 mono_locks_coop_acquire (&loader_mutex, LoaderLock);
2265 if (G_UNLIKELY (loader_lock_track_ownership)) {
2266 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));
2271 mono_loader_unlock (void)
2273 mono_locks_coop_release (&loader_mutex, LoaderLock);
2274 if (G_UNLIKELY (loader_lock_track_ownership)) {
2275 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));
2280 * mono_loader_lock_track_ownership:
2282 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2283 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2284 * thread owns the loader lock.
2287 mono_loader_lock_track_ownership (gboolean track)
2289 loader_lock_track_ownership = track;
2293 * mono_loader_lock_is_owned_by_self:
2295 * Return whenever the current thread owns the loader lock.
2296 * This is useful to avoid blocking operations while holding the loader lock.
2299 mono_loader_lock_is_owned_by_self (void)
2301 g_assert (loader_lock_track_ownership);
2303 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2307 * mono_loader_lock_if_inited:
2309 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2310 * be used in runtime initialization code which can be executed before mono_loader_init ().
2313 mono_loader_lock_if_inited (void)
2315 if (loader_lock_inited)
2316 mono_loader_lock ();
2320 mono_loader_unlock_if_inited (void)
2322 if (loader_lock_inited)
2323 mono_loader_unlock ();
2327 * mono_method_signature:
2329 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2331 MonoMethodSignature*
2332 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2337 gboolean can_cache_signature;
2338 MonoGenericContainer *container;
2339 MonoMethodSignature *signature = NULL, *sig2;
2342 /* We need memory barriers below because of the double-checked locking pattern */
2344 mono_error_init (error);
2347 return m->signature;
2349 img = m->klass->image;
2351 if (m->is_inflated) {
2352 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2353 /* the lock is recursive */
2354 signature = mono_method_signature (imethod->declaring);
2355 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2356 if (!mono_error_ok (error))
2359 inflated_signatures_size += mono_metadata_signature_size (signature);
2361 mono_image_lock (img);
2363 mono_memory_barrier ();
2365 m->signature = signature;
2367 mono_image_unlock (img);
2369 return m->signature;
2372 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2373 idx = mono_metadata_token_index (m->token);
2375 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2377 g_assert (!m->klass->generic_class);
2378 container = mono_method_get_generic_container (m);
2380 container = m->klass->generic_container;
2382 /* Generic signatures depend on the container so they cannot be cached */
2383 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2384 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2386 /* If the method has parameter attributes, that can modify the signature */
2387 if (mono_metadata_method_has_param_attrs (img, idx))
2388 can_cache_signature = FALSE;
2390 if (can_cache_signature) {
2391 mono_image_lock (img);
2392 signature = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2393 mono_image_unlock (img);
2397 const char *sig_body;
2398 /*TODO we should cache the failure result somewhere*/
2399 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2402 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2404 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2408 if (can_cache_signature) {
2409 mono_image_lock (img);
2410 sig2 = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2412 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2413 mono_image_unlock (img);
2416 signatures_size += mono_metadata_signature_size (signature);
2419 /* Verify metadata consistency */
2420 if (signature->generic_param_count) {
2421 if (!container || !container->is_method) {
2422 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);
2425 if (container->type_argc != signature->generic_param_count) {
2426 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);
2429 } else if (container && container->is_method && container->type_argc) {
2430 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);
2433 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2434 signature->pinvoke = 1;
2435 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2436 MonoCallConvention conv = (MonoCallConvention)0;
2437 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2438 signature->pinvoke = 1;
2440 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2441 case 0: /* no call conv, so using default */
2442 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2443 conv = MONO_CALL_DEFAULT;
2445 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2448 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2449 conv = MONO_CALL_STDCALL;
2451 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2452 conv = MONO_CALL_THISCALL;
2454 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2455 conv = MONO_CALL_FASTCALL;
2457 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2458 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2460 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);
2463 signature->call_convention = conv;
2466 mono_image_lock (img);
2468 mono_memory_barrier ();
2470 m->signature = signature;
2472 mono_image_unlock (img);
2474 return m->signature;
2478 * mono_method_signature:
2480 * Return the signature of the method M. On failure, returns NULL.
2482 MonoMethodSignature*
2483 mono_method_signature (MonoMethod *m)
2486 MonoMethodSignature *sig;
2488 sig = mono_method_signature_checked (m, &error);
2490 char *type_name = mono_type_get_full_name (m->klass);
2491 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2493 mono_error_cleanup (&error);
2500 mono_method_get_name (MonoMethod *method)
2502 return method->name;
2506 mono_method_get_class (MonoMethod *method)
2508 return method->klass;
2512 mono_method_get_token (MonoMethod *method)
2514 return method->token;
2518 mono_method_get_header_checked (MonoMethod *method, MonoError *error)
2524 MonoGenericContainer *container;
2526 mono_error_init (error);
2527 img = method->klass->image;
2529 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)) {
2530 mono_error_set_bad_image (error, img, "Method has no body");
2534 if (method->is_inflated) {
2535 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2536 MonoMethodHeader *header, *iheader;
2538 header = mono_method_get_header_checked (imethod->declaring, error);
2542 iheader = inflate_generic_header (header, mono_method_get_context (method), error);
2543 mono_metadata_free_mh (header);
2551 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2552 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2553 g_assert (mw->header);
2558 * We don't need locks here: the new header is allocated from malloc memory
2559 * and is not stored anywhere in the runtime, the user needs to free it.
2561 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2562 idx = mono_metadata_token_index (method->token);
2563 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2565 if (!mono_verifier_verify_method_header (img, rva, NULL)) {
2566 mono_error_set_bad_image (error, img, "Invalid method header, failed verification");
2570 loc = mono_image_rva_map (img, rva);
2572 mono_error_set_bad_image (error, img, "Method has zero rva");
2577 * When parsing the types of local variables, we must pass any container available
2578 * to ensure that both VAR and MVAR will get the right owner.
2580 container = mono_method_get_generic_container (method);
2582 container = method->klass->generic_container;
2583 return mono_metadata_parse_mh_full (img, container, (const char *)loc, error);
2587 mono_method_get_header (MonoMethod *method)
2590 MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
2591 mono_error_cleanup (&error);
2597 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2600 *iflags = method->iflags;
2601 return method->flags;
2605 * Find the method index in the metadata methodDef table.
2608 mono_method_get_index (MonoMethod *method)
2610 MonoClass *klass = method->klass;
2614 /* constructed array methods are not in the MethodDef table */
2618 return mono_metadata_token_index (method->token);
2620 mono_class_setup_methods (klass);
2621 if (mono_class_has_failure (klass))
2623 for (i = 0; i < klass->method.count; ++i) {
2624 if (method == klass->methods [i]) {
2625 if (klass->image->uncompressed_metadata)
2626 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2628 return klass->method.first + i + 1;