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)
12 * This file is used by the interpreter and the JIT engine to locate
13 * assemblies. Used to load AssemblyRef and later to resolve various
17 * This should keep track of the assembly versions that we are loading.
25 #include <mono/metadata/metadata.h>
26 #include <mono/metadata/image.h>
27 #include <mono/metadata/assembly.h>
28 #include <mono/metadata/tokentype.h>
29 #include <mono/metadata/tabledefs.h>
30 #include <mono/metadata/metadata-internals.h>
31 #include <mono/metadata/loader.h>
32 #include <mono/metadata/class-internals.h>
33 #include <mono/metadata/debug-helpers.h>
34 #include <mono/metadata/reflection.h>
35 #include <mono/metadata/profiler.h>
36 #include <mono/metadata/profiler-private.h>
37 #include <mono/metadata/exception.h>
38 #include <mono/metadata/marshal.h>
39 #include <mono/metadata/lock-tracer.h>
40 #include <mono/metadata/verify-internals.h>
41 #include <mono/utils/mono-logger.h>
42 #include <mono/utils/mono-dl.h>
43 #include <mono/utils/mono-membar.h>
44 #include <mono/utils/mono-counters.h>
46 MonoDefaults mono_defaults;
49 * This lock protects the hash tables inside MonoImage used by the metadata
50 * loading functions in class.c and loader.c.
52 * See domain-internals.h for locking policy in combination with the
55 static CRITICAL_SECTION loader_mutex;
58 static guint32 inflated_signatures_size;
59 static guint32 memberref_sig_cache_size;
62 * This TLS variable contains the last type load error encountered by the loader.
64 guint32 loader_error_thread_id;
67 * This TLS variable holds how many times the current thread has acquired the loader
70 guint32 loader_lock_nest_id;
75 static gboolean inited;
78 InitializeCriticalSection (&loader_mutex);
80 loader_error_thread_id = TlsAlloc ();
81 loader_lock_nest_id = TlsAlloc ();
83 mono_counters_register ("Inflated signatures size",
84 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
85 mono_counters_register ("Memberref signature cache size",
86 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
93 mono_loader_cleanup (void)
95 TlsFree (loader_error_thread_id);
96 TlsFree (loader_lock_nest_id);
98 /*DeleteCriticalSection (&loader_mutex);*/
102 * Handling of type load errors should be done as follows:
104 * If something could not be loaded, the loader should call one of the
105 * mono_loader_set_error_XXX functions ()
106 * with the appropriate arguments, then return NULL to report the failure. The error
107 * should be propagated until it reaches code which can throw managed exceptions. At that
108 * point, an exception should be thrown based on the information returned by
109 * mono_loader_get_last_error (). Then the error should be cleared by calling
110 * mono_loader_clear_error ().
114 set_loader_error (MonoLoaderError *error)
116 TlsSetValue (loader_error_thread_id, error);
120 * mono_loader_set_error_assembly_load:
122 * Set the loader error for this thread.
125 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
127 MonoLoaderError *error;
129 if (mono_loader_get_last_error ())
132 error = g_new0 (MonoLoaderError, 1);
133 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
134 error->assembly_name = g_strdup (assembly_name);
135 error->ref_only = ref_only;
138 * This is not strictly needed, but some (most) of the loader code still
139 * can't deal with load errors, and this message is more helpful than an
143 g_warning ("Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.", assembly_name);
145 g_warning ("Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
147 set_loader_error (error);
151 * mono_loader_set_error_type_load:
153 * Set the loader error for this thread.
156 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
158 MonoLoaderError *error;
160 if (mono_loader_get_last_error ())
163 error = g_new0 (MonoLoaderError, 1);
164 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
165 error->class_name = g_strdup (class_name);
166 error->assembly_name = g_strdup (assembly_name);
169 * This is not strictly needed, but some (most) of the loader code still
170 * can't deal with load errors, and this message is more helpful than an
173 g_warning ("The class %s could not be loaded, used in %s", class_name, assembly_name);
175 set_loader_error (error);
179 * mono_loader_set_error_method_load:
181 * Set the loader error for this thread. MEMBER_NAME should point to a string
185 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
187 MonoLoaderError *error;
189 /* FIXME: Store the signature as well */
190 if (mono_loader_get_last_error ())
193 error = g_new0 (MonoLoaderError, 1);
194 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
195 error->class_name = g_strdup (class_name);
196 error->member_name = member_name;
198 set_loader_error (error);
202 * mono_loader_set_error_field_load:
204 * Set the loader error for this thread. MEMBER_NAME should point to a string
208 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
210 MonoLoaderError *error;
212 /* FIXME: Store the signature as well */
213 if (mono_loader_get_last_error ())
216 error = g_new0 (MonoLoaderError, 1);
217 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
218 error->klass = klass;
219 error->member_name = member_name;
221 set_loader_error (error);
225 * mono_loader_set_error_bad_image:
227 * Set the loader error for this thread.
230 mono_loader_set_error_bad_image (char *msg)
232 MonoLoaderError *error;
234 if (mono_loader_get_last_error ())
237 error = g_new0 (MonoLoaderError, 1);
238 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
241 set_loader_error (error);
246 * mono_loader_get_last_error:
248 * Returns information about the last type load exception encountered by the loader, or
249 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
252 mono_loader_get_last_error (void)
254 return (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
258 * mono_loader_clear_error:
260 * Disposes any loader error messages on this thread
263 mono_loader_clear_error (void)
265 MonoLoaderError *ex = (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
268 g_free (ex->class_name);
269 g_free (ex->assembly_name);
273 TlsSetValue (loader_error_thread_id, NULL);
278 * mono_loader_error_prepare_exception:
279 * @error: The MonoLoaderError to turn into an exception
281 * This turns a MonoLoaderError into an exception that can be thrown
282 * and resets the Mono Loader Error state during this process.
286 mono_loader_error_prepare_exception (MonoLoaderError *error)
288 MonoException *ex = NULL;
290 switch (error->exception_type) {
291 case MONO_EXCEPTION_TYPE_LOAD: {
292 char *cname = g_strdup (error->class_name);
293 char *aname = g_strdup (error->assembly_name);
294 MonoString *class_name;
296 mono_loader_clear_error ();
298 class_name = mono_string_new (mono_domain_get (), cname);
300 ex = mono_get_exception_type_load (class_name, aname);
305 case MONO_EXCEPTION_MISSING_METHOD: {
306 char *cname = g_strdup (error->class_name);
307 char *aname = g_strdup (error->member_name);
309 mono_loader_clear_error ();
310 ex = mono_get_exception_missing_method (cname, aname);
316 case MONO_EXCEPTION_MISSING_FIELD: {
317 char *cnspace = g_strdup ((error->klass && *error->klass->name_space) ? error->klass->name_space : "");
318 char *cname = g_strdup (error->klass ? error->klass->name : "");
319 char *cmembername = g_strdup (error->member_name);
322 mono_loader_clear_error ();
323 class_name = g_strdup_printf ("%s%s%s", cnspace, cnspace ? "." : "", cname);
325 ex = mono_get_exception_missing_field (class_name, cmembername);
328 g_free (cmembername);
333 case MONO_EXCEPTION_FILE_NOT_FOUND: {
338 msg = g_strdup_printf ("Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.", error->assembly_name);
340 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
341 filename = g_strdup (error->assembly_name);
342 /* Has to call this before calling anything which might call mono_class_init () */
343 mono_loader_clear_error ();
344 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
350 case MONO_EXCEPTION_BAD_IMAGE: {
351 char *msg = g_strdup (error->msg);
352 mono_loader_clear_error ();
353 ex = mono_get_exception_bad_image_format (msg);
359 g_assert_not_reached ();
366 * find_cached_memberref_sig:
368 * Return a cached copy of the memberref signature identified by SIG_IDX.
369 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
370 * A cache is needed since the type/signature parsing routines allocate everything
371 * from a mempool, so without a cache, multiple requests for the same signature would
372 * lead to unbounded memory growth. For normal methods/fields this is not a problem
373 * since the resulting methods/fields are cached, but inflated methods/fields cannot
375 * LOCKING: Acquires the loader lock.
378 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
383 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
384 mono_loader_unlock ();
390 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
395 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
397 /* Somebody got in before us */
401 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
402 /* An approximation based on glib 2.18 */
403 memberref_sig_cache_size += sizeof (gpointer) * 4;
406 mono_loader_unlock ();
411 static MonoClassField*
412 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
413 MonoGenericContext *context)
416 MonoClassField *field;
417 MonoTableInfo *tables = image->tables;
420 guint32 nindex, class, class_table;
423 guint32 idx = mono_metadata_token_index (token);
425 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
426 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
427 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
429 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
431 if (!mono_verifier_verify_memberref_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
432 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
437 case MONO_MEMBERREF_PARENT_TYPEDEF:
438 class_table = MONO_TOKEN_TYPE_DEF;
439 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
441 case MONO_MEMBERREF_PARENT_TYPEREF:
442 class_table = MONO_TOKEN_TYPE_REF;
443 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
445 case MONO_MEMBERREF_PARENT_TYPESPEC:
446 class_table = MONO_TOKEN_TYPE_SPEC;
447 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
450 /*FIXME this must set a loader error!*/
451 g_warning ("field load from %x", class);
456 char *name = mono_class_name_from_token (image, class_table | nindex);
457 g_warning ("Missing field %s in class %s (type token %d)", fname, name, class_table | nindex);
458 mono_loader_set_error_type_load (name, image->assembly_name);
463 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
464 mono_metadata_decode_blob_size (ptr, &ptr);
465 /* we may want to check the signature here... */
468 g_warning ("Bad field signature class token %08x field name %s token %08x", class, fname, token);
469 mono_loader_set_error_field_load (klass, fname);
472 /* FIXME: This needs a cache, especially for generic instances, since
473 * mono_metadata_parse_type () allocates everything from a mempool.
475 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
477 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
478 if (sig_type == NULL) {
479 mono_loader_set_error_field_load (klass, fname);
482 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
485 mono_class_init (klass); /*FIXME is this really necessary?*/
488 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
491 mono_loader_set_error_field_load (klass, fname);
497 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
498 MonoGenericContext *context)
502 MonoClassField *field;
504 if (image->dynamic) {
505 MonoClassField *result;
506 MonoClass *handle_class;
509 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
510 // This checks the memberref type as well
511 if (!result || handle_class != mono_defaults.fieldhandle_class) {
512 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field token 0x%08x on image %s.", token, image->name));
515 *retklass = result->parent;
520 if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
521 *retklass = field->parent;
522 mono_loader_unlock ();
525 mono_loader_unlock ();
527 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
528 field = field_from_memberref (image, token, retklass, context);
530 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
533 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
539 field = mono_class_get_field (k, token);
543 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
544 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
545 mono_loader_unlock ();
550 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
554 if (sig1->hasthis != sig2->hasthis ||
555 sig1->sentinelpos != sig2->sentinelpos)
558 for (i = 0; i < sig1->sentinelpos; i++) {
559 MonoType *p1 = sig1->params[i];
560 MonoType *p2 = sig2->params[i];
562 /*if (p1->attrs != p2->attrs)
565 if (!mono_metadata_type_equal (p1, p2))
569 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
575 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
576 MonoMethodSignature *sig, MonoClass *from_class)
580 /* Search directly in the metadata to avoid calling setup_methods () */
582 /* FIXME: !from_class->generic_class condition causes test failures. */
583 if (klass->type_token && !klass->image->dynamic && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
584 for (i = 0; i < klass->method.count; ++i) {
585 guint32 cols [MONO_METHOD_SIZE];
588 MonoMethodSignature *other_sig;
590 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
592 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
594 if (!((fqname && !strcmp (m_name, fqname)) ||
595 (qname && !strcmp (m_name, qname)) ||
596 (name && !strcmp (m_name, name))))
599 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
600 other_sig = mono_method_signature (method);
601 if (method && other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
606 mono_class_setup_methods (klass);
608 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
609 See mono/tests/generic-type-load-exception.2.il
610 FIXME we should better report this error to the caller
614 for (i = 0; i < klass->method.count; ++i) {
615 MonoMethod *m = klass->methods [i];
616 MonoMethodSignature *msig;
618 if (!((fqname && !strcmp (m->name, fqname)) ||
619 (qname && !strcmp (m->name, qname)) ||
620 (name && !strcmp (m->name, name))))
622 msig = mono_method_signature (m);
626 if (sig->call_convention == MONO_CALL_VARARG) {
627 if (mono_metadata_signature_vararg_match (sig, msig))
630 if (mono_metadata_signature_equal (sig, msig))
635 if (i < klass->method.count)
636 return mono_class_get_method_by_index (from_class, i);
641 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
644 char *qname, *fqname, *class_name;
645 gboolean is_interface;
646 MonoMethod *result = NULL;
648 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
651 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
653 qname = g_strconcat (class_name, ".", name, NULL);
654 if (ic->name_space && ic->name_space [0])
655 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
659 class_name = qname = fqname = NULL;
662 g_assert (from_class);
663 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
667 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
670 g_assert (from_class->interface_offsets_count == in_class->interface_offsets_count);
671 for (i = 0; i < in_class->interface_offsets_count; i++) {
672 MonoClass *in_ic = in_class->interfaces_packed [i];
673 MonoClass *from_ic = from_class->interfaces_packed [i];
674 char *ic_qname, *ic_fqname, *ic_class_name;
676 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
677 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
678 if (in_ic->name_space && in_ic->name_space [0])
679 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
683 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic);
684 g_free (ic_class_name);
691 in_class = in_class->parent;
692 from_class = from_class->parent;
694 g_assert (!in_class == !from_class);
697 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
706 static MonoMethodSignature*
707 inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
709 MonoMethodSignature *res;
716 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
717 res->param_count = sig->param_count;
718 res->sentinelpos = -1;
719 res->ret = mono_class_inflate_generic_type (sig->ret, context);
720 is_open = mono_class_is_open_constructed_type (res->ret);
721 for (i = 0; i < sig->param_count; ++i) {
722 res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
724 is_open = mono_class_is_open_constructed_type (res->params [i]);
726 res->hasthis = sig->hasthis;
727 res->explicit_this = sig->explicit_this;
728 res->call_convention = sig->call_convention;
729 res->pinvoke = sig->pinvoke;
730 res->generic_param_count = sig->generic_param_count;
731 res->sentinelpos = sig->sentinelpos;
732 res->has_type_parameters = is_open;
733 res->is_inflated = 1;
737 static MonoMethodHeader*
738 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
740 MonoMethodHeader *res;
742 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
743 res->code = header->code;
744 res->code_size = header->code_size;
745 res->max_stack = header->max_stack;
746 res->num_clauses = header->num_clauses;
747 res->init_locals = header->init_locals;
748 res->num_locals = header->num_locals;
749 res->clauses = header->clauses;
750 for (i = 0; i < header->num_locals; ++i)
751 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
752 if (res->num_clauses) {
753 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
754 for (i = 0; i < header->num_clauses; ++i) {
755 MonoExceptionClause *clause = &res->clauses [i];
756 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
758 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
765 * token is the method_ref/def/spec token used in a call IL instruction.
768 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
770 int table = mono_metadata_token_table (token);
771 int idx = mono_metadata_token_index (token);
773 guint32 cols [MONO_MEMBERREF_SIZE];
774 MonoMethodSignature *sig;
777 /* !table is for wrappers: we should really assign their own token to them */
778 if (!table || table == MONO_TABLE_METHOD)
779 return mono_method_signature (method);
781 if (table == MONO_TABLE_METHODSPEC) {
782 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
783 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
786 return mono_method_signature (method);
789 if (method->klass->generic_class)
790 return mono_method_signature (method);
793 /* FIXME: This might be incorrect for vararg methods */
794 return mono_method_signature (method);
796 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
797 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
799 sig = find_cached_memberref_sig (image, sig_idx);
801 if (!mono_verifier_verify_memberref_signature (image, sig_idx, NULL)) {
802 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
803 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
805 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
809 ptr = mono_metadata_blob_heap (image, sig_idx);
810 mono_metadata_decode_blob_size (ptr, &ptr);
811 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
814 sig = cache_memberref_sig (image, sig_idx, sig);
817 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
818 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
819 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
821 mono_loader_set_error_bad_image (g_strdup_printf ("Incompatible method signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
826 MonoMethodSignature *cached;
828 /* This signature is not owned by a MonoMethod, so need to cache */
829 sig = inflate_generic_signature (image, sig, context);
830 cached = mono_metadata_get_inflated_signature (sig, context);
832 mono_metadata_free_inflated_signature (sig);
834 inflated_signatures_size += mono_metadata_signature_size (cached);
842 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
844 return mono_method_get_signature_full (method, image, token, NULL);
847 /* this is only for the typespec array methods */
849 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
853 mono_class_setup_methods (klass);
854 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
855 for (i = 0; i < klass->method.count; ++i) {
856 MonoMethod *method = klass->methods [i];
857 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
864 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
865 gboolean *used_context)
867 MonoClass *klass = NULL;
868 MonoMethod *method = NULL;
869 MonoTableInfo *tables = image->tables;
871 guint32 nindex, class, sig_idx;
873 MonoMethodSignature *sig;
876 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
877 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
878 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
879 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
880 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
882 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
885 * Whether we actually used the `typespec_context' or not.
886 * This is used to tell our caller whether or not it's safe to insert the returned
887 * method into a cache.
890 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
893 case MONO_MEMBERREF_PARENT_TYPEREF:
894 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
896 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
897 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
898 mono_loader_set_error_type_load (name, image->assembly_name);
903 case MONO_MEMBERREF_PARENT_TYPESPEC:
905 * Parse the TYPESPEC in the parent's context.
907 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
909 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
910 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
911 mono_loader_set_error_type_load (name, image->assembly_name);
916 case MONO_MEMBERREF_PARENT_TYPEDEF:
917 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
919 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
920 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
921 mono_loader_set_error_type_load (name, image->assembly_name);
926 case MONO_MEMBERREF_PARENT_METHODDEF:
927 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
931 /* This message leaks */
932 char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
933 mono_loader_set_error_method_load ("", message);
939 mono_class_init (klass);
941 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
943 if (!mono_verifier_verify_memberref_signature (image, sig_idx, NULL)) {
944 mono_loader_set_error_method_load (klass->name, mname);
948 ptr = mono_metadata_blob_heap (image, sig_idx);
949 mono_metadata_decode_blob_size (ptr, &ptr);
951 sig = find_cached_memberref_sig (image, sig_idx);
953 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
957 sig = cache_memberref_sig (image, sig_idx, sig);
961 case MONO_MEMBERREF_PARENT_TYPEREF:
962 case MONO_MEMBERREF_PARENT_TYPEDEF:
963 method = find_method (klass, NULL, mname, sig, klass);
966 case MONO_MEMBERREF_PARENT_TYPESPEC: {
969 type = &klass->byval_arg;
971 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
972 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
973 method = find_method (in_class, NULL, mname, sig, klass);
977 /* we're an array and we created these methods already in klass in mono_class_init () */
978 method = mono_method_search_in_array_class (klass, mname, sig);
982 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
983 g_assert_not_reached ();
987 char *msig = mono_signature_get_desc (sig, FALSE);
988 char * class_name = mono_type_get_name (&klass->byval_arg);
989 GString *s = g_string_new (mname);
990 if (sig->generic_param_count)
991 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
992 g_string_append_printf (s, "(%s)", msig);
994 msig = g_string_free (s, FALSE);
997 "Missing method %s::%s in assembly %s, referenced in assembly %s",
998 class_name, msig, klass->image->name, image->name);
999 mono_loader_set_error_method_load (class_name, mname);
1001 g_free (class_name);
1008 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
1013 MonoTableInfo *tables = image->tables;
1014 MonoGenericContext new_context;
1015 MonoGenericInst *inst;
1017 guint32 cols [MONO_METHODSPEC_SIZE];
1018 guint32 token, nindex, param_count;
1020 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1021 token = cols [MONO_METHODSPEC_METHOD];
1022 nindex = token >> MONO_METHODDEFORREF_BITS;
1024 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL))
1027 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1029 mono_metadata_decode_value (ptr, &ptr);
1031 param_count = mono_metadata_decode_value (ptr, &ptr);
1032 g_assert (param_count);
1034 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1035 if (context && inst->is_open) {
1036 inst = mono_metadata_inflate_generic_inst (inst, context, &error);
1037 if (!mono_error_ok (&error)) {
1038 mono_error_cleanup (&error); /*FIXME don't swallow error message.*/
1043 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
1044 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
1046 method = method_from_memberref (image, nindex, context, NULL);
1051 klass = method->klass;
1053 if (klass->generic_class) {
1054 g_assert (method->is_inflated);
1055 method = ((MonoMethodInflated *) method)->declaring;
1058 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1059 new_context.method_inst = inst;
1061 return mono_class_inflate_generic_method_full (method, klass, &new_context);
1064 struct _MonoDllMap {
1072 static MonoDllMap *global_dll_map;
1075 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1083 mono_loader_lock ();
1086 * we use the first entry we find that matches, since entries from
1087 * the config file are prepended to the list and we document that the
1088 * later entries win.
1090 for (; dll_map; dll_map = dll_map->next) {
1091 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1092 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1094 } else if (strcmp (dll_map->dll, dll)) {
1097 if (!found && dll_map->target) {
1098 *rdll = dll_map->target;
1100 /* we don't quit here, because we could find a full
1101 * entry that matches also function and that has priority.
1104 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1105 *rfunc = dll_map->target_func;
1110 mono_loader_unlock ();
1115 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1118 if (assembly && assembly->dll_map) {
1119 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1123 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1127 * mono_dllmap_insert:
1129 * LOCKING: Acquires the loader lock.
1131 * NOTE: This can be called before the runtime is initialized, for example from
1132 * mono_config_parse ().
1135 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1139 mono_loader_init ();
1141 mono_loader_lock ();
1144 entry = g_malloc0 (sizeof (MonoDllMap));
1145 entry->dll = dll? g_strdup (dll): NULL;
1146 entry->target = tdll? g_strdup (tdll): NULL;
1147 entry->func = func? g_strdup (func): NULL;
1148 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1149 entry->next = global_dll_map;
1150 global_dll_map = entry;
1152 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1153 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1154 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1155 entry->func = func? mono_image_strdup (assembly, func): NULL;
1156 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1157 entry->next = assembly->dll_map;
1158 assembly->dll_map = entry;
1161 mono_loader_unlock ();
1164 static GHashTable *global_module_map;
1167 cached_module_load (const char *name, int flags, char **err)
1170 mono_loader_lock ();
1171 if (!global_module_map)
1172 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1173 res = g_hash_table_lookup (global_module_map, name);
1176 mono_loader_unlock ();
1179 res = mono_dl_open (name, flags, err);
1181 g_hash_table_insert (global_module_map, g_strdup (name), res);
1182 mono_loader_unlock ();
1187 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1189 MonoImage *image = method->klass->image;
1190 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1191 MonoTableInfo *tables = image->tables;
1192 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1193 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1194 guint32 im_cols [MONO_IMPLMAP_SIZE];
1195 guint32 scope_token;
1196 const char *import = NULL;
1197 const char *orig_scope;
1198 const char *new_scope;
1200 char *full_name, *file_name;
1202 MonoDl *module = NULL;
1204 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1207 return piinfo->addr;
1209 if (method->klass->image->dynamic) {
1210 MonoReflectionMethodAux *method_aux =
1211 g_hash_table_lookup (
1212 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1216 import = method_aux->dllentry;
1217 orig_scope = method_aux->dll;
1220 if (!piinfo->implmap_idx)
1223 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1225 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1226 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1227 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1228 orig_scope = mono_metadata_string_heap (image, scope_token);
1231 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1233 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1234 "DllImport attempting to load: '%s'.", new_scope);
1241 /* we allow a special name to dlopen from the running process namespace */
1242 if (strcmp (new_scope, "__Internal") == 0)
1243 module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1246 * Try loading the module using a variety of names
1248 for (i = 0; i < 4; ++i) {
1251 /* Try the original name */
1252 file_name = g_strdup (new_scope);
1255 /* Try trimming the .dll extension */
1256 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1257 file_name = g_strdup (new_scope);
1258 file_name [strlen (new_scope) - 4] = '\0';
1264 if (strstr (new_scope, "lib") != new_scope) {
1265 file_name = g_strdup_printf ("lib%s", new_scope);
1271 #ifndef TARGET_WIN32
1272 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1273 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1274 !g_ascii_strcasecmp ("user32", new_scope) ||
1275 !g_ascii_strcasecmp ("kernel", new_scope)) {
1276 file_name = g_strdup ("libMonoSupportW.so");
1280 #ifndef TARGET_WIN32
1287 while ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {
1288 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1289 "DllImport loading location: '%s'.", full_name);
1290 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1292 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1293 "DllImport error loading library: '%s'.",
1305 while ((full_name = mono_dl_build_path (".", file_name, &iter))) {
1306 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1307 "DllImport loading library: '%s'.", full_name);
1308 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1310 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1311 "DllImport error loading library '%s'.",
1322 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1323 "DllImport loading: '%s'.", file_name);
1324 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1326 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1327 "DllImport error loading library '%s'.",
1339 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1340 "DllImport unable to load library '%s'.",
1345 *exc_class = "DllNotFoundException";
1346 *exc_arg = new_scope;
1351 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1352 "Searching for '%s'.", import);
1354 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1355 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1357 char *mangled_name = NULL, *mangled_name2 = NULL;
1360 int mangle_param_count;
1366 * Search using a variety of mangled names
1368 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1369 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1370 gboolean need_param_count = FALSE;
1372 if (mangle_stdcall > 0)
1373 need_param_count = TRUE;
1375 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1380 mangled_name = (char*)import;
1381 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1382 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1383 /* Try the mangled name first */
1384 if (mangle_charset == 0)
1385 mangled_name = g_strconcat (import, "W", NULL);
1387 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1389 if (mangle_charset == 0)
1390 mangled_name = g_strconcat (import, "W", NULL);
1392 /* Try the mangled name last */
1393 if (mangle_charset == 1)
1394 mangled_name = g_strconcat (import, "A", NULL);
1397 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1399 /* Try the mangled name last */
1400 if (mangle_charset == 1)
1401 mangled_name = g_strconcat (import, "A", NULL);
1406 if (mangle_param_count == 0)
1407 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1409 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1410 param_count = mangle_param_count;
1412 /* Try the stdcall mangled name */
1414 * gcc under windows creates mangled names without the underscore, but MS.NET
1415 * doesn't support it, so we doesn't support it either.
1417 if (mangle_stdcall == 1)
1418 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1420 mangled_name2 = mangled_name;
1422 mangled_name2 = mangled_name;
1425 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1426 "Probing '%s'.", mangled_name2);
1428 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1431 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1432 "Found as '%s'.", mangled_name2);
1434 if (mangled_name != mangled_name2)
1435 g_free (mangled_name2);
1436 if (mangled_name != import)
1437 g_free (mangled_name);
1443 if (!piinfo->addr) {
1446 *exc_class = "EntryPointNotFoundException";
1451 return piinfo->addr;
1455 * LOCKING: assumes the loader lock to be taken.
1458 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1459 MonoGenericContext *context, gboolean *used_context)
1462 int table = mono_metadata_token_table (token);
1463 int idx = mono_metadata_token_index (token);
1464 MonoTableInfo *tables = image->tables;
1465 MonoGenericContainer *generic_container = NULL, *container = NULL;
1466 const char *sig = NULL;
1468 guint32 cols [MONO_TYPEDEF_SIZE];
1470 if (image->dynamic) {
1471 MonoClass *handle_class;
1473 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1474 // This checks the memberref type as well
1475 if (result && handle_class != mono_defaults.methodhandle_class) {
1476 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1482 if (table != MONO_TABLE_METHOD) {
1483 if (table == MONO_TABLE_METHODSPEC) {
1484 if (used_context) *used_context = TRUE;
1485 return method_from_methodspec (image, context, idx);
1487 if (table != MONO_TABLE_MEMBERREF) {
1488 g_warning ("got wrong token: 0x%08x\n", token);
1489 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1492 return method_from_memberref (image, idx, context, used_context);
1495 if (used_context) *used_context = FALSE;
1497 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1498 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1502 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1504 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1505 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1506 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1508 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodNormal));
1510 mono_stats.method_count ++;
1512 if (!klass) { /*FIXME put this before the image alloc*/
1513 guint32 type = mono_metadata_typedef_from_method (image, token);
1516 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1522 result->klass = klass;
1523 result->flags = cols [2];
1524 result->iflags = cols [1];
1525 result->token = token;
1526 result->name = mono_metadata_string_heap (image, cols [3]);
1528 if (!sig) /* already taken from the methodref */
1529 sig = mono_metadata_blob_heap (image, cols [4]);
1530 size = mono_metadata_decode_blob_size (sig, &sig);
1532 container = klass->generic_container;
1535 * load_generic_params does a binary search so only call it if the method
1539 generic_container = mono_metadata_load_generic_params (image, token, container);
1540 if (generic_container) {
1541 result->is_generic = TRUE;
1542 generic_container->owner.method = result;
1543 /*FIXME put this before the image alloc*/
1544 if (!mono_metadata_load_generic_param_constraints_full (image, token, generic_container))
1547 container = generic_container;
1550 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1551 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1552 result->string_ctor = 1;
1553 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1554 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1557 /* IJW is P/Invoke with a predefined function pointer. */
1558 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1559 piinfo->addr = mono_image_rva_map (image, cols [0]);
1560 g_assert (piinfo->addr);
1563 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1564 /* Native methods can have no map. */
1565 if (piinfo->implmap_idx)
1566 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1569 if (generic_container)
1570 mono_method_set_generic_container (result, generic_container);
1576 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1578 return mono_get_method_full (image, token, klass, NULL);
1582 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1583 MonoGenericContext *context)
1586 gboolean used_context = FALSE;
1588 /* We do everything inside the lock to prevent creation races */
1590 mono_image_lock (image);
1592 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1593 if (!image->method_cache)
1594 image->method_cache = g_hash_table_new (NULL, NULL);
1595 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1597 if (!image->methodref_cache)
1598 image->methodref_cache = g_hash_table_new (NULL, NULL);
1599 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1601 mono_image_unlock (image);
1606 result = mono_get_method_from_token (image, token, klass, context, &used_context);
1610 mono_image_lock (image);
1611 if (!used_context && !result->is_inflated) {
1612 MonoMethod *result2;
1613 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1614 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1616 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1619 mono_image_unlock (image);
1623 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1624 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1626 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1629 mono_image_unlock (image);
1635 * mono_get_method_constrained:
1637 * This is used when JITing the `constrained.' opcode.
1639 * This returns two values: the contrained method, which has been inflated
1640 * as the function return value; And the original CIL-stream method as
1641 * declared in cil_method. The later is used for verification.
1644 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1645 MonoGenericContext *context, MonoMethod **cil_method)
1647 MonoMethod *method, *result;
1648 MonoClass *ic = NULL;
1649 MonoGenericContext *method_context = NULL;
1650 MonoMethodSignature *sig, *original_sig;
1652 mono_loader_lock ();
1654 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL);
1656 mono_loader_unlock ();
1660 mono_class_init (constrained_class);
1661 method = *cil_method;
1662 original_sig = sig = mono_method_signature (method);
1666 if (method->is_inflated && sig->generic_param_count) {
1667 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1668 sig = mono_method_signature (imethod->declaring); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1669 method_context = mono_method_get_context (method);
1673 * We must inflate the signature with the class instantiation to work on
1674 * cases where a class inherit from a generic type and the override replaces
1675 * any type argument which a concrete type. See #325283.
1677 if (method_context->class_inst) {
1678 MonoGenericContext ctx;
1679 ctx.method_inst = NULL;
1680 ctx.class_inst = method_context->class_inst;
1682 sig = inflate_generic_signature (method->klass->image, sig, &ctx);
1688 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1691 result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1692 if (sig != original_sig)
1693 mono_metadata_free_inflated_signature (sig);
1696 g_warning ("Missing method %s.%s.%s in assembly %s token %x", method->klass->name_space,
1697 method->klass->name, method->name, image->name, token);
1698 mono_loader_unlock ();
1703 result = mono_class_inflate_generic_method (result, method_context);
1705 mono_loader_unlock ();
1710 mono_free_method (MonoMethod *method)
1712 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1713 mono_profiler_method_free (method);
1715 /* FIXME: This hack will go away when the profiler will support freeing methods */
1716 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1719 if (method->signature) {
1721 * FIXME: This causes crashes because the types inside signatures and
1722 * locals are shared.
1724 /* mono_metadata_free_method_signature (method->signature); */
1725 /* g_free (method->signature); */
1728 if (method->dynamic) {
1729 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1732 mono_marshal_free_dynamic_wrappers (method);
1734 mono_image_property_remove (method->klass->image, method);
1736 g_free ((char*)method->name);
1737 if (mw->method.header) {
1738 g_free ((char*)mw->method.header->code);
1739 for (i = 0; i < mw->method.header->num_locals; ++i)
1740 g_free (mw->method.header->locals [i]);
1741 g_free (mw->method.header->clauses);
1742 g_free (mw->method.header);
1744 g_free (mw->method_data);
1745 g_free (method->signature);
1751 mono_method_get_param_names (MonoMethod *method, const char **names)
1755 MonoTableInfo *methodt;
1756 MonoTableInfo *paramt;
1757 MonoMethodSignature *signature;
1760 if (method->is_inflated)
1761 method = ((MonoMethodInflated *) method)->declaring;
1763 signature = mono_method_signature (method);
1764 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
1765 number of arguments and allocate a properly sized array. */
1766 if (signature == NULL)
1769 if (!signature->param_count)
1772 for (i = 0; i < signature->param_count; ++i)
1775 klass = method->klass;
1779 mono_class_init (klass);
1781 if (klass->image->dynamic) {
1782 MonoReflectionMethodAux *method_aux =
1783 g_hash_table_lookup (
1784 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1785 if (method_aux && method_aux->param_names) {
1786 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1787 if (method_aux->param_names [i + 1])
1788 names [i] = method_aux->param_names [i + 1];
1793 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1794 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1795 idx = mono_method_get_index (method);
1797 guint32 cols [MONO_PARAM_SIZE];
1800 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1802 if (idx < methodt->rows)
1803 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1805 lastp = paramt->rows + 1;
1806 for (i = param_index; i < lastp; ++i) {
1807 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1808 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
1809 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1815 mono_method_get_param_token (MonoMethod *method, int index)
1817 MonoClass *klass = method->klass;
1818 MonoTableInfo *methodt;
1821 mono_class_init (klass);
1823 if (klass->image->dynamic) {
1824 g_assert_not_reached ();
1827 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1828 idx = mono_method_get_index (method);
1830 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1834 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
1836 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1843 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1846 MonoClass *klass = method->klass;
1847 MonoTableInfo *methodt;
1848 MonoTableInfo *paramt;
1849 MonoMethodSignature *signature;
1852 signature = mono_method_signature (method);
1853 g_assert (signature); /*FIXME there is no way to signal error from this function*/
1855 for (i = 0; i < signature->param_count + 1; ++i)
1858 if (method->klass->image->dynamic) {
1859 MonoReflectionMethodAux *method_aux =
1860 g_hash_table_lookup (
1861 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1862 if (method_aux && method_aux->param_marshall) {
1863 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1864 for (i = 0; i < signature->param_count + 1; ++i)
1865 if (dyn_specs [i]) {
1866 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1867 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1873 mono_class_init (klass);
1875 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1876 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1877 idx = mono_method_get_index (method);
1879 guint32 cols [MONO_PARAM_SIZE];
1880 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1882 if (idx < methodt->rows)
1883 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1885 lastp = paramt->rows + 1;
1887 for (i = param_index; i < lastp; ++i) {
1888 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1890 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
1892 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1894 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1903 mono_method_has_marshal_info (MonoMethod *method)
1906 MonoClass *klass = method->klass;
1907 MonoTableInfo *methodt;
1908 MonoTableInfo *paramt;
1911 if (method->klass->image->dynamic) {
1912 MonoReflectionMethodAux *method_aux =
1913 g_hash_table_lookup (
1914 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1915 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1917 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1924 mono_class_init (klass);
1926 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1927 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1928 idx = mono_method_get_index (method);
1930 guint32 cols [MONO_PARAM_SIZE];
1931 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1933 if (idx + 1 < methodt->rows)
1934 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1936 lastp = paramt->rows + 1;
1938 for (i = param_index; i < lastp; ++i) {
1939 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1941 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1950 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1953 g_assert (method != NULL);
1954 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1956 if (method->is_inflated)
1957 method = ((MonoMethodInflated *) method)->declaring;
1958 data = ((MonoMethodWrapper *)method)->method_data;
1959 g_assert (data != NULL);
1960 g_assert (id <= GPOINTER_TO_UINT (*data));
1965 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1966 g_error ("stack walk not installed");
1969 static MonoStackWalkImpl stack_walk = default_stack_walk;
1972 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1974 stack_walk (func, TRUE, user_data);
1978 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1980 stack_walk (func, FALSE, user_data);
1984 mono_install_stack_walk (MonoStackWalkImpl func)
1990 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1992 MonoMethod **dest = data;
1994 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2000 mono_method_get_last_managed (void)
2002 MonoMethod *m = NULL;
2003 stack_walk (last_managed, FALSE, &m);
2007 static gboolean loader_lock_track_ownership = FALSE;
2012 * See docs/thread-safety.txt for the locking strategy.
2015 mono_loader_lock (void)
2017 mono_locks_acquire (&loader_mutex, LoaderLock);
2018 if (G_UNLIKELY (loader_lock_track_ownership)) {
2019 TlsSetValue (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) + 1));
2024 mono_loader_unlock (void)
2026 mono_locks_release (&loader_mutex, LoaderLock);
2027 if (G_UNLIKELY (loader_lock_track_ownership)) {
2028 TlsSetValue (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) - 1));
2033 * mono_loader_lock_track_ownership:
2035 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2036 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2037 * thread owns the loader lock.
2040 mono_loader_lock_track_ownership (gboolean track)
2042 loader_lock_track_ownership = track;
2046 * mono_loader_lock_is_owned_by_self:
2048 * Return whenever the current thread owns the loader lock.
2049 * This is useful to avoid blocking operations while holding the loader lock.
2052 mono_loader_lock_is_owned_by_self (void)
2054 g_assert (loader_lock_track_ownership);
2056 return GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) > 0;
2060 * mono_method_signature:
2062 * Return the signature of the method M. On failure, returns NULL.
2064 MonoMethodSignature*
2065 mono_method_signature (MonoMethod *m)
2071 gboolean can_cache_signature;
2072 MonoGenericContainer *container;
2073 MonoMethodSignature *signature = NULL;
2076 /* We need memory barriers below because of the double-checked locking pattern */
2079 return m->signature;
2081 mono_loader_lock ();
2084 mono_loader_unlock ();
2085 return m->signature;
2088 if (m->is_inflated) {
2089 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2090 /* the lock is recursive */
2091 signature = mono_method_signature (imethod->declaring);
2092 signature = inflate_generic_signature (imethod->declaring->klass->image, signature, mono_method_get_context (m));
2094 inflated_signatures_size += mono_metadata_signature_size (signature);
2096 mono_memory_barrier ();
2097 m->signature = signature;
2098 mono_loader_unlock ();
2099 return m->signature;
2102 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2103 idx = mono_metadata_token_index (m->token);
2104 img = m->klass->image;
2106 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2108 g_assert (!m->klass->generic_class);
2109 container = mono_method_get_generic_container (m);
2111 container = m->klass->generic_container;
2113 /* Generic signatures depend on the container so they cannot be cached */
2114 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2115 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2117 /* If the method has parameter attributes, that can modify the signature */
2118 if (mono_metadata_method_has_param_attrs (img, idx))
2119 can_cache_signature = FALSE;
2121 if (can_cache_signature)
2122 signature = g_hash_table_lookup (img->method_signatures, sig);
2125 const char *sig_body;
2126 /*TODO we should cache the failure result somewhere*/
2127 if (!mono_verifier_verify_method_signature (img, sig_offset, NULL)) {
2128 mono_loader_unlock ();
2132 size = mono_metadata_decode_blob_size (sig, &sig_body);
2134 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
2136 mono_loader_unlock ();
2140 if (can_cache_signature)
2141 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2144 /* Verify metadata consistency */
2145 if (signature->generic_param_count) {
2146 if (!container || !container->is_method) {
2147 g_warning ("Signature claims method has generic parameters, but generic_params table says it doesn't for method 0x%08x from image %s", idx, img->name);
2148 mono_loader_unlock ();
2151 if (container->type_argc != signature->generic_param_count) {
2152 g_warning ("Inconsistent generic parameter count. Signature says %d, generic_params table says %d for method 0x%08x from image %s",
2153 signature->generic_param_count, container->type_argc, idx, img->name);
2154 mono_loader_unlock ();
2157 } else if (container && container->is_method && container->type_argc) {
2158 g_warning ("generic_params table claims method has generic parameters, but signature says it doesn't for method 0x%08x from image %s", idx, img->name);
2159 mono_loader_unlock ();
2162 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2163 signature->pinvoke = 1;
2164 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2165 MonoCallConvention conv = 0;
2166 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2167 signature->pinvoke = 1;
2169 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2170 case 0: /* no call conv, so using default */
2171 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2172 conv = MONO_CALL_DEFAULT;
2174 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2177 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2178 conv = MONO_CALL_STDCALL;
2180 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2181 conv = MONO_CALL_THISCALL;
2183 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2184 conv = MONO_CALL_FASTCALL;
2186 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2187 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2189 g_warning ("unsupported calling convention : 0x%04x for method 0x%08x from image %s", piinfo->piflags, idx, img->name);
2190 mono_loader_unlock ();
2193 signature->call_convention = conv;
2196 mono_memory_barrier ();
2197 m->signature = signature;
2199 mono_loader_unlock ();
2200 return m->signature;
2204 mono_method_get_name (MonoMethod *method)
2206 return method->name;
2210 mono_method_get_class (MonoMethod *method)
2212 return method->klass;
2216 mono_method_get_token (MonoMethod *method)
2218 return method->token;
2222 mono_method_get_header (MonoMethod *method)
2228 MonoMethodNormal* mn = (MonoMethodNormal*) method;
2229 MonoMethodHeader *header;
2231 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))
2235 if (G_LIKELY (mn->header))
2241 if (method->is_inflated) {
2242 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2243 MonoMethodHeader *header;
2245 header = mono_method_get_header (imethod->declaring);
2247 mono_loader_lock ();
2250 mono_loader_unlock ();
2254 mn->header = inflate_generic_header (header, mono_method_get_context (method));
2255 mono_loader_unlock ();
2260 * Do most of the work outside the loader lock, to avoid assembly loader hook
2263 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2264 idx = mono_metadata_token_index (method->token);
2265 img = method->klass->image;
2266 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2268 if (!mono_verifier_verify_method_header (img, rva, NULL))
2271 loc = mono_image_rva_map (img, rva);
2274 header = mono_metadata_parse_mh_full (img, mono_method_get_generic_container (method), loc);
2276 mono_loader_lock ();
2279 /* header is allocated from the image mempool, no need to free it */
2280 mono_loader_unlock ();
2284 mono_memory_barrier ();
2286 mn->header = header;
2288 mono_loader_unlock ();
2293 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2296 *iflags = method->iflags;
2297 return method->flags;
2301 * Find the method index in the metadata methodDef table.
2304 mono_method_get_index (MonoMethod *method) {
2305 MonoClass *klass = method->klass;
2309 return mono_metadata_token_index (method->token);
2311 mono_class_setup_methods (klass);
2312 if (klass->exception_type)
2314 for (i = 0; i < klass->method.count; ++i) {
2315 if (method == klass->methods [i]) {
2316 if (klass->image->uncompressed_metadata)
2317 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2319 return klass->method.first + i + 1;