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-internal.h>
42 #include <mono/utils/mono-dl.h>
43 #include <mono/utils/mono-membar.h>
44 #include <mono/utils/mono-counters.h>
45 #include <mono/utils/mono-error-internals.h>
47 MonoDefaults mono_defaults;
50 * This lock protects the hash tables inside MonoImage used by the metadata
51 * loading functions in class.c and loader.c.
53 * See domain-internals.h for locking policy in combination with the
56 static CRITICAL_SECTION loader_mutex;
57 static gboolean loader_lock_inited;
60 static guint32 inflated_signatures_size;
61 static guint32 memberref_sig_cache_size;
64 * This TLS variable contains the last type load error encountered by the loader.
66 guint32 loader_error_thread_id;
69 * This TLS variable holds how many times the current thread has acquired the loader
72 guint32 loader_lock_nest_id;
77 static gboolean inited;
80 InitializeCriticalSection (&loader_mutex);
81 loader_lock_inited = TRUE;
83 loader_error_thread_id = TlsAlloc ();
84 loader_lock_nest_id = TlsAlloc ();
86 mono_counters_register ("Inflated signatures size",
87 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
88 mono_counters_register ("Memberref signature cache size",
89 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
96 mono_loader_cleanup (void)
98 TlsFree (loader_error_thread_id);
99 TlsFree (loader_lock_nest_id);
101 DeleteCriticalSection (&loader_mutex);
102 loader_lock_inited = FALSE;
106 * Handling of type load errors should be done as follows:
108 * If something could not be loaded, the loader should call one of the
109 * mono_loader_set_error_XXX functions ()
110 * with the appropriate arguments, then return NULL to report the failure. The error
111 * should be propagated until it reaches code which can throw managed exceptions. At that
112 * point, an exception should be thrown based on the information returned by
113 * mono_loader_get_last_error (). Then the error should be cleared by calling
114 * mono_loader_clear_error ().
118 set_loader_error (MonoLoaderError *error)
120 TlsSetValue (loader_error_thread_id, error);
124 * mono_loader_set_error_assembly_load:
126 * Set the loader error for this thread.
129 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
131 MonoLoaderError *error;
133 if (mono_loader_get_last_error ())
136 error = g_new0 (MonoLoaderError, 1);
137 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
138 error->assembly_name = g_strdup (assembly_name);
139 error->ref_only = ref_only;
142 * This is not strictly needed, but some (most) of the loader code still
143 * can't deal with load errors, and this message is more helpful than an
147 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);
149 g_warning ("Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
151 set_loader_error (error);
155 * mono_loader_set_error_type_load:
157 * Set the loader error for this thread.
160 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
162 MonoLoaderError *error;
164 if (mono_loader_get_last_error ())
167 error = g_new0 (MonoLoaderError, 1);
168 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
169 error->class_name = g_strdup (class_name);
170 error->assembly_name = g_strdup (assembly_name);
173 * This is not strictly needed, but some (most) of the loader code still
174 * can't deal with load errors, and this message is more helpful than an
177 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
179 set_loader_error (error);
183 * mono_loader_set_error_method_load:
185 * Set the loader error for this thread. MEMBER_NAME should point to a string
189 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
191 MonoLoaderError *error;
193 /* FIXME: Store the signature as well */
194 if (mono_loader_get_last_error ())
197 error = g_new0 (MonoLoaderError, 1);
198 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
199 error->class_name = g_strdup (class_name);
200 error->member_name = member_name;
202 set_loader_error (error);
206 * mono_loader_set_error_field_load:
208 * Set the loader error for this thread. MEMBER_NAME should point to a string
212 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
214 MonoLoaderError *error;
216 /* FIXME: Store the signature as well */
217 if (mono_loader_get_last_error ())
220 error = g_new0 (MonoLoaderError, 1);
221 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
222 error->klass = klass;
223 error->member_name = member_name;
225 set_loader_error (error);
229 * mono_loader_set_error_bad_image:
231 * Set the loader error for this thread.
234 mono_loader_set_error_bad_image (char *msg)
236 MonoLoaderError *error;
238 if (mono_loader_get_last_error ())
241 error = g_new0 (MonoLoaderError, 1);
242 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
245 set_loader_error (error);
250 * mono_loader_get_last_error:
252 * Returns information about the last type load exception encountered by the loader, or
253 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
256 mono_loader_get_last_error (void)
258 return (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
262 * mono_loader_clear_error:
264 * Disposes any loader error messages on this thread
267 mono_loader_clear_error (void)
269 MonoLoaderError *ex = (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
272 g_free (ex->class_name);
273 g_free (ex->assembly_name);
277 TlsSetValue (loader_error_thread_id, NULL);
282 * mono_loader_error_prepare_exception:
283 * @error: The MonoLoaderError to turn into an exception
285 * This turns a MonoLoaderError into an exception that can be thrown
286 * and resets the Mono Loader Error state during this process.
290 mono_loader_error_prepare_exception (MonoLoaderError *error)
292 MonoException *ex = NULL;
294 switch (error->exception_type) {
295 case MONO_EXCEPTION_TYPE_LOAD: {
296 char *cname = g_strdup (error->class_name);
297 char *aname = g_strdup (error->assembly_name);
298 MonoString *class_name;
300 mono_loader_clear_error ();
302 class_name = mono_string_new (mono_domain_get (), cname);
304 ex = mono_get_exception_type_load (class_name, aname);
309 case MONO_EXCEPTION_MISSING_METHOD: {
310 char *cname = g_strdup (error->class_name);
311 char *aname = g_strdup (error->member_name);
313 mono_loader_clear_error ();
314 ex = mono_get_exception_missing_method (cname, aname);
320 case MONO_EXCEPTION_MISSING_FIELD: {
321 char *cnspace = g_strdup ((error->klass && *error->klass->name_space) ? error->klass->name_space : "");
322 char *cname = g_strdup (error->klass ? error->klass->name : "");
323 char *cmembername = g_strdup (error->member_name);
326 mono_loader_clear_error ();
327 class_name = g_strdup_printf ("%s%s%s", cnspace, cnspace ? "." : "", cname);
329 ex = mono_get_exception_missing_field (class_name, cmembername);
332 g_free (cmembername);
337 case MONO_EXCEPTION_FILE_NOT_FOUND: {
342 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);
344 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
345 filename = g_strdup (error->assembly_name);
346 /* Has to call this before calling anything which might call mono_class_init () */
347 mono_loader_clear_error ();
348 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
354 case MONO_EXCEPTION_BAD_IMAGE: {
355 char *msg = g_strdup (error->msg);
356 mono_loader_clear_error ();
357 ex = mono_get_exception_bad_image_format (msg);
363 g_assert_not_reached ();
370 * find_cached_memberref_sig:
372 * Return a cached copy of the memberref signature identified by SIG_IDX.
373 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
374 * A cache is needed since the type/signature parsing routines allocate everything
375 * from a mempool, so without a cache, multiple requests for the same signature would
376 * lead to unbounded memory growth. For normal methods/fields this is not a problem
377 * since the resulting methods/fields are cached, but inflated methods/fields cannot
379 * LOCKING: Acquires the loader lock.
382 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
387 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
388 mono_loader_unlock ();
394 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
399 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
401 /* Somebody got in before us */
405 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
406 /* An approximation based on glib 2.18 */
407 memberref_sig_cache_size += sizeof (gpointer) * 4;
410 mono_loader_unlock ();
415 static MonoClassField*
416 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
417 MonoGenericContext *context)
420 MonoClassField *field;
421 MonoTableInfo *tables = image->tables;
424 guint32 nindex, class, class_table;
427 guint32 idx = mono_metadata_token_index (token);
429 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
430 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
431 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
433 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
435 if (!mono_verifier_verify_memberref_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
436 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));
441 case MONO_MEMBERREF_PARENT_TYPEDEF:
442 class_table = MONO_TOKEN_TYPE_DEF;
443 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
445 case MONO_MEMBERREF_PARENT_TYPEREF:
446 class_table = MONO_TOKEN_TYPE_REF;
447 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
449 case MONO_MEMBERREF_PARENT_TYPESPEC:
450 class_table = MONO_TOKEN_TYPE_SPEC;
451 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
454 /*FIXME this must set a loader error!*/
455 g_warning ("field load from %x", class);
460 char *name = mono_class_name_from_token (image, class_table | nindex);
461 g_warning ("Missing field %s in class %s (type token %d)", fname, name, class_table | nindex);
462 mono_loader_set_error_type_load (name, image->assembly_name);
467 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
468 mono_metadata_decode_blob_size (ptr, &ptr);
469 /* we may want to check the signature here... */
472 g_warning ("Bad field signature class token %08x field name %s token %08x", class, fname, token);
473 mono_loader_set_error_field_load (klass, fname);
476 /* FIXME: This needs a cache, especially for generic instances, since
477 * mono_metadata_parse_type () allocates everything from a mempool.
479 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
481 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
482 if (sig_type == NULL) {
483 mono_loader_set_error_field_load (klass, fname);
486 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
489 mono_class_init (klass); /*FIXME is this really necessary?*/
492 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
495 mono_loader_set_error_field_load (klass, fname);
501 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
502 MonoGenericContext *context)
506 MonoClassField *field;
508 if (image->dynamic) {
509 MonoClassField *result;
510 MonoClass *handle_class;
513 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
514 // This checks the memberref type as well
515 if (!result || handle_class != mono_defaults.fieldhandle_class) {
516 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field token 0x%08x on image %s.", token, image->name));
519 *retklass = result->parent;
524 if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
525 *retklass = field->parent;
526 mono_loader_unlock ();
529 mono_loader_unlock ();
531 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
532 field = field_from_memberref (image, token, retklass, context);
534 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
537 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
543 field = mono_class_get_field (k, token);
547 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
548 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
549 mono_loader_unlock ();
554 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
558 if (sig1->hasthis != sig2->hasthis ||
559 sig1->sentinelpos != sig2->sentinelpos)
562 for (i = 0; i < sig1->sentinelpos; i++) {
563 MonoType *p1 = sig1->params[i];
564 MonoType *p2 = sig2->params[i];
566 /*if (p1->attrs != p2->attrs)
569 if (!mono_metadata_type_equal (p1, p2))
573 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
579 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
580 MonoMethodSignature *sig, MonoClass *from_class)
584 /* Search directly in the metadata to avoid calling setup_methods () */
586 /* FIXME: !from_class->generic_class condition causes test failures. */
587 if (klass->type_token && !klass->image->dynamic && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
588 for (i = 0; i < klass->method.count; ++i) {
589 guint32 cols [MONO_METHOD_SIZE];
592 MonoMethodSignature *other_sig;
594 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
596 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
598 if (!((fqname && !strcmp (m_name, fqname)) ||
599 (qname && !strcmp (m_name, qname)) ||
600 (name && !strcmp (m_name, name))))
603 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
604 other_sig = mono_method_signature (method);
605 if (method && other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
610 mono_class_setup_methods (klass);
612 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
613 See mono/tests/generic-type-load-exception.2.il
614 FIXME we should better report this error to the caller
618 for (i = 0; i < klass->method.count; ++i) {
619 MonoMethod *m = klass->methods [i];
620 MonoMethodSignature *msig;
622 if (!((fqname && !strcmp (m->name, fqname)) ||
623 (qname && !strcmp (m->name, qname)) ||
624 (name && !strcmp (m->name, name))))
626 msig = mono_method_signature (m);
630 if (sig->call_convention == MONO_CALL_VARARG) {
631 if (mono_metadata_signature_vararg_match (sig, msig))
634 if (mono_metadata_signature_equal (sig, msig))
639 if (i < klass->method.count)
640 return mono_class_get_method_by_index (from_class, i);
645 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
648 char *qname, *fqname, *class_name;
649 gboolean is_interface;
650 MonoMethod *result = NULL;
652 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
655 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
657 qname = g_strconcat (class_name, ".", name, NULL);
658 if (ic->name_space && ic->name_space [0])
659 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
663 class_name = qname = fqname = NULL;
666 g_assert (from_class);
667 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
671 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
674 g_assert (from_class->interface_offsets_count == in_class->interface_offsets_count);
675 for (i = 0; i < in_class->interface_offsets_count; i++) {
676 MonoClass *in_ic = in_class->interfaces_packed [i];
677 MonoClass *from_ic = from_class->interfaces_packed [i];
678 char *ic_qname, *ic_fqname, *ic_class_name;
680 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
681 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
682 if (in_ic->name_space && in_ic->name_space [0])
683 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
687 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic);
688 g_free (ic_class_name);
695 in_class = in_class->parent;
696 from_class = from_class->parent;
698 g_assert (!in_class == !from_class);
701 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
710 static MonoMethodSignature*
711 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
713 MonoMethodSignature *res;
717 mono_error_init (error);
721 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
722 res->param_count = sig->param_count;
723 res->sentinelpos = -1;
724 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
725 if (!mono_error_ok (error))
727 is_open = mono_class_is_open_constructed_type (res->ret);
728 for (i = 0; i < sig->param_count; ++i) {
729 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
730 if (!mono_error_ok (error))
734 is_open = mono_class_is_open_constructed_type (res->params [i]);
736 res->hasthis = sig->hasthis;
737 res->explicit_this = sig->explicit_this;
738 res->call_convention = sig->call_convention;
739 res->pinvoke = sig->pinvoke;
740 res->generic_param_count = sig->generic_param_count;
741 res->sentinelpos = sig->sentinelpos;
742 res->has_type_parameters = is_open;
743 res->is_inflated = 1;
748 mono_metadata_free_type (res->ret);
749 for (i = 0; i < sig->param_count; ++i) {
751 mono_metadata_free_type (res->params [i]);
757 static MonoMethodHeader*
758 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
760 MonoMethodHeader *res;
762 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
763 res->code = header->code;
764 res->code_size = header->code_size;
765 res->max_stack = header->max_stack;
766 res->num_clauses = header->num_clauses;
767 res->init_locals = header->init_locals;
768 res->num_locals = header->num_locals;
769 res->clauses = header->clauses;
770 for (i = 0; i < header->num_locals; ++i)
771 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
772 if (res->num_clauses) {
773 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
774 for (i = 0; i < header->num_clauses; ++i) {
775 MonoExceptionClause *clause = &res->clauses [i];
776 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
778 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
785 * token is the method_ref/def/spec token used in a call IL instruction.
788 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
790 int table = mono_metadata_token_table (token);
791 int idx = mono_metadata_token_index (token);
793 guint32 cols [MONO_MEMBERREF_SIZE];
794 MonoMethodSignature *sig;
797 /* !table is for wrappers: we should really assign their own token to them */
798 if (!table || table == MONO_TABLE_METHOD)
799 return mono_method_signature (method);
801 if (table == MONO_TABLE_METHODSPEC) {
802 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
803 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
806 return mono_method_signature (method);
809 if (method->klass->generic_class)
810 return mono_method_signature (method);
812 if (image->dynamic) {
813 sig = mono_reflection_lookup_signature (image, method, token);
815 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
816 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
818 sig = find_cached_memberref_sig (image, sig_idx);
820 if (!mono_verifier_verify_memberref_signature (image, sig_idx, NULL)) {
821 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
822 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
824 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));
828 ptr = mono_metadata_blob_heap (image, sig_idx);
829 mono_metadata_decode_blob_size (ptr, &ptr);
830 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
833 sig = cache_memberref_sig (image, sig_idx, sig);
835 /* FIXME: we probably should verify signature compat in the dynamic case too*/
836 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
837 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
838 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
840 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));
848 MonoMethodSignature *cached;
850 /* This signature is not owned by a MonoMethod, so need to cache */
851 sig = inflate_generic_signature_checked (image, sig, context, &error);
852 if (!mono_error_ok (&error)) {/*XXX bubble up this and kill one use of loader errors */
853 mono_loader_set_error_bad_image (g_strdup_printf ("Could not inflate signature %s", mono_error_get_message (&error)));
854 mono_error_cleanup (&error);
858 cached = mono_metadata_get_inflated_signature (sig, context);
860 mono_metadata_free_inflated_signature (sig);
862 inflated_signatures_size += mono_metadata_signature_size (cached);
870 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
872 return mono_method_get_signature_full (method, image, token, NULL);
875 /* this is only for the typespec array methods */
877 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
881 mono_class_setup_methods (klass);
882 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
883 for (i = 0; i < klass->method.count; ++i) {
884 MonoMethod *method = klass->methods [i];
885 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
892 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
893 gboolean *used_context)
895 MonoClass *klass = NULL;
896 MonoMethod *method = NULL;
897 MonoTableInfo *tables = image->tables;
899 guint32 nindex, class, sig_idx;
901 MonoMethodSignature *sig;
904 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
905 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
906 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
907 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
908 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
910 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
913 * Whether we actually used the `typespec_context' or not.
914 * This is used to tell our caller whether or not it's safe to insert the returned
915 * method into a cache.
918 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
921 case MONO_MEMBERREF_PARENT_TYPEREF:
922 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
924 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
925 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
926 mono_loader_set_error_type_load (name, image->assembly_name);
931 case MONO_MEMBERREF_PARENT_TYPESPEC:
933 * Parse the TYPESPEC in the parent's context.
935 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
937 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
938 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
939 mono_loader_set_error_type_load (name, image->assembly_name);
944 case MONO_MEMBERREF_PARENT_TYPEDEF:
945 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
947 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
948 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
949 mono_loader_set_error_type_load (name, image->assembly_name);
954 case MONO_MEMBERREF_PARENT_METHODDEF:
955 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
959 /* This message leaks */
960 char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
961 mono_loader_set_error_method_load ("", message);
967 mono_class_init (klass);
969 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
971 if (!mono_verifier_verify_memberref_signature (image, sig_idx, NULL)) {
972 mono_loader_set_error_method_load (klass->name, mname);
976 ptr = mono_metadata_blob_heap (image, sig_idx);
977 mono_metadata_decode_blob_size (ptr, &ptr);
979 sig = find_cached_memberref_sig (image, sig_idx);
981 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
985 sig = cache_memberref_sig (image, sig_idx, sig);
989 case MONO_MEMBERREF_PARENT_TYPEREF:
990 case MONO_MEMBERREF_PARENT_TYPEDEF:
991 method = find_method (klass, NULL, mname, sig, klass);
994 case MONO_MEMBERREF_PARENT_TYPESPEC: {
997 type = &klass->byval_arg;
999 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1000 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1001 method = find_method (in_class, NULL, mname, sig, klass);
1005 /* we're an array and we created these methods already in klass in mono_class_init () */
1006 method = mono_method_search_in_array_class (klass, mname, sig);
1010 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
1011 g_assert_not_reached ();
1015 char *msig = mono_signature_get_desc (sig, FALSE);
1016 char * class_name = mono_type_get_name (&klass->byval_arg);
1017 GString *s = g_string_new (mname);
1018 if (sig->generic_param_count)
1019 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1020 g_string_append_printf (s, "(%s)", msig);
1022 msig = g_string_free (s, FALSE);
1025 "Missing method %s::%s in assembly %s, referenced in assembly %s",
1026 class_name, msig, klass->image->name, image->name);
1027 mono_loader_set_error_method_load (class_name, mname);
1029 g_free (class_name);
1036 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
1041 MonoTableInfo *tables = image->tables;
1042 MonoGenericContext new_context;
1043 MonoGenericInst *inst;
1045 guint32 cols [MONO_METHODSPEC_SIZE];
1046 guint32 token, nindex, param_count;
1048 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1049 token = cols [MONO_METHODSPEC_METHOD];
1050 nindex = token >> MONO_METHODDEFORREF_BITS;
1052 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL))
1055 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1057 mono_metadata_decode_value (ptr, &ptr);
1059 param_count = mono_metadata_decode_value (ptr, &ptr);
1060 g_assert (param_count);
1062 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1063 if (context && inst->is_open) {
1064 inst = mono_metadata_inflate_generic_inst (inst, context, &error);
1065 if (!mono_error_ok (&error)) {
1066 mono_error_cleanup (&error); /*FIXME don't swallow error message.*/
1071 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
1072 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
1074 method = method_from_memberref (image, nindex, context, NULL);
1079 klass = method->klass;
1081 if (klass->generic_class) {
1082 g_assert (method->is_inflated);
1083 method = ((MonoMethodInflated *) method)->declaring;
1086 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1087 new_context.method_inst = inst;
1089 return mono_class_inflate_generic_method_full (method, klass, &new_context);
1092 struct _MonoDllMap {
1100 static MonoDllMap *global_dll_map;
1103 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1111 mono_loader_lock ();
1114 * we use the first entry we find that matches, since entries from
1115 * the config file are prepended to the list and we document that the
1116 * later entries win.
1118 for (; dll_map; dll_map = dll_map->next) {
1119 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1120 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1122 } else if (strcmp (dll_map->dll, dll)) {
1125 if (!found && dll_map->target) {
1126 *rdll = dll_map->target;
1128 /* we don't quit here, because we could find a full
1129 * entry that matches also function and that has priority.
1132 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1133 *rfunc = dll_map->target_func;
1138 mono_loader_unlock ();
1143 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1146 if (assembly && assembly->dll_map) {
1147 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1151 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1155 * mono_dllmap_insert:
1157 * LOCKING: Acquires the loader lock.
1159 * NOTE: This can be called before the runtime is initialized, for example from
1160 * mono_config_parse ().
1163 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1167 mono_loader_init ();
1169 mono_loader_lock ();
1172 entry = g_malloc0 (sizeof (MonoDllMap));
1173 entry->dll = dll? g_strdup (dll): NULL;
1174 entry->target = tdll? g_strdup (tdll): NULL;
1175 entry->func = func? g_strdup (func): NULL;
1176 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1177 entry->next = global_dll_map;
1178 global_dll_map = entry;
1180 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1181 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1182 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1183 entry->func = func? mono_image_strdup (assembly, func): NULL;
1184 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1185 entry->next = assembly->dll_map;
1186 assembly->dll_map = entry;
1189 mono_loader_unlock ();
1192 static GHashTable *global_module_map;
1195 cached_module_load (const char *name, int flags, char **err)
1201 mono_loader_lock ();
1202 if (!global_module_map)
1203 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1204 res = g_hash_table_lookup (global_module_map, name);
1206 mono_loader_unlock ();
1209 res = mono_dl_open (name, flags, NULL);
1211 g_hash_table_insert (global_module_map, g_strdup (name), res);
1212 mono_loader_unlock ();
1217 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1219 MonoImage *image = method->klass->image;
1220 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1221 MonoTableInfo *tables = image->tables;
1222 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1223 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1224 guint32 im_cols [MONO_IMPLMAP_SIZE];
1225 guint32 scope_token;
1226 const char *import = NULL;
1227 const char *orig_scope;
1228 const char *new_scope;
1230 char *full_name, *file_name;
1232 MonoDl *module = NULL;
1234 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1237 return piinfo->addr;
1239 if (method->klass->image->dynamic) {
1240 MonoReflectionMethodAux *method_aux =
1241 g_hash_table_lookup (
1242 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1246 import = method_aux->dllentry;
1247 orig_scope = method_aux->dll;
1250 if (!piinfo->implmap_idx)
1253 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1255 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1256 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1257 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1258 orig_scope = mono_metadata_string_heap (image, scope_token);
1261 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1263 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1264 "DllImport attempting to load: '%s'.", new_scope);
1271 /* we allow a special name to dlopen from the running process namespace */
1272 if (strcmp (new_scope, "__Internal") == 0)
1273 module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1276 * Try loading the module using a variety of names
1278 for (i = 0; i < 4; ++i) {
1281 /* Try the original name */
1282 file_name = g_strdup (new_scope);
1285 /* Try trimming the .dll extension */
1286 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1287 file_name = g_strdup (new_scope);
1288 file_name [strlen (new_scope) - 4] = '\0';
1294 if (strstr (new_scope, "lib") != new_scope) {
1295 file_name = g_strdup_printf ("lib%s", new_scope);
1301 #ifndef TARGET_WIN32
1302 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1303 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1304 !g_ascii_strcasecmp ("user32", new_scope) ||
1305 !g_ascii_strcasecmp ("kernel", new_scope)) {
1306 file_name = g_strdup ("libMonoSupportW.so");
1310 #ifndef TARGET_WIN32
1317 while ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {
1318 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1319 "DllImport loading location: '%s'.", full_name);
1320 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1322 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1323 "DllImport error loading library: '%s'.",
1335 while ((full_name = mono_dl_build_path (".", file_name, &iter))) {
1336 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1337 "DllImport loading library: '%s'.", full_name);
1338 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1340 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1341 "DllImport error loading library '%s'.",
1352 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1353 "DllImport loading: '%s'.", file_name);
1354 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1356 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1357 "DllImport error loading library '%s'.",
1369 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1370 "DllImport unable to load library '%s'.",
1375 *exc_class = "DllNotFoundException";
1376 *exc_arg = new_scope;
1381 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1382 "Searching for '%s'.", import);
1384 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1385 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1387 char *mangled_name = NULL, *mangled_name2 = NULL;
1390 int mangle_param_count;
1396 * Search using a variety of mangled names
1398 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1399 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1400 gboolean need_param_count = FALSE;
1402 if (mangle_stdcall > 0)
1403 need_param_count = TRUE;
1405 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1410 mangled_name = (char*)import;
1411 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1412 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1413 /* Try the mangled name first */
1414 if (mangle_charset == 0)
1415 mangled_name = g_strconcat (import, "W", NULL);
1417 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1419 if (mangle_charset == 0)
1420 mangled_name = g_strconcat (import, "W", NULL);
1422 /* Try the mangled name last */
1423 if (mangle_charset == 1)
1424 mangled_name = g_strconcat (import, "A", NULL);
1427 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1429 /* Try the mangled name last */
1430 if (mangle_charset == 1)
1431 mangled_name = g_strconcat (import, "A", NULL);
1436 if (mangle_param_count == 0)
1437 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1439 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1440 param_count = mangle_param_count;
1442 /* Try the stdcall mangled name */
1444 * gcc under windows creates mangled names without the underscore, but MS.NET
1445 * doesn't support it, so we doesn't support it either.
1447 if (mangle_stdcall == 1)
1448 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1450 mangled_name2 = mangled_name;
1452 mangled_name2 = mangled_name;
1455 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1456 "Probing '%s'.", mangled_name2);
1458 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1461 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1462 "Found as '%s'.", mangled_name2);
1464 if (mangled_name != mangled_name2)
1465 g_free (mangled_name2);
1466 if (mangled_name != import)
1467 g_free (mangled_name);
1473 if (!piinfo->addr) {
1476 *exc_class = "EntryPointNotFoundException";
1481 return piinfo->addr;
1485 * LOCKING: assumes the loader lock to be taken.
1488 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1489 MonoGenericContext *context, gboolean *used_context)
1492 int table = mono_metadata_token_table (token);
1493 int idx = mono_metadata_token_index (token);
1494 MonoTableInfo *tables = image->tables;
1495 MonoGenericContainer *generic_container = NULL, *container = NULL;
1496 const char *sig = NULL;
1498 guint32 cols [MONO_TYPEDEF_SIZE];
1500 if (image->dynamic) {
1501 MonoClass *handle_class;
1503 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1504 // This checks the memberref type as well
1505 if (result && handle_class != mono_defaults.methodhandle_class) {
1506 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1512 if (table != MONO_TABLE_METHOD) {
1513 if (table == MONO_TABLE_METHODSPEC) {
1514 if (used_context) *used_context = TRUE;
1515 return method_from_methodspec (image, context, idx);
1517 if (table != MONO_TABLE_MEMBERREF) {
1518 g_warning ("got wrong token: 0x%08x\n", token);
1519 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1522 return method_from_memberref (image, idx, context, used_context);
1525 if (used_context) *used_context = FALSE;
1527 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1528 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1532 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1534 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1535 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1536 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1538 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1540 mono_stats.method_count ++;
1542 if (!klass) { /*FIXME put this before the image alloc*/
1543 guint32 type = mono_metadata_typedef_from_method (image, token);
1546 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1552 result->klass = klass;
1553 result->flags = cols [2];
1554 result->iflags = cols [1];
1555 result->token = token;
1556 result->name = mono_metadata_string_heap (image, cols [3]);
1558 if (!sig) /* already taken from the methodref */
1559 sig = mono_metadata_blob_heap (image, cols [4]);
1560 size = mono_metadata_decode_blob_size (sig, &sig);
1562 container = klass->generic_container;
1565 * load_generic_params does a binary search so only call it if the method
1569 generic_container = mono_metadata_load_generic_params (image, token, container);
1570 if (generic_container) {
1571 result->is_generic = TRUE;
1572 generic_container->owner.method = result;
1573 /*FIXME put this before the image alloc*/
1574 if (!mono_metadata_load_generic_param_constraints_full (image, token, generic_container))
1577 container = generic_container;
1580 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1581 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1582 result->string_ctor = 1;
1583 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1584 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1587 /* IJW is P/Invoke with a predefined function pointer. */
1588 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1589 piinfo->addr = mono_image_rva_map (image, cols [0]);
1590 g_assert (piinfo->addr);
1593 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1594 /* Native methods can have no map. */
1595 if (piinfo->implmap_idx)
1596 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1599 if (generic_container)
1600 mono_method_set_generic_container (result, generic_container);
1606 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1608 return mono_get_method_full (image, token, klass, NULL);
1612 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1613 MonoGenericContext *context)
1616 gboolean used_context = FALSE;
1618 /* We do everything inside the lock to prevent creation races */
1620 mono_image_lock (image);
1622 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1623 if (!image->method_cache)
1624 image->method_cache = g_hash_table_new (NULL, NULL);
1625 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1627 if (!image->methodref_cache)
1628 image->methodref_cache = g_hash_table_new (NULL, NULL);
1629 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1631 mono_image_unlock (image);
1636 result = mono_get_method_from_token (image, token, klass, context, &used_context);
1640 mono_image_lock (image);
1641 if (!used_context && !result->is_inflated) {
1642 MonoMethod *result2;
1643 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1644 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1646 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1649 mono_image_unlock (image);
1653 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1654 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1656 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1659 mono_image_unlock (image);
1665 * mono_get_method_constrained:
1667 * This is used when JITing the `constrained.' opcode.
1669 * This returns two values: the contrained method, which has been inflated
1670 * as the function return value; And the original CIL-stream method as
1671 * declared in cil_method. The later is used for verification.
1674 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1675 MonoGenericContext *context, MonoMethod **cil_method)
1677 MonoMethod *method, *result;
1678 MonoClass *ic = NULL;
1679 MonoGenericContext *method_context = NULL;
1680 MonoMethodSignature *sig, *original_sig;
1682 mono_loader_lock ();
1684 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL);
1686 mono_loader_unlock ();
1690 mono_class_init (constrained_class);
1691 method = *cil_method;
1692 original_sig = sig = mono_method_signature (method);
1694 mono_loader_unlock ();
1698 if (method->is_inflated && sig->generic_param_count) {
1699 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1700 sig = mono_method_signature (imethod->declaring); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1701 method_context = mono_method_get_context (method);
1705 * We must inflate the signature with the class instantiation to work on
1706 * cases where a class inherit from a generic type and the override replaces
1707 * any type argument which a concrete type. See #325283.
1709 if (method_context->class_inst) {
1711 MonoGenericContext ctx;
1712 ctx.method_inst = NULL;
1713 ctx.class_inst = method_context->class_inst;
1714 /*Fixme, property propagate this error*/
1715 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, &error);
1716 if (!mono_error_ok (&error)) {
1717 mono_loader_unlock ();
1718 mono_error_cleanup (&error);
1724 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1727 result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1728 if (sig != original_sig)
1729 mono_metadata_free_inflated_signature (sig);
1732 g_warning ("Missing method %s.%s.%s in assembly %s token %x", method->klass->name_space,
1733 method->klass->name, method->name, image->name, token);
1734 mono_loader_unlock ();
1739 result = mono_class_inflate_generic_method (result, method_context);
1741 mono_loader_unlock ();
1746 mono_free_method (MonoMethod *method)
1748 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1749 mono_profiler_method_free (method);
1751 /* FIXME: This hack will go away when the profiler will support freeing methods */
1752 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1755 if (method->signature) {
1757 * FIXME: This causes crashes because the types inside signatures and
1758 * locals are shared.
1760 /* mono_metadata_free_method_signature (method->signature); */
1761 /* g_free (method->signature); */
1764 if (method->dynamic) {
1765 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1768 mono_marshal_free_dynamic_wrappers (method);
1770 mono_image_property_remove (method->klass->image, method);
1772 g_free ((char*)method->name);
1774 g_free ((char*)mw->header->code);
1775 for (i = 0; i < mw->header->num_locals; ++i)
1776 g_free (mw->header->locals [i]);
1777 g_free (mw->header->clauses);
1778 g_free (mw->header);
1780 g_free (mw->method_data);
1781 g_free (method->signature);
1787 mono_method_get_param_names (MonoMethod *method, const char **names)
1791 MonoTableInfo *methodt;
1792 MonoTableInfo *paramt;
1793 MonoMethodSignature *signature;
1796 if (method->is_inflated)
1797 method = ((MonoMethodInflated *) method)->declaring;
1799 signature = mono_method_signature (method);
1800 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
1801 number of arguments and allocate a properly sized array. */
1802 if (signature == NULL)
1805 if (!signature->param_count)
1808 for (i = 0; i < signature->param_count; ++i)
1811 klass = method->klass;
1815 mono_class_init (klass);
1817 if (klass->image->dynamic) {
1818 MonoReflectionMethodAux *method_aux =
1819 g_hash_table_lookup (
1820 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1821 if (method_aux && method_aux->param_names) {
1822 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1823 if (method_aux->param_names [i + 1])
1824 names [i] = method_aux->param_names [i + 1];
1829 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1830 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1831 idx = mono_method_get_index (method);
1833 guint32 cols [MONO_PARAM_SIZE];
1836 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1838 if (idx < methodt->rows)
1839 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1841 lastp = paramt->rows + 1;
1842 for (i = param_index; i < lastp; ++i) {
1843 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1844 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
1845 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1851 mono_method_get_param_token (MonoMethod *method, int index)
1853 MonoClass *klass = method->klass;
1854 MonoTableInfo *methodt;
1857 mono_class_init (klass);
1859 if (klass->image->dynamic) {
1860 g_assert_not_reached ();
1863 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1864 idx = mono_method_get_index (method);
1866 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1870 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
1872 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1879 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1882 MonoClass *klass = method->klass;
1883 MonoTableInfo *methodt;
1884 MonoTableInfo *paramt;
1885 MonoMethodSignature *signature;
1888 signature = mono_method_signature (method);
1889 g_assert (signature); /*FIXME there is no way to signal error from this function*/
1891 for (i = 0; i < signature->param_count + 1; ++i)
1894 if (method->klass->image->dynamic) {
1895 MonoReflectionMethodAux *method_aux =
1896 g_hash_table_lookup (
1897 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1898 if (method_aux && method_aux->param_marshall) {
1899 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1900 for (i = 0; i < signature->param_count + 1; ++i)
1901 if (dyn_specs [i]) {
1902 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1903 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1904 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
1905 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
1911 mono_class_init (klass);
1913 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1914 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1915 idx = mono_method_get_index (method);
1917 guint32 cols [MONO_PARAM_SIZE];
1918 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1920 if (idx < methodt->rows)
1921 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1923 lastp = paramt->rows + 1;
1925 for (i = param_index; i < lastp; ++i) {
1926 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1928 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
1930 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1932 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1941 mono_method_has_marshal_info (MonoMethod *method)
1944 MonoClass *klass = method->klass;
1945 MonoTableInfo *methodt;
1946 MonoTableInfo *paramt;
1949 if (method->klass->image->dynamic) {
1950 MonoReflectionMethodAux *method_aux =
1951 g_hash_table_lookup (
1952 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1953 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1955 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1962 mono_class_init (klass);
1964 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1965 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1966 idx = mono_method_get_index (method);
1968 guint32 cols [MONO_PARAM_SIZE];
1969 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1971 if (idx + 1 < methodt->rows)
1972 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1974 lastp = paramt->rows + 1;
1976 for (i = param_index; i < lastp; ++i) {
1977 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1979 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1988 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1991 g_assert (method != NULL);
1992 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1994 if (method->is_inflated)
1995 method = ((MonoMethodInflated *) method)->declaring;
1996 data = ((MonoMethodWrapper *)method)->method_data;
1997 g_assert (data != NULL);
1998 g_assert (id <= GPOINTER_TO_UINT (*data));
2003 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
2004 g_error ("stack walk not installed");
2007 static MonoStackWalkImpl stack_walk = default_stack_walk;
2010 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2012 stack_walk (func, TRUE, user_data);
2016 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2018 stack_walk (func, FALSE, user_data);
2022 mono_install_stack_walk (MonoStackWalkImpl func)
2028 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2030 MonoMethod **dest = data;
2032 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2038 mono_method_get_last_managed (void)
2040 MonoMethod *m = NULL;
2041 stack_walk (last_managed, FALSE, &m);
2045 static gboolean loader_lock_track_ownership = FALSE;
2050 * See docs/thread-safety.txt for the locking strategy.
2053 mono_loader_lock (void)
2055 mono_locks_acquire (&loader_mutex, LoaderLock);
2056 if (G_UNLIKELY (loader_lock_track_ownership)) {
2057 TlsSetValue (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) + 1));
2062 mono_loader_unlock (void)
2064 mono_locks_release (&loader_mutex, LoaderLock);
2065 if (G_UNLIKELY (loader_lock_track_ownership)) {
2066 TlsSetValue (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) - 1));
2071 * mono_loader_lock_track_ownership:
2073 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2074 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2075 * thread owns the loader lock.
2078 mono_loader_lock_track_ownership (gboolean track)
2080 loader_lock_track_ownership = track;
2084 * mono_loader_lock_is_owned_by_self:
2086 * Return whenever the current thread owns the loader lock.
2087 * This is useful to avoid blocking operations while holding the loader lock.
2090 mono_loader_lock_is_owned_by_self (void)
2092 g_assert (loader_lock_track_ownership);
2094 return GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) > 0;
2098 * mono_loader_lock_if_inited:
2100 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2101 * be used in runtime initialization code which can be executed before mono_loader_init ().
2104 mono_loader_lock_if_inited (void)
2106 if (loader_lock_inited)
2107 mono_loader_lock ();
2111 mono_loader_unlock_if_inited (void)
2113 if (loader_lock_inited)
2114 mono_loader_unlock ();
2118 * mono_method_signature:
2120 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2122 MonoMethodSignature*
2123 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2129 gboolean can_cache_signature;
2130 MonoGenericContainer *container;
2131 MonoMethodSignature *signature = NULL;
2134 /* We need memory barriers below because of the double-checked locking pattern */
2136 mono_error_init (error);
2139 return m->signature;
2141 mono_loader_lock ();
2144 mono_loader_unlock ();
2145 return m->signature;
2148 if (m->is_inflated) {
2149 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2150 /* the lock is recursive */
2151 signature = mono_method_signature (imethod->declaring);
2152 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2153 if (!mono_error_ok (error)) {
2154 mono_loader_unlock ();
2158 inflated_signatures_size += mono_metadata_signature_size (signature);
2160 mono_memory_barrier ();
2161 m->signature = signature;
2162 mono_loader_unlock ();
2163 return m->signature;
2166 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2167 idx = mono_metadata_token_index (m->token);
2168 img = m->klass->image;
2170 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2172 g_assert (!m->klass->generic_class);
2173 container = mono_method_get_generic_container (m);
2175 container = m->klass->generic_container;
2177 /* Generic signatures depend on the container so they cannot be cached */
2178 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2179 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2181 /* If the method has parameter attributes, that can modify the signature */
2182 if (mono_metadata_method_has_param_attrs (img, idx))
2183 can_cache_signature = FALSE;
2185 if (can_cache_signature)
2186 signature = g_hash_table_lookup (img->method_signatures, sig);
2189 const char *sig_body;
2190 /*TODO we should cache the failure result somewhere*/
2191 if (!mono_verifier_verify_method_signature (img, sig_offset, NULL)) {
2192 mono_loader_unlock ();
2193 mono_error_set_method_load (error, m->klass, m->name, "");
2197 size = mono_metadata_decode_blob_size (sig, &sig_body);
2199 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
2201 mono_loader_unlock ();
2202 mono_error_set_method_load (error, m->klass, m->name, "");
2206 if (can_cache_signature)
2207 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2210 /* Verify metadata consistency */
2211 if (signature->generic_param_count) {
2212 if (!container || !container->is_method) {
2213 mono_loader_unlock ();
2214 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);
2217 if (container->type_argc != signature->generic_param_count) {
2218 mono_loader_unlock ();
2219 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);
2222 } else if (container && container->is_method && container->type_argc) {
2223 mono_loader_unlock ();
2224 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);
2227 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2228 signature->pinvoke = 1;
2229 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2230 MonoCallConvention conv = 0;
2231 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2232 signature->pinvoke = 1;
2234 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2235 case 0: /* no call conv, so using default */
2236 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2237 conv = MONO_CALL_DEFAULT;
2239 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2242 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2243 conv = MONO_CALL_STDCALL;
2245 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2246 conv = MONO_CALL_THISCALL;
2248 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2249 conv = MONO_CALL_FASTCALL;
2251 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2252 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2254 mono_loader_unlock ();
2255 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);
2258 signature->call_convention = conv;
2261 mono_memory_barrier ();
2262 m->signature = signature;
2264 mono_loader_unlock ();
2265 return m->signature;
2269 * mono_method_signature:
2271 * Return the signature of the method M. On failure, returns NULL.
2273 MonoMethodSignature*
2274 mono_method_signature (MonoMethod *m)
2277 MonoMethodSignature *sig;
2279 sig = mono_method_signature_checked (m, &error);
2281 g_warning ("Could not load signature due to: %s", mono_error_get_message (&error));
2282 mono_error_cleanup (&error);
2289 mono_method_get_name (MonoMethod *method)
2291 return method->name;
2295 mono_method_get_class (MonoMethod *method)
2297 return method->klass;
2301 mono_method_get_token (MonoMethod *method)
2303 return method->token;
2307 mono_method_get_header (MonoMethod *method)
2313 MonoMethodHeader *header;
2315 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))
2318 if (method->is_inflated) {
2319 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2320 MonoMethodHeader *header;
2322 mono_loader_lock ();
2324 if (imethod->header) {
2325 mono_loader_unlock ();
2326 return imethod->header;
2329 header = mono_method_get_header (imethod->declaring);
2333 imethod->header = inflate_generic_header (header, mono_method_get_context (method));
2334 mono_loader_unlock ();
2335 mono_metadata_free_mh (header);
2336 return imethod->header;
2339 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2340 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2341 g_assert (mw->header);
2346 * We don't need locks here: the new header is allocated from malloc memory
2347 * and is not stored anywhere in the runtime, the user needs to free it.
2349 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2350 idx = mono_metadata_token_index (method->token);
2351 img = method->klass->image;
2352 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2354 if (!mono_verifier_verify_method_header (img, rva, NULL))
2357 loc = mono_image_rva_map (img, rva);
2361 header = mono_metadata_parse_mh_full (img, mono_method_get_generic_container (method), loc);
2367 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2370 *iflags = method->iflags;
2371 return method->flags;
2375 * Find the method index in the metadata methodDef table.
2378 mono_method_get_index (MonoMethod *method) {
2379 MonoClass *klass = method->klass;
2383 return mono_metadata_token_index (method->token);
2385 mono_class_setup_methods (klass);
2386 if (klass->exception_type)
2388 for (i = 0; i < klass->method.count; ++i) {
2389 if (method == klass->methods [i]) {
2390 if (klass->image->uncompressed_metadata)
2391 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2393 return klass->method.first + i + 1;