6 * Paolo Molaro (lupus@ximian.com)
7 * Miguel de Icaza (miguel@ximian.com)
8 * Patrik Torstensson (patrik.torstensson@labs2.com)
10 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
14 * This file is used by the interpreter and the JIT engine to locate
15 * assemblies. Used to load AssemblyRef and later to resolve various
19 * This should keep track of the assembly versions that we are loading.
21 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
28 #include <mono/metadata/metadata.h>
29 #include <mono/metadata/image.h>
30 #include <mono/metadata/assembly.h>
31 #include <mono/metadata/tokentype.h>
32 #include <mono/metadata/tabledefs.h>
33 #include <mono/metadata/metadata-internals.h>
34 #include <mono/metadata/loader.h>
35 #include <mono/metadata/class-internals.h>
36 #include <mono/metadata/debug-helpers.h>
37 #include <mono/metadata/reflection.h>
38 #include <mono/metadata/profiler.h>
39 #include <mono/metadata/profiler-private.h>
40 #include <mono/metadata/exception.h>
41 #include <mono/metadata/marshal.h>
42 #include <mono/metadata/lock-tracer.h>
43 #include <mono/metadata/verify-internals.h>
44 #include <mono/utils/mono-logger-internals.h>
45 #include <mono/utils/mono-dl.h>
46 #include <mono/utils/mono-membar.h>
47 #include <mono/utils/mono-counters.h>
48 #include <mono/utils/mono-error-internals.h>
49 #include <mono/utils/mono-tls.h>
50 #include <mono/utils/mono-path.h>
52 MonoDefaults mono_defaults;
55 * This lock protects the hash tables inside MonoImage used by the metadata
56 * loading functions in class.c and loader.c.
58 * See domain-internals.h for locking policy in combination with the
61 static MonoCoopMutex loader_mutex;
62 static mono_mutex_t global_loader_data_mutex;
63 static gboolean loader_lock_inited;
66 static guint32 inflated_signatures_size;
67 static guint32 memberref_sig_cache_size;
68 static guint32 methods_size;
69 static guint32 signatures_size;
72 * This TLS variable holds how many times the current thread has acquired the loader
75 MonoNativeTlsKey loader_lock_nest_id;
77 static void dllmap_cleanup (void);
81 global_loader_data_lock (void)
83 mono_locks_os_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
87 global_loader_data_unlock (void)
89 mono_locks_os_release (&global_loader_data_mutex, LoaderGlobalDataLock);
95 static gboolean inited;
98 mono_coop_mutex_init_recursive (&loader_mutex);
99 mono_os_mutex_init_recursive (&global_loader_data_mutex);
100 loader_lock_inited = TRUE;
102 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
104 mono_counters_init ();
105 mono_counters_register ("Inflated signatures size",
106 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
107 mono_counters_register ("Memberref signature cache size",
108 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
109 mono_counters_register ("MonoMethod size",
110 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
111 mono_counters_register ("MonoMethodSignature size",
112 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
119 mono_loader_cleanup (void)
123 mono_native_tls_free (loader_lock_nest_id);
125 mono_coop_mutex_destroy (&loader_mutex);
126 mono_os_mutex_destroy (&global_loader_data_mutex);
127 loader_lock_inited = FALSE;
131 * find_cached_memberref_sig:
133 * Return a cached copy of the memberref signature identified by SIG_IDX.
134 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
135 * A cache is needed since the type/signature parsing routines allocate everything
136 * from a mempool, so without a cache, multiple requests for the same signature would
137 * lead to unbounded memory growth. For normal methods/fields this is not a problem
138 * since the resulting methods/fields are cached, but inflated methods/fields cannot
140 * LOCKING: Acquires the loader lock.
143 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
147 mono_image_lock (image);
148 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
149 mono_image_unlock (image);
155 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
159 mono_image_lock (image);
160 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
162 /* Somebody got in before us */
166 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
167 /* An approximation based on glib 2.18 */
168 memberref_sig_cache_size += sizeof (gpointer) * 4;
170 mono_image_unlock (image);
175 static MonoClassField*
176 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
177 MonoGenericContext *context, MonoError *error)
179 MonoClass *klass = NULL;
180 MonoClassField *field;
181 MonoTableInfo *tables = image->tables;
184 guint32 nindex, class_index;
187 guint32 idx = mono_metadata_token_index (token);
191 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
192 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
193 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
195 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
197 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
198 mono_error_set_bad_image (error, image, "Bad field '%u' signature 0x%08x", class_index, token);
202 switch (class_index) {
203 case MONO_MEMBERREF_PARENT_TYPEDEF:
204 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
206 case MONO_MEMBERREF_PARENT_TYPEREF:
207 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
209 case MONO_MEMBERREF_PARENT_TYPESPEC:
210 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
213 mono_error_set_bad_image (error, image, "Bad field field '%u' signature 0x%08x", class_index, token);
219 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
220 mono_metadata_decode_blob_size (ptr, &ptr);
221 /* we may want to check the signature here... */
224 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class_index, fname, token);
228 /* FIXME: This needs a cache, especially for generic instances, since
229 * we ask mono_metadata_parse_type_checked () to allocates everything from a mempool.
230 * FIXME part2, mono_metadata_parse_type_checked actually allows for a transient type instead.
231 * FIXME part3, transient types are not 100% transient, so we need to take care of that first.
233 sig_type = (MonoType *)find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
235 MonoError inner_error;
236 sig_type = mono_metadata_parse_type_checked (image, NULL, 0, FALSE, ptr, &ptr, &inner_error);
237 if (sig_type == NULL) {
238 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));
239 mono_error_cleanup (&inner_error);
242 sig_type = (MonoType *)cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
245 mono_class_init (klass); /*FIXME is this really necessary?*/
248 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
251 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
258 * mono_field_from_token:
259 * @deprecated use the _checked variant
260 * Notes: runtime code MUST not use this function
263 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
266 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
267 g_assert (mono_error_ok (&error));
272 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
276 MonoClassField *field;
280 if (image_is_dynamic (image)) {
281 MonoClassField *result;
282 MonoClass *handle_class;
285 MonoError inner_error;
286 result = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, &inner_error);
287 mono_error_cleanup (&inner_error);
288 // This checks the memberref type as well
289 if (!result || handle_class != mono_defaults.fieldhandle_class) {
290 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
293 *retklass = result->parent;
297 if ((field = (MonoClassField *)mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
298 *retklass = field->parent;
302 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
303 field = field_from_memberref (image, token, retklass, context, error);
305 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
307 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
310 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
317 field = mono_class_get_field (k, token);
319 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
323 if (field && field->parent && !mono_class_is_ginst (field->parent) && !mono_class_is_gtd (field->parent)) {
324 mono_image_lock (image);
325 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
326 mono_image_unlock (image);
333 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
337 if (sig1->hasthis != sig2->hasthis ||
338 sig1->sentinelpos != sig2->sentinelpos)
341 for (i = 0; i < sig1->sentinelpos; i++) {
342 MonoType *p1 = sig1->params[i];
343 MonoType *p2 = sig2->params[i];
345 /*if (p1->attrs != p2->attrs)
348 if (!mono_metadata_type_equal (p1, p2))
352 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
358 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
359 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
363 /* Search directly in the metadata to avoid calling setup_methods () */
366 /* FIXME: !mono_class_is_ginst (from_class) condition causes test failures. */
367 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !mono_class_is_ginst (from_class)) {
368 int first_idx = mono_class_get_first_method_idx (klass);
369 int mcount = mono_class_get_method_count (klass);
370 for (i = 0; i < mcount; ++i) {
371 guint32 cols [MONO_METHOD_SIZE];
374 MonoMethodSignature *other_sig;
376 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, first_idx + i, cols, MONO_METHOD_SIZE);
378 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
380 if (!((fqname && !strcmp (m_name, fqname)) ||
381 (qname && !strcmp (m_name, qname)) ||
382 (name && !strcmp (m_name, name))))
385 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (first_idx + i + 1), klass, NULL, error);
386 if (!mono_error_ok (error)) //bail out if we hit a loader error
389 other_sig = mono_method_signature_checked (method, error);
390 if (!mono_error_ok (error)) //bail out if we hit a loader error
392 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
398 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
400 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
401 See mono/tests/generic-type-load-exception.2.il
402 FIXME we should better report this error to the caller
404 if (!klass->methods || mono_class_has_failure (klass)) {
405 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
409 int mcount = mono_class_get_method_count (klass);
410 for (i = 0; i < mcount; ++i) {
411 MonoMethod *m = klass->methods [i];
412 MonoMethodSignature *msig;
414 /* We must cope with failing to load some of the types. */
418 if (!((fqname && !strcmp (m->name, fqname)) ||
419 (qname && !strcmp (m->name, qname)) ||
420 (name && !strcmp (m->name, name))))
422 msig = mono_method_signature_checked (m, error);
423 if (!mono_error_ok (error)) //bail out if we hit a loader error
429 if (sig->call_convention == MONO_CALL_VARARG) {
430 if (mono_metadata_signature_vararg_match (sig, msig))
433 if (mono_metadata_signature_equal (sig, msig))
439 return mono_class_get_method_by_index (from_class, i);
444 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
447 char *qname, *fqname, *class_name;
448 gboolean is_interface;
449 MonoMethod *result = NULL;
450 MonoClass *initial_class = in_class;
453 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
456 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
458 qname = g_strconcat (class_name, ".", name, NULL);
459 if (ic->name_space && ic->name_space [0])
460 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
464 class_name = qname = fqname = NULL;
467 g_assert (from_class);
468 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
469 if (result || !mono_error_ok (error))
472 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
476 * This happens when we fail to lazily load the interfaces of one of the types.
477 * On such case we can't just bail out since user code depends on us trying harder.
479 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
480 in_class = in_class->parent;
481 from_class = from_class->parent;
485 for (i = 0; i < in_class->interface_offsets_count; i++) {
486 MonoClass *in_ic = in_class->interfaces_packed [i];
487 MonoClass *from_ic = from_class->interfaces_packed [i];
488 char *ic_qname, *ic_fqname, *ic_class_name;
490 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
491 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
492 if (in_ic->name_space && in_ic->name_space [0])
493 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
497 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
498 g_free (ic_class_name);
501 if (result || !mono_error_ok (error))
505 in_class = in_class->parent;
506 from_class = from_class->parent;
508 g_assert (!in_class == !from_class);
511 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
513 //we did not find the method
514 if (!result && mono_error_ok (error)) {
515 char *desc = mono_signature_get_desc (sig, FALSE);
516 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
527 static MonoMethodSignature*
528 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
530 MonoMethodSignature *res;
538 res = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
539 res->param_count = sig->param_count;
540 res->sentinelpos = -1;
541 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
542 if (!mono_error_ok (error))
544 is_open = mono_class_is_open_constructed_type (res->ret);
545 for (i = 0; i < sig->param_count; ++i) {
546 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
547 if (!mono_error_ok (error))
551 is_open = mono_class_is_open_constructed_type (res->params [i]);
553 res->hasthis = sig->hasthis;
554 res->explicit_this = sig->explicit_this;
555 res->call_convention = sig->call_convention;
556 res->pinvoke = sig->pinvoke;
557 res->generic_param_count = sig->generic_param_count;
558 res->sentinelpos = sig->sentinelpos;
559 res->has_type_parameters = is_open;
560 res->is_inflated = 1;
565 mono_metadata_free_type (res->ret);
566 for (i = 0; i < sig->param_count; ++i) {
568 mono_metadata_free_type (res->params [i]);
575 * mono_inflate_generic_signature:
577 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
580 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
582 MonoMethodSignature *res, *cached;
584 res = inflate_generic_signature_checked (NULL, sig, context, error);
585 if (!mono_error_ok (error))
587 cached = mono_metadata_get_inflated_signature (res, context);
589 mono_metadata_free_inflated_signature (res);
593 static MonoMethodHeader*
594 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context, MonoError *error)
596 size_t locals_size = sizeof (gpointer) * header->num_locals;
597 size_t clauses_size = header->num_clauses * sizeof (MonoExceptionClause);
598 size_t header_size = MONO_SIZEOF_METHOD_HEADER + locals_size + clauses_size;
599 MonoMethodHeader *res = (MonoMethodHeader *)g_malloc0 (header_size);
600 res->num_locals = header->num_locals;
601 res->clauses = (MonoExceptionClause *) &res->locals [res->num_locals] ;
602 memcpy (res->clauses, header->clauses, clauses_size);
604 res->code = header->code;
605 res->code_size = header->code_size;
606 res->max_stack = header->max_stack;
607 res->num_clauses = header->num_clauses;
608 res->init_locals = header->init_locals;
610 res->is_transient = TRUE;
614 for (int i = 0; i < header->num_locals; ++i) {
615 res->locals [i] = mono_class_inflate_generic_type_checked (header->locals [i], context, error);
619 if (res->num_clauses) {
620 for (int i = 0; i < header->num_clauses; ++i) {
621 MonoExceptionClause *clause = &res->clauses [i];
622 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
624 clause->data.catch_class = mono_class_inflate_generic_class_checked (clause->data.catch_class, context, error);
636 * mono_method_get_signature_full:
637 * \p token is the method ref/def/spec token used in a \c call IL instruction.
638 * \deprecated use the \c _checked variant
639 * Notes: runtime code MUST not use this function
642 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
645 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
646 mono_error_cleanup (&error);
651 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
653 int table = mono_metadata_token_table (token);
654 int idx = mono_metadata_token_index (token);
656 guint32 cols [MONO_MEMBERREF_SIZE];
657 MonoMethodSignature *sig;
662 /* !table is for wrappers: we should really assign their own token to them */
663 if (!table || table == MONO_TABLE_METHOD)
664 return mono_method_signature_checked (method, error);
666 if (table == MONO_TABLE_METHODSPEC) {
667 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
668 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated) {
669 mono_error_set_bad_image (error, image, "Method is a pinvoke or open generic");
673 return mono_method_signature_checked (method, error);
676 if (mono_class_is_ginst (method->klass))
677 return mono_method_signature_checked (method, error);
679 if (image_is_dynamic (image)) {
680 sig = mono_reflection_lookup_signature (image, method, token, error);
684 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
685 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
687 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
689 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
690 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
691 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
693 //FIXME include the verification error
694 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
698 ptr = mono_metadata_blob_heap (image, sig_idx);
699 mono_metadata_decode_blob_size (ptr, &ptr);
701 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
705 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
707 /* FIXME: we probably should verify signature compat in the dynamic case too*/
708 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
709 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
710 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
712 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
718 MonoMethodSignature *cached;
720 /* This signature is not owned by a MonoMethod, so need to cache */
721 sig = inflate_generic_signature_checked (image, sig, context, error);
722 if (!mono_error_ok (error))
725 cached = mono_metadata_get_inflated_signature (sig, context);
727 mono_metadata_free_inflated_signature (sig);
729 inflated_signatures_size += mono_metadata_signature_size (cached);
733 g_assert (mono_error_ok (error));
738 * mono_method_get_signature:
739 * \p token is the method_ref/def/spec token used in a call IL instruction.
740 * \deprecated use the \c _checked variant
741 * Notes: runtime code MUST not use this function
744 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
747 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
748 mono_error_cleanup (&error);
752 /* this is only for the typespec array methods */
754 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
758 mono_class_setup_methods (klass);
759 g_assert (!mono_class_has_failure (klass)); /*FIXME this should not fail, right?*/
760 int mcount = mono_class_get_method_count (klass);
761 for (i = 0; i < mcount; ++i) {
762 MonoMethod *method = klass->methods [i];
763 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
770 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
771 gboolean *used_context, MonoError *error)
773 MonoClass *klass = NULL;
774 MonoMethod *method = NULL;
775 MonoTableInfo *tables = image->tables;
777 guint32 nindex, class_index, sig_idx;
779 MonoMethodSignature *sig;
784 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
785 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
786 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
787 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
788 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
790 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
793 * Whether we actually used the `typespec_context' or not.
794 * This is used to tell our caller whether or not it's safe to insert the returned
795 * method into a cache.
798 *used_context = class_index == MONO_MEMBERREF_PARENT_TYPESPEC;
800 switch (class_index) {
801 case MONO_MEMBERREF_PARENT_TYPEREF:
802 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
806 case MONO_MEMBERREF_PARENT_TYPESPEC:
808 * Parse the TYPESPEC in the parent's context.
810 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
814 case MONO_MEMBERREF_PARENT_TYPEDEF:
815 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
819 case MONO_MEMBERREF_PARENT_METHODDEF: {
820 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
826 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class_index, nindex);
831 mono_class_init (klass);
833 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
835 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
836 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
840 ptr = mono_metadata_blob_heap (image, sig_idx);
841 mono_metadata_decode_blob_size (ptr, &ptr);
843 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
845 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
849 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
852 switch (class_index) {
853 case MONO_MEMBERREF_PARENT_TYPEREF:
854 case MONO_MEMBERREF_PARENT_TYPEDEF:
855 method = find_method (klass, NULL, mname, sig, klass, error);
858 case MONO_MEMBERREF_PARENT_TYPESPEC: {
861 type = &klass->byval_arg;
863 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
864 MonoClass *in_class = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->container_class : klass;
865 method = find_method (in_class, NULL, mname, sig, klass, error);
869 /* we're an array and we created these methods already in klass in mono_class_init () */
870 method = mono_method_search_in_array_class (klass, mname, sig);
874 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class_index, nindex);
878 if (!method && mono_error_ok (error)) {
879 char *msig = mono_signature_get_desc (sig, FALSE);
880 GString *s = g_string_new (mname);
881 if (sig->generic_param_count)
882 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
883 g_string_append_printf (s, "(%s)", msig);
885 msig = g_string_free (s, FALSE);
887 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
895 g_assert (!mono_error_ok (error));
900 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
904 MonoTableInfo *tables = image->tables;
905 MonoGenericContext new_context;
906 MonoGenericInst *inst;
908 guint32 cols [MONO_METHODSPEC_SIZE];
909 guint32 token, nindex, param_count;
913 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
914 token = cols [MONO_METHODSPEC_METHOD];
915 nindex = token >> MONO_METHODDEFORREF_BITS;
917 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
918 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
922 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
924 mono_metadata_decode_value (ptr, &ptr);
926 param_count = mono_metadata_decode_value (ptr, &ptr);
928 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr, error);
932 if (context && inst->is_open) {
933 inst = mono_metadata_inflate_generic_inst (inst, context, error);
934 if (!mono_error_ok (error))
938 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
939 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
943 method = method_from_memberref (image, nindex, context, NULL, error);
949 klass = method->klass;
951 if (mono_class_is_ginst (klass)) {
952 g_assert (method->is_inflated);
953 method = ((MonoMethodInflated *) method)->declaring;
956 new_context.class_inst = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->context.class_inst : NULL;
957 new_context.method_inst = inst;
959 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
971 static MonoDllMap *global_dll_map;
974 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
982 global_loader_data_lock ();
985 * we use the first entry we find that matches, since entries from
986 * the config file are prepended to the list and we document that the
989 for (; dll_map; dll_map = dll_map->next) {
990 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
991 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
993 } else if (strcmp (dll_map->dll, dll)) {
996 if (!found && dll_map->target) {
997 *rdll = dll_map->target;
999 /* we don't quit here, because we could find a full
1000 * entry that matches also function and that has priority.
1003 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1004 *rdll = dll_map->target;
1005 *rfunc = dll_map->target_func;
1010 global_loader_data_unlock ();
1015 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1018 if (assembly && assembly->dll_map) {
1019 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1023 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1027 * mono_dllmap_insert:
1028 * \param assembly if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1029 * \param 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
1030 * \param func if not null, the mapping will only applied to the named function (the value of EntryPoint)
1031 * \param tdll The name of the library to map the specified \p dll if it matches.
1032 * \param tfunc The name of the function that replaces the invocation. If NULL, it is replaced with a copy of \p func.
1034 * LOCKING: Acquires the loader lock.
1036 * This function is used to programatically add DllImport remapping in either
1037 * a specific assembly, or as a global remapping. This is done by remapping
1038 * references in a DllImport attribute from the \p dll library name into the \p tdll
1039 * name. If the \p dll name contains the prefix "i:", the comparison of the
1040 * library name is done without case sensitivity.
1042 * If you pass \p func, this is the name of the EntryPoint in a DllImport if specified
1043 * or the name of the function as determined by DllImport. If you pass \p func, you
1044 * must also pass \p tfunc which is the name of the target function to invoke on a match.
1047 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1049 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1050 * the contents of relocated_demo_path for all assemblies in the Mono process.
1052 * NOTE: This can be called before the runtime is initialized, for example from
1053 * mono_config_parse ().
1056 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1060 mono_loader_init ();
1063 entry = (MonoDllMap *)g_malloc0 (sizeof (MonoDllMap));
1064 entry->dll = dll? g_strdup (dll): NULL;
1065 entry->target = tdll? g_strdup (tdll): NULL;
1066 entry->func = func? g_strdup (func): NULL;
1067 entry->target_func = tfunc? g_strdup (tfunc): (func? g_strdup (func): NULL);
1069 global_loader_data_lock ();
1070 entry->next = global_dll_map;
1071 global_dll_map = entry;
1072 global_loader_data_unlock ();
1074 entry = (MonoDllMap *)mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1075 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1076 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1077 entry->func = func? mono_image_strdup (assembly, func): NULL;
1078 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): (func? mono_image_strdup (assembly, func): NULL);
1080 mono_image_lock (assembly);
1081 entry->next = assembly->dll_map;
1082 assembly->dll_map = entry;
1083 mono_image_unlock (assembly);
1088 free_dllmap (MonoDllMap *map)
1091 MonoDllMap *next = map->next;
1094 g_free (map->target);
1096 g_free (map->target_func);
1103 dllmap_cleanup (void)
1105 free_dllmap (global_dll_map);
1106 global_dll_map = NULL;
1109 static GHashTable *global_module_map;
1112 cached_module_load (const char *name, int flags, char **err)
1118 global_loader_data_lock ();
1119 if (!global_module_map)
1120 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1121 res = (MonoDl *)g_hash_table_lookup (global_module_map, name);
1123 global_loader_data_unlock ();
1126 res = mono_dl_open (name, flags, err);
1128 g_hash_table_insert (global_module_map, g_strdup (name), res);
1129 global_loader_data_unlock ();
1134 mono_loader_register_module (const char *name, MonoDl *module)
1136 if (!global_module_map)
1137 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1138 g_hash_table_insert (global_module_map, g_strdup (name), module);
1141 static MonoDl *internal_module;
1144 is_absolute_path (const char *path)
1146 #ifdef PLATFORM_MACOSX
1147 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1148 !strncmp (path, "@rpath/", 7))
1151 return g_path_is_absolute (path);
1155 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1157 MonoImage *image = method->klass->image;
1158 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1159 MonoTableInfo *tables = image->tables;
1160 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1161 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1162 guint32 im_cols [MONO_IMPLMAP_SIZE];
1163 guint32 scope_token;
1164 const char *import = NULL;
1165 const char *orig_scope;
1166 const char *new_scope;
1168 char *full_name, *file_name, *found_name = NULL;
1170 MonoDl *module = NULL;
1171 gboolean cached = FALSE;
1172 gpointer addr = NULL;
1174 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1182 return piinfo->addr;
1184 if (image_is_dynamic (method->klass->image)) {
1185 MonoReflectionMethodAux *method_aux =
1186 (MonoReflectionMethodAux *)g_hash_table_lookup (
1187 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1191 import = method_aux->dllentry;
1192 orig_scope = method_aux->dll;
1195 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1198 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1200 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1203 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1204 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1205 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1206 orig_scope = mono_metadata_string_heap (image, scope_token);
1209 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1212 mono_image_lock (image);
1213 if (!image->pinvoke_scopes) {
1214 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1215 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1217 module = (MonoDl *)g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1218 found_name = (char *)g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1219 mono_image_unlock (image);
1223 found_name = g_strdup (found_name);
1227 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1228 "DllImport attempting to load: '%s'.", new_scope);
1230 /* we allow a special name to dlopen from the running process namespace */
1231 if (strcmp (new_scope, "__Internal") == 0){
1232 if (internal_module == NULL)
1233 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1234 module = internal_module;
1239 * Try loading the module using a variety of names
1241 for (i = 0; i < 5; ++i) {
1242 char *base_name = NULL, *dir_name = NULL;
1243 gboolean is_absolute = is_absolute_path (new_scope);
1247 /* Try the original name */
1248 file_name = g_strdup (new_scope);
1251 /* Try trimming the .dll extension */
1252 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1253 file_name = g_strdup (new_scope);
1254 file_name [strlen (new_scope) - 4] = '\0';
1261 dir_name = g_path_get_dirname (new_scope);
1262 base_name = g_path_get_basename (new_scope);
1263 if (strstr (base_name, "lib") != base_name) {
1264 char *tmp = g_strdup_printf ("lib%s", base_name);
1267 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1270 } else if (strstr (new_scope, "lib") != new_scope) {
1271 file_name = g_strdup_printf ("lib%s", new_scope);
1276 if (!is_absolute && mono_dl_get_system_dir ()) {
1277 dir_name = (char*)mono_dl_get_system_dir ();
1278 file_name = g_path_get_basename (new_scope);
1284 #ifndef TARGET_WIN32
1285 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1286 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1287 !g_ascii_strcasecmp ("user32", new_scope) ||
1288 !g_ascii_strcasecmp ("kernel", new_scope)) {
1289 file_name = g_strdup ("libMonoSupportW.so");
1293 #ifndef TARGET_WIN32
1300 dir_name = g_path_get_dirname (file_name);
1302 base_name = g_path_get_basename (file_name);
1305 if (!module && is_absolute) {
1306 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1308 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1309 "DllImport error loading library '%s': '%s'.",
1310 file_name, error_msg);
1313 found_name = g_strdup (file_name);
1317 if (!module && !is_absolute) {
1321 for (j = 0; j < 3; ++j) {
1326 mdirname = g_path_get_dirname (image->name);
1328 case 1: /* @executable_path@/../lib */
1332 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1334 char *base, *newbase;
1337 resolvedname = mono_path_resolve_symlinks (buf);
1339 base = g_path_get_dirname (resolvedname);
1340 newbase = g_path_get_dirname(base);
1341 mdirname = g_strdup_printf ("%s/lib", newbase);
1343 g_free (resolvedname);
1350 case 2: /* @executable_path@/../Libraries */
1354 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1356 char *base, *newbase;
1359 resolvedname = mono_path_resolve_symlinks (buf);
1361 base = g_path_get_dirname (resolvedname);
1362 newbase = g_path_get_dirname(base);
1363 mdirname = g_strdup_printf ("%s/Libraries", newbase);
1365 g_free (resolvedname);
1377 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1378 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1380 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1381 "DllImport error loading library '%s': '%s'.",
1382 full_name, error_msg);
1385 found_name = g_strdup (full_name);
1401 char *file_or_base = is_absolute ? base_name : file_name;
1402 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1403 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1405 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1406 "DllImport error loading library '%s': '%s'.",
1407 full_name, error_msg);
1410 found_name = g_strdup (full_name);
1419 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1421 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1422 "DllImport error loading library '%s': '%s'.",
1423 file_name, error_msg);
1425 found_name = g_strdup (file_name);
1440 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1441 "DllImport unable to load library '%s'.",
1446 *exc_class = "DllNotFoundException";
1447 *exc_arg = new_scope;
1453 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1454 "DllImport loaded library '%s'.", found_name);
1455 mono_image_lock (image);
1456 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1457 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1458 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1460 mono_image_unlock (image);
1463 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1464 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1465 g_free (found_name);
1468 if (import && import [0] == '#' && isdigit (import [1])) {
1472 id = strtol (import + 1, &end, 10);
1473 if (id > 0 && *end == '\0')
1477 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1478 "Searching for '%s'.", import);
1480 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1481 error_msg = mono_dl_symbol (module, import, &addr);
1483 char *mangled_name = NULL, *mangled_name2 = NULL;
1486 int mangle_param_count;
1492 * Search using a variety of mangled names
1494 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1495 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1496 gboolean need_param_count = FALSE;
1498 if (mangle_stdcall > 0)
1499 need_param_count = TRUE;
1501 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1506 mangled_name = (char*)import;
1507 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1508 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1509 /* Try the mangled name first */
1510 if (mangle_charset == 0)
1511 mangled_name = g_strconcat (import, "W", NULL);
1513 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1515 if (mangle_charset == 0)
1516 mangled_name = g_strconcat (import, "W", NULL);
1518 /* Try the mangled name last */
1519 if (mangle_charset == 1)
1520 mangled_name = g_strconcat (import, "A", NULL);
1523 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1525 /* Try the mangled name last */
1526 if (mangle_charset == 1)
1527 mangled_name = g_strconcat (import, "A", NULL);
1532 if (mangle_param_count == 0)
1533 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1535 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1536 param_count = mangle_param_count;
1538 /* Try the stdcall mangled name */
1540 * gcc under windows creates mangled names without the underscore, but MS.NET
1541 * doesn't support it, so we doesn't support it either.
1543 if (mangle_stdcall == 1)
1544 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1546 mangled_name2 = mangled_name;
1548 mangled_name2 = mangled_name;
1551 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1552 "Probing '%s'.", mangled_name2);
1554 error_msg = mono_dl_symbol (module, mangled_name2, &addr);
1557 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1558 "Found as '%s'.", mangled_name2);
1560 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1561 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1566 if (mangled_name != mangled_name2)
1567 g_free (mangled_name2);
1568 if (mangled_name != import)
1569 g_free (mangled_name);
1578 *exc_class = "EntryPointNotFoundException";
1583 piinfo->addr = addr;
1588 * LOCKING: assumes the loader lock to be taken.
1591 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1592 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1595 int table = mono_metadata_token_table (token);
1596 int idx = mono_metadata_token_index (token);
1597 MonoTableInfo *tables = image->tables;
1598 MonoGenericContainer *generic_container = NULL, *container = NULL;
1599 const char *sig = NULL;
1600 guint32 cols [MONO_TYPEDEF_SIZE];
1604 if (image_is_dynamic (image)) {
1605 MonoClass *handle_class;
1607 result = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, error);
1608 mono_error_assert_ok (error);
1610 // This checks the memberref type as well
1611 if (result && handle_class != mono_defaults.methodhandle_class) {
1612 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1618 if (table != MONO_TABLE_METHOD) {
1619 if (table == MONO_TABLE_METHODSPEC) {
1620 if (used_context) *used_context = TRUE;
1621 return method_from_methodspec (image, context, idx, error);
1623 if (table != MONO_TABLE_MEMBERREF) {
1624 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1627 return method_from_memberref (image, idx, context, used_context, error);
1630 if (used_context) *used_context = FALSE;
1632 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1633 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1638 guint32 type = mono_metadata_typedef_from_method (image, token);
1640 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1643 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1648 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1650 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1651 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1652 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1654 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1655 methods_size += sizeof (MonoMethod);
1658 mono_stats.method_count ++;
1661 result->klass = klass;
1662 result->flags = cols [2];
1663 result->iflags = cols [1];
1664 result->token = token;
1665 result->name = mono_metadata_string_heap (image, cols [3]);
1667 if (!sig) /* already taken from the methodref */
1668 sig = mono_metadata_blob_heap (image, cols [4]);
1669 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1671 container = mono_class_try_get_generic_container (klass);
1674 * load_generic_params does a binary search so only call it if the method
1678 generic_container = mono_metadata_load_generic_params (image, token, container);
1680 if (generic_container) {
1681 result->is_generic = TRUE;
1682 generic_container->owner.method = result;
1683 generic_container->is_anonymous = FALSE; // Method is now known, container is no longer anonymous
1684 /*FIXME put this before the image alloc*/
1685 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1688 container = generic_container;
1691 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1692 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1693 result->string_ctor = 1;
1694 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1695 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1698 /* IJW is P/Invoke with a predefined function pointer. */
1699 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1700 piinfo->addr = mono_image_rva_map (image, cols [0]);
1701 g_assert (piinfo->addr);
1704 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1705 /* Native methods can have no map. */
1706 if (piinfo->implmap_idx)
1707 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1710 if (generic_container)
1711 mono_method_set_generic_container (result, generic_container);
1720 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1723 MonoMethod *result = mono_get_method_checked (image, token, klass, NULL, &error);
1724 mono_error_cleanup (&error);
1729 * mono_get_method_full:
1732 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1733 MonoGenericContext *context)
1736 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
1737 mono_error_cleanup (&error);
1742 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
1744 MonoMethod *result = NULL;
1745 gboolean used_context = FALSE;
1747 /* We do everything inside the lock to prevent creation races */
1751 mono_image_lock (image);
1753 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1754 if (!image->method_cache)
1755 image->method_cache = g_hash_table_new (NULL, NULL);
1756 result = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1757 } else if (!image_is_dynamic (image)) {
1758 if (!image->methodref_cache)
1759 image->methodref_cache = g_hash_table_new (NULL, NULL);
1760 result = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1762 mono_image_unlock (image);
1768 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
1772 mono_image_lock (image);
1773 if (!used_context && !result->is_inflated) {
1774 MonoMethod *result2 = NULL;
1776 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1777 result2 = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1778 else if (!image_is_dynamic (image))
1779 result2 = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1782 mono_image_unlock (image);
1786 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1787 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1788 else if (!image_is_dynamic (image))
1789 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1792 mono_image_unlock (image);
1798 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
1801 MonoClass *ic = NULL;
1802 MonoGenericContext *method_context = NULL;
1803 MonoMethodSignature *sig, *original_sig;
1807 mono_class_init (constrained_class);
1808 original_sig = sig = mono_method_signature_checked (method, error);
1813 if (method->is_inflated && sig->generic_param_count) {
1814 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1815 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1818 method_context = mono_method_get_context (method);
1822 * We must inflate the signature with the class instantiation to work on
1823 * cases where a class inherit from a generic type and the override replaces
1824 * any type argument which a concrete type. See #325283.
1826 if (method_context->class_inst) {
1827 MonoGenericContext ctx;
1828 ctx.method_inst = NULL;
1829 ctx.class_inst = method_context->class_inst;
1830 /*Fixme, property propagate this error*/
1831 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
1837 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1840 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
1841 if (sig != original_sig)
1842 mono_metadata_free_inflated_signature (sig);
1847 if (method_context) {
1848 result = mono_class_inflate_generic_method_checked (result, method_context, error);
1857 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
1858 MonoGenericContext *context, MonoError *error)
1862 return get_method_constrained (image, method, constrained_class, context, error);
1866 * mono_get_method_constrained:
1867 * This is used when JITing the <code>constrained.</code> opcode.
1868 * \returns The contrained method, which has been inflated
1869 * as the function return value; and the original CIL-stream method as
1870 * declared in \p cil_method. The latter is used for verification.
1873 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1874 MonoGenericContext *context, MonoMethod **cil_method)
1877 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
1878 mono_error_cleanup (&error);
1883 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
1887 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
1891 return get_method_constrained (image, *cil_method, constrained_class, context, error);
1895 mono_free_method (MonoMethod *method)
1897 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1898 mono_profiler_method_free (method);
1900 /* FIXME: This hack will go away when the profiler will support freeing methods */
1901 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1904 if (method->signature) {
1906 * FIXME: This causes crashes because the types inside signatures and
1907 * locals are shared.
1909 /* mono_metadata_free_method_signature (method->signature); */
1910 /* g_free (method->signature); */
1913 if (method_is_dynamic (method)) {
1914 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1917 mono_marshal_free_dynamic_wrappers (method);
1919 mono_image_property_remove (method->klass->image, method);
1921 g_free ((char*)method->name);
1923 g_free ((char*)mw->header->code);
1924 for (i = 0; i < mw->header->num_locals; ++i)
1925 g_free (mw->header->locals [i]);
1926 g_free (mw->header->clauses);
1927 g_free (mw->header);
1929 g_free (mw->method_data);
1930 g_free (method->signature);
1936 * mono_method_get_param_names:
1939 mono_method_get_param_names (MonoMethod *method, const char **names)
1943 MonoTableInfo *methodt;
1944 MonoTableInfo *paramt;
1945 MonoMethodSignature *signature;
1948 if (method->is_inflated)
1949 method = ((MonoMethodInflated *) method)->declaring;
1951 signature = mono_method_signature (method);
1952 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
1953 number of arguments and allocate a properly sized array. */
1954 if (signature == NULL)
1957 if (!signature->param_count)
1960 for (i = 0; i < signature->param_count; ++i)
1963 klass = method->klass;
1967 mono_class_init (klass);
1969 if (image_is_dynamic (klass->image)) {
1970 MonoReflectionMethodAux *method_aux =
1971 (MonoReflectionMethodAux *)g_hash_table_lookup (
1972 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1973 if (method_aux && method_aux->param_names) {
1974 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1975 if (method_aux->param_names [i + 1])
1976 names [i] = method_aux->param_names [i + 1];
1981 if (method->wrapper_type) {
1982 char **pnames = NULL;
1984 mono_image_lock (klass->image);
1985 if (klass->image->wrapper_param_names)
1986 pnames = (char **)g_hash_table_lookup (klass->image->wrapper_param_names, method);
1987 mono_image_unlock (klass->image);
1990 for (i = 0; i < signature->param_count; ++i)
1991 names [i] = pnames [i];
1996 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1997 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1998 idx = mono_method_get_index (method);
2000 guint32 cols [MONO_PARAM_SIZE];
2003 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2005 if (idx < methodt->rows)
2006 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2008 lastp = paramt->rows + 1;
2009 for (i = param_index; i < lastp; ++i) {
2010 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2011 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2012 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2018 * mono_method_get_param_token:
2021 mono_method_get_param_token (MonoMethod *method, int index)
2023 MonoClass *klass = method->klass;
2024 MonoTableInfo *methodt;
2027 mono_class_init (klass);
2029 if (image_is_dynamic (klass->image))
2030 g_assert_not_reached ();
2032 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2033 idx = mono_method_get_index (method);
2035 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2039 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2041 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2048 * mono_method_get_marshal_info:
2051 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2054 MonoClass *klass = method->klass;
2055 MonoTableInfo *methodt;
2056 MonoTableInfo *paramt;
2057 MonoMethodSignature *signature;
2060 signature = mono_method_signature (method);
2061 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2063 for (i = 0; i < signature->param_count + 1; ++i)
2066 if (image_is_dynamic (method->klass->image)) {
2067 MonoReflectionMethodAux *method_aux =
2068 (MonoReflectionMethodAux *)g_hash_table_lookup (
2069 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2070 if (method_aux && method_aux->param_marshall) {
2071 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2072 for (i = 0; i < signature->param_count + 1; ++i)
2073 if (dyn_specs [i]) {
2074 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2075 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2076 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2077 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2083 mono_class_init (klass);
2085 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2086 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2087 idx = mono_method_get_index (method);
2089 guint32 cols [MONO_PARAM_SIZE];
2090 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2092 if (idx < methodt->rows)
2093 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2095 lastp = paramt->rows + 1;
2097 for (i = param_index; i < lastp; ++i) {
2098 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2100 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2102 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2104 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2113 * mono_method_has_marshal_info:
2116 mono_method_has_marshal_info (MonoMethod *method)
2119 MonoClass *klass = method->klass;
2120 MonoTableInfo *methodt;
2121 MonoTableInfo *paramt;
2124 if (image_is_dynamic (method->klass->image)) {
2125 MonoReflectionMethodAux *method_aux =
2126 (MonoReflectionMethodAux *)g_hash_table_lookup (
2127 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2128 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2130 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2137 mono_class_init (klass);
2139 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2140 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2141 idx = mono_method_get_index (method);
2143 guint32 cols [MONO_PARAM_SIZE];
2144 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2146 if (idx + 1 < methodt->rows)
2147 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2149 lastp = paramt->rows + 1;
2151 for (i = param_index; i < lastp; ++i) {
2152 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2154 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2163 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2166 g_assert (method != NULL);
2167 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2169 data = (void **)((MonoMethodWrapper *)method)->method_data;
2170 g_assert (data != NULL);
2171 g_assert (id <= GPOINTER_TO_UINT (*data));
2178 } StackWalkUserData;
2181 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2183 StackWalkUserData *d = (StackWalkUserData *)data;
2185 switch (frame->type) {
2186 case FRAME_TYPE_DEBUGGER_INVOKE:
2187 case FRAME_TYPE_MANAGED_TO_NATIVE:
2188 case FRAME_TYPE_TRAMPOLINE:
2190 case FRAME_TYPE_MANAGED:
2191 g_assert (frame->ji);
2192 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2195 g_assert_not_reached ();
2201 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2203 StackWalkUserData ud = { func, user_data };
2204 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2208 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2210 StackWalkUserData ud = { func, user_data };
2211 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2215 MonoStackWalkAsyncSafe func;
2217 } AsyncStackWalkUserData;
2221 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2223 AsyncStackWalkUserData *d = (AsyncStackWalkUserData *)data;
2225 switch (frame->type) {
2226 case FRAME_TYPE_DEBUGGER_INVOKE:
2227 case FRAME_TYPE_MANAGED_TO_NATIVE:
2228 case FRAME_TYPE_TRAMPOLINE:
2230 case FRAME_TYPE_MANAGED:
2233 if (frame->ji->async) {
2234 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2236 return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2240 g_assert_not_reached ();
2247 * mono_stack_walk_async_safe:
2249 * Async safe version callable from signal handlers.
2252 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2255 AsyncStackWalkUserData ud = { func, user_data };
2257 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2258 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, &ctx, MONO_UNWIND_SIGNAL_SAFE, &ud);
2262 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2264 MonoMethod **dest = (MonoMethod **)data;
2266 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2272 * mono_method_get_last_managed:
2275 mono_method_get_last_managed (void)
2277 MonoMethod *m = NULL;
2278 mono_stack_walk_no_il (last_managed, &m);
2282 static gboolean loader_lock_track_ownership = FALSE;
2287 * See \c docs/thread-safety.txt for the locking strategy.
2290 mono_loader_lock (void)
2292 mono_locks_coop_acquire (&loader_mutex, LoaderLock);
2293 if (G_UNLIKELY (loader_lock_track_ownership)) {
2294 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));
2299 * mono_loader_unlock:
2302 mono_loader_unlock (void)
2304 mono_locks_coop_release (&loader_mutex, LoaderLock);
2305 if (G_UNLIKELY (loader_lock_track_ownership)) {
2306 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));
2311 * mono_loader_lock_track_ownership:
2313 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2314 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2315 * thread owns the loader lock.
2318 mono_loader_lock_track_ownership (gboolean track)
2320 loader_lock_track_ownership = track;
2324 * mono_loader_lock_is_owned_by_self:
2326 * Return whenever the current thread owns the loader lock.
2327 * This is useful to avoid blocking operations while holding the loader lock.
2330 mono_loader_lock_is_owned_by_self (void)
2332 g_assert (loader_lock_track_ownership);
2334 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2338 * mono_loader_lock_if_inited:
2340 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2341 * be used in runtime initialization code which can be executed before mono_loader_init ().
2344 mono_loader_lock_if_inited (void)
2346 if (loader_lock_inited)
2347 mono_loader_lock ();
2351 mono_loader_unlock_if_inited (void)
2353 if (loader_lock_inited)
2354 mono_loader_unlock ();
2358 * mono_method_signature_checked:
2360 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2362 MonoMethodSignature*
2363 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2368 gboolean can_cache_signature;
2369 MonoGenericContainer *container;
2370 MonoMethodSignature *signature = NULL, *sig2;
2373 /* We need memory barriers below because of the double-checked locking pattern */
2378 return m->signature;
2380 img = m->klass->image;
2382 if (m->is_inflated) {
2383 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2384 /* the lock is recursive */
2385 signature = mono_method_signature (imethod->declaring);
2386 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2387 if (!mono_error_ok (error))
2390 inflated_signatures_size += mono_metadata_signature_size (signature);
2392 mono_image_lock (img);
2394 mono_memory_barrier ();
2396 m->signature = signature;
2398 mono_image_unlock (img);
2400 return m->signature;
2403 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2404 idx = mono_metadata_token_index (m->token);
2406 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2408 g_assert (!mono_class_is_ginst (m->klass));
2409 container = mono_method_get_generic_container (m);
2411 container = mono_class_try_get_generic_container (m->klass);
2413 /* Generic signatures depend on the container so they cannot be cached */
2414 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2415 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2417 /* If the method has parameter attributes, that can modify the signature */
2418 if (mono_metadata_method_has_param_attrs (img, idx))
2419 can_cache_signature = FALSE;
2421 if (can_cache_signature) {
2422 mono_image_lock (img);
2423 signature = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2424 mono_image_unlock (img);
2428 const char *sig_body;
2429 /*TODO we should cache the failure result somewhere*/
2430 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2433 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2435 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2439 if (can_cache_signature) {
2440 mono_image_lock (img);
2441 sig2 = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2443 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2444 mono_image_unlock (img);
2447 signatures_size += mono_metadata_signature_size (signature);
2450 /* Verify metadata consistency */
2451 if (signature->generic_param_count) {
2452 if (!container || !container->is_method) {
2453 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);
2456 if (container->type_argc != signature->generic_param_count) {
2457 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);
2460 } else if (container && container->is_method && container->type_argc) {
2461 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);
2464 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
2465 signature->pinvoke = 1;
2468 * On Windows the default pinvoke calling convention is STDCALL but
2469 * we need CDECL since this is actually an icall.
2471 signature->call_convention = MONO_CALL_C;
2473 } else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2474 MonoCallConvention conv = (MonoCallConvention)0;
2475 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2476 signature->pinvoke = 1;
2478 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2479 case 0: /* no call conv, so using default */
2480 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2481 conv = MONO_CALL_DEFAULT;
2483 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2486 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2487 conv = MONO_CALL_STDCALL;
2489 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2490 conv = MONO_CALL_THISCALL;
2492 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2493 conv = MONO_CALL_FASTCALL;
2495 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2496 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2498 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);
2501 signature->call_convention = conv;
2504 mono_image_lock (img);
2506 mono_memory_barrier ();
2508 m->signature = signature;
2510 mono_image_unlock (img);
2512 return m->signature;
2516 * mono_method_signature:
2517 * \returns the signature of the method \p m. On failure, returns NULL.
2519 MonoMethodSignature*
2520 mono_method_signature (MonoMethod *m)
2523 MonoMethodSignature *sig;
2525 sig = mono_method_signature_checked (m, &error);
2527 char *type_name = mono_type_get_full_name (m->klass);
2528 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2530 mono_error_cleanup (&error);
2537 * mono_method_get_name:
2540 mono_method_get_name (MonoMethod *method)
2542 return method->name;
2546 * mono_method_get_class:
2549 mono_method_get_class (MonoMethod *method)
2551 return method->klass;
2555 * mono_method_get_token:
2558 mono_method_get_token (MonoMethod *method)
2560 return method->token;
2564 mono_method_get_header_checked (MonoMethod *method, MonoError *error)
2570 MonoGenericContainer *container;
2573 img = method->klass->image;
2575 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)) {
2576 mono_error_set_bad_image (error, img, "Method has no body");
2580 if (method->is_inflated) {
2581 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2582 MonoMethodHeader *header, *iheader;
2584 header = mono_method_get_header_checked (imethod->declaring, error);
2588 iheader = inflate_generic_header (header, mono_method_get_context (method), error);
2589 mono_metadata_free_mh (header);
2597 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2598 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2599 g_assert (mw->header);
2604 * We don't need locks here: the new header is allocated from malloc memory
2605 * and is not stored anywhere in the runtime, the user needs to free it.
2607 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2608 idx = mono_metadata_token_index (method->token);
2609 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2611 if (!mono_verifier_verify_method_header (img, rva, NULL)) {
2612 mono_error_set_bad_image (error, img, "Invalid method header, failed verification");
2616 loc = mono_image_rva_map (img, rva);
2618 mono_error_set_bad_image (error, img, "Method has zero rva");
2623 * When parsing the types of local variables, we must pass any container available
2624 * to ensure that both VAR and MVAR will get the right owner.
2626 container = mono_method_get_generic_container (method);
2628 container = mono_class_try_get_generic_container (method->klass);
2629 return mono_metadata_parse_mh_full (img, container, (const char *)loc, error);
2633 * mono_method_get_header:
2636 mono_method_get_header (MonoMethod *method)
2639 MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
2640 mono_error_cleanup (&error);
2646 * mono_method_get_flags:
2649 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2652 *iflags = method->iflags;
2653 return method->flags;
2657 * mono_method_get_index:
2658 * Find the method index in the metadata \c MethodDef table.
2661 mono_method_get_index (MonoMethod *method)
2663 MonoClass *klass = method->klass;
2667 /* constructed array methods are not in the MethodDef table */
2671 return mono_metadata_token_index (method->token);
2673 mono_class_setup_methods (klass);
2674 if (mono_class_has_failure (klass))
2676 int first_idx = mono_class_get_first_method_idx (klass);
2677 int mcount = mono_class_get_method_count (klass);
2678 for (i = 0; i < mcount; ++i) {
2679 if (method == klass->methods [i]) {
2680 if (klass->image->uncompressed_metadata)
2681 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, first_idx + i + 1);
2683 return first_idx + i + 1;