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);
813 /* FIXME: This might be incorrect for vararg methods */
814 return mono_method_signature (method);
816 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
817 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
819 sig = find_cached_memberref_sig (image, sig_idx);
821 if (!mono_verifier_verify_memberref_signature (image, sig_idx, NULL)) {
822 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
823 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
825 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));
829 ptr = mono_metadata_blob_heap (image, sig_idx);
830 mono_metadata_decode_blob_size (ptr, &ptr);
831 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
834 sig = cache_memberref_sig (image, sig_idx, sig);
837 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
838 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
839 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
841 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));
847 MonoMethodSignature *cached;
849 /* This signature is not owned by a MonoMethod, so need to cache */
850 sig = inflate_generic_signature_checked (image, sig, context, &error);
851 if (!mono_error_ok (&error)) {/*XXX bubble up this and kill one use of loader errors */
852 mono_loader_set_error_bad_image (g_strdup_printf ("Could not inflate signature %s", mono_error_get_message (&error)));
853 mono_error_cleanup (&error);
857 cached = mono_metadata_get_inflated_signature (sig, context);
859 mono_metadata_free_inflated_signature (sig);
861 inflated_signatures_size += mono_metadata_signature_size (cached);
869 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
871 return mono_method_get_signature_full (method, image, token, NULL);
874 /* this is only for the typespec array methods */
876 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
880 mono_class_setup_methods (klass);
881 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
882 for (i = 0; i < klass->method.count; ++i) {
883 MonoMethod *method = klass->methods [i];
884 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
891 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
892 gboolean *used_context)
894 MonoClass *klass = NULL;
895 MonoMethod *method = NULL;
896 MonoTableInfo *tables = image->tables;
898 guint32 nindex, class, sig_idx;
900 MonoMethodSignature *sig;
903 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
904 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
905 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
906 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
907 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
909 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
912 * Whether we actually used the `typespec_context' or not.
913 * This is used to tell our caller whether or not it's safe to insert the returned
914 * method into a cache.
917 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
920 case MONO_MEMBERREF_PARENT_TYPEREF:
921 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
923 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
924 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
925 mono_loader_set_error_type_load (name, image->assembly_name);
930 case MONO_MEMBERREF_PARENT_TYPESPEC:
932 * Parse the TYPESPEC in the parent's context.
934 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
936 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
937 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
938 mono_loader_set_error_type_load (name, image->assembly_name);
943 case MONO_MEMBERREF_PARENT_TYPEDEF:
944 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
946 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
947 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
948 mono_loader_set_error_type_load (name, image->assembly_name);
953 case MONO_MEMBERREF_PARENT_METHODDEF:
954 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
958 /* This message leaks */
959 char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
960 mono_loader_set_error_method_load ("", message);
966 mono_class_init (klass);
968 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
970 if (!mono_verifier_verify_memberref_signature (image, sig_idx, NULL)) {
971 mono_loader_set_error_method_load (klass->name, mname);
975 ptr = mono_metadata_blob_heap (image, sig_idx);
976 mono_metadata_decode_blob_size (ptr, &ptr);
978 sig = find_cached_memberref_sig (image, sig_idx);
980 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
984 sig = cache_memberref_sig (image, sig_idx, sig);
988 case MONO_MEMBERREF_PARENT_TYPEREF:
989 case MONO_MEMBERREF_PARENT_TYPEDEF:
990 method = find_method (klass, NULL, mname, sig, klass);
993 case MONO_MEMBERREF_PARENT_TYPESPEC: {
996 type = &klass->byval_arg;
998 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
999 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1000 method = find_method (in_class, NULL, mname, sig, klass);
1004 /* we're an array and we created these methods already in klass in mono_class_init () */
1005 method = mono_method_search_in_array_class (klass, mname, sig);
1009 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
1010 g_assert_not_reached ();
1014 char *msig = mono_signature_get_desc (sig, FALSE);
1015 char * class_name = mono_type_get_name (&klass->byval_arg);
1016 GString *s = g_string_new (mname);
1017 if (sig->generic_param_count)
1018 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1019 g_string_append_printf (s, "(%s)", msig);
1021 msig = g_string_free (s, FALSE);
1024 "Missing method %s::%s in assembly %s, referenced in assembly %s",
1025 class_name, msig, klass->image->name, image->name);
1026 mono_loader_set_error_method_load (class_name, mname);
1028 g_free (class_name);
1035 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
1040 MonoTableInfo *tables = image->tables;
1041 MonoGenericContext new_context;
1042 MonoGenericInst *inst;
1044 guint32 cols [MONO_METHODSPEC_SIZE];
1045 guint32 token, nindex, param_count;
1047 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1048 token = cols [MONO_METHODSPEC_METHOD];
1049 nindex = token >> MONO_METHODDEFORREF_BITS;
1051 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL))
1054 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1056 mono_metadata_decode_value (ptr, &ptr);
1058 param_count = mono_metadata_decode_value (ptr, &ptr);
1059 g_assert (param_count);
1061 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1062 if (context && inst->is_open) {
1063 inst = mono_metadata_inflate_generic_inst (inst, context, &error);
1064 if (!mono_error_ok (&error)) {
1065 mono_error_cleanup (&error); /*FIXME don't swallow error message.*/
1070 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
1071 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
1073 method = method_from_memberref (image, nindex, context, NULL);
1078 klass = method->klass;
1080 if (klass->generic_class) {
1081 g_assert (method->is_inflated);
1082 method = ((MonoMethodInflated *) method)->declaring;
1085 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1086 new_context.method_inst = inst;
1088 return mono_class_inflate_generic_method_full (method, klass, &new_context);
1091 struct _MonoDllMap {
1099 static MonoDllMap *global_dll_map;
1102 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1110 mono_loader_lock ();
1113 * we use the first entry we find that matches, since entries from
1114 * the config file are prepended to the list and we document that the
1115 * later entries win.
1117 for (; dll_map; dll_map = dll_map->next) {
1118 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1119 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1121 } else if (strcmp (dll_map->dll, dll)) {
1124 if (!found && dll_map->target) {
1125 *rdll = dll_map->target;
1127 /* we don't quit here, because we could find a full
1128 * entry that matches also function and that has priority.
1131 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1132 *rfunc = dll_map->target_func;
1137 mono_loader_unlock ();
1142 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1145 if (assembly && assembly->dll_map) {
1146 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1150 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1154 * mono_dllmap_insert:
1156 * LOCKING: Acquires the loader lock.
1158 * NOTE: This can be called before the runtime is initialized, for example from
1159 * mono_config_parse ().
1162 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1166 mono_loader_init ();
1168 mono_loader_lock ();
1171 entry = g_malloc0 (sizeof (MonoDllMap));
1172 entry->dll = dll? g_strdup (dll): NULL;
1173 entry->target = tdll? g_strdup (tdll): NULL;
1174 entry->func = func? g_strdup (func): NULL;
1175 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1176 entry->next = global_dll_map;
1177 global_dll_map = entry;
1179 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1180 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1181 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1182 entry->func = func? mono_image_strdup (assembly, func): NULL;
1183 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1184 entry->next = assembly->dll_map;
1185 assembly->dll_map = entry;
1188 mono_loader_unlock ();
1191 static GHashTable *global_module_map;
1194 cached_module_load (const char *name, int flags, char **err)
1200 mono_loader_lock ();
1201 if (!global_module_map)
1202 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1203 res = g_hash_table_lookup (global_module_map, name);
1205 mono_loader_unlock ();
1208 res = mono_dl_open (name, flags, NULL);
1210 g_hash_table_insert (global_module_map, g_strdup (name), res);
1211 mono_loader_unlock ();
1216 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1218 MonoImage *image = method->klass->image;
1219 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1220 MonoTableInfo *tables = image->tables;
1221 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1222 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1223 guint32 im_cols [MONO_IMPLMAP_SIZE];
1224 guint32 scope_token;
1225 const char *import = NULL;
1226 const char *orig_scope;
1227 const char *new_scope;
1229 char *full_name, *file_name;
1231 MonoDl *module = NULL;
1233 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1236 return piinfo->addr;
1238 if (method->klass->image->dynamic) {
1239 MonoReflectionMethodAux *method_aux =
1240 g_hash_table_lookup (
1241 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1245 import = method_aux->dllentry;
1246 orig_scope = method_aux->dll;
1249 if (!piinfo->implmap_idx)
1252 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1254 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1255 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1256 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1257 orig_scope = mono_metadata_string_heap (image, scope_token);
1260 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1262 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1263 "DllImport attempting to load: '%s'.", new_scope);
1270 /* we allow a special name to dlopen from the running process namespace */
1271 if (strcmp (new_scope, "__Internal") == 0)
1272 module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1275 * Try loading the module using a variety of names
1277 for (i = 0; i < 4; ++i) {
1280 /* Try the original name */
1281 file_name = g_strdup (new_scope);
1284 /* Try trimming the .dll extension */
1285 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1286 file_name = g_strdup (new_scope);
1287 file_name [strlen (new_scope) - 4] = '\0';
1293 if (strstr (new_scope, "lib") != new_scope) {
1294 file_name = g_strdup_printf ("lib%s", new_scope);
1300 #ifndef TARGET_WIN32
1301 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1302 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1303 !g_ascii_strcasecmp ("user32", new_scope) ||
1304 !g_ascii_strcasecmp ("kernel", new_scope)) {
1305 file_name = g_strdup ("libMonoSupportW.so");
1309 #ifndef TARGET_WIN32
1316 while ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {
1317 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1318 "DllImport loading location: '%s'.", full_name);
1319 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1321 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1322 "DllImport error loading library: '%s'.",
1334 while ((full_name = mono_dl_build_path (".", file_name, &iter))) {
1335 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1336 "DllImport loading library: '%s'.", full_name);
1337 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1339 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1340 "DllImport error loading library '%s'.",
1351 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1352 "DllImport loading: '%s'.", file_name);
1353 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1355 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1356 "DllImport error loading library '%s'.",
1368 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1369 "DllImport unable to load library '%s'.",
1374 *exc_class = "DllNotFoundException";
1375 *exc_arg = new_scope;
1380 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1381 "Searching for '%s'.", import);
1383 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1384 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1386 char *mangled_name = NULL, *mangled_name2 = NULL;
1389 int mangle_param_count;
1395 * Search using a variety of mangled names
1397 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1398 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1399 gboolean need_param_count = FALSE;
1401 if (mangle_stdcall > 0)
1402 need_param_count = TRUE;
1404 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1409 mangled_name = (char*)import;
1410 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1411 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1412 /* Try the mangled name first */
1413 if (mangle_charset == 0)
1414 mangled_name = g_strconcat (import, "W", NULL);
1416 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1418 if (mangle_charset == 0)
1419 mangled_name = g_strconcat (import, "W", NULL);
1421 /* Try the mangled name last */
1422 if (mangle_charset == 1)
1423 mangled_name = g_strconcat (import, "A", NULL);
1426 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1428 /* Try the mangled name last */
1429 if (mangle_charset == 1)
1430 mangled_name = g_strconcat (import, "A", NULL);
1435 if (mangle_param_count == 0)
1436 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1438 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1439 param_count = mangle_param_count;
1441 /* Try the stdcall mangled name */
1443 * gcc under windows creates mangled names without the underscore, but MS.NET
1444 * doesn't support it, so we doesn't support it either.
1446 if (mangle_stdcall == 1)
1447 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1449 mangled_name2 = mangled_name;
1451 mangled_name2 = mangled_name;
1454 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1455 "Probing '%s'.", mangled_name2);
1457 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1460 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1461 "Found as '%s'.", mangled_name2);
1463 if (mangled_name != mangled_name2)
1464 g_free (mangled_name2);
1465 if (mangled_name != import)
1466 g_free (mangled_name);
1472 if (!piinfo->addr) {
1475 *exc_class = "EntryPointNotFoundException";
1480 return piinfo->addr;
1484 * LOCKING: assumes the loader lock to be taken.
1487 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1488 MonoGenericContext *context, gboolean *used_context)
1491 int table = mono_metadata_token_table (token);
1492 int idx = mono_metadata_token_index (token);
1493 MonoTableInfo *tables = image->tables;
1494 MonoGenericContainer *generic_container = NULL, *container = NULL;
1495 const char *sig = NULL;
1497 guint32 cols [MONO_TYPEDEF_SIZE];
1499 if (image->dynamic) {
1500 MonoClass *handle_class;
1502 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1503 // This checks the memberref type as well
1504 if (result && handle_class != mono_defaults.methodhandle_class) {
1505 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1511 if (table != MONO_TABLE_METHOD) {
1512 if (table == MONO_TABLE_METHODSPEC) {
1513 if (used_context) *used_context = TRUE;
1514 return method_from_methodspec (image, context, idx);
1516 if (table != MONO_TABLE_MEMBERREF) {
1517 g_warning ("got wrong token: 0x%08x\n", token);
1518 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1521 return method_from_memberref (image, idx, context, used_context);
1524 if (used_context) *used_context = FALSE;
1526 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1527 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1531 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1533 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1534 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1535 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1537 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1539 mono_stats.method_count ++;
1541 if (!klass) { /*FIXME put this before the image alloc*/
1542 guint32 type = mono_metadata_typedef_from_method (image, token);
1545 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1551 result->klass = klass;
1552 result->flags = cols [2];
1553 result->iflags = cols [1];
1554 result->token = token;
1555 result->name = mono_metadata_string_heap (image, cols [3]);
1557 if (!sig) /* already taken from the methodref */
1558 sig = mono_metadata_blob_heap (image, cols [4]);
1559 size = mono_metadata_decode_blob_size (sig, &sig);
1561 container = klass->generic_container;
1564 * load_generic_params does a binary search so only call it if the method
1568 generic_container = mono_metadata_load_generic_params (image, token, container);
1569 if (generic_container) {
1570 result->is_generic = TRUE;
1571 generic_container->owner.method = result;
1572 /*FIXME put this before the image alloc*/
1573 if (!mono_metadata_load_generic_param_constraints_full (image, token, generic_container))
1576 container = generic_container;
1579 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1580 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1581 result->string_ctor = 1;
1582 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1583 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1586 /* IJW is P/Invoke with a predefined function pointer. */
1587 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1588 piinfo->addr = mono_image_rva_map (image, cols [0]);
1589 g_assert (piinfo->addr);
1592 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1593 /* Native methods can have no map. */
1594 if (piinfo->implmap_idx)
1595 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1598 if (generic_container)
1599 mono_method_set_generic_container (result, generic_container);
1605 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1607 return mono_get_method_full (image, token, klass, NULL);
1611 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1612 MonoGenericContext *context)
1615 gboolean used_context = FALSE;
1617 /* We do everything inside the lock to prevent creation races */
1619 mono_image_lock (image);
1621 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1622 if (!image->method_cache)
1623 image->method_cache = g_hash_table_new (NULL, NULL);
1624 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1626 if (!image->methodref_cache)
1627 image->methodref_cache = g_hash_table_new (NULL, NULL);
1628 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1630 mono_image_unlock (image);
1635 result = mono_get_method_from_token (image, token, klass, context, &used_context);
1639 mono_image_lock (image);
1640 if (!used_context && !result->is_inflated) {
1641 MonoMethod *result2;
1642 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1643 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1645 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1648 mono_image_unlock (image);
1652 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1653 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1655 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1658 mono_image_unlock (image);
1664 * mono_get_method_constrained:
1666 * This is used when JITing the `constrained.' opcode.
1668 * This returns two values: the contrained method, which has been inflated
1669 * as the function return value; And the original CIL-stream method as
1670 * declared in cil_method. The later is used for verification.
1673 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1674 MonoGenericContext *context, MonoMethod **cil_method)
1676 MonoMethod *method, *result;
1677 MonoClass *ic = NULL;
1678 MonoGenericContext *method_context = NULL;
1679 MonoMethodSignature *sig, *original_sig;
1681 mono_loader_lock ();
1683 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL);
1685 mono_loader_unlock ();
1689 mono_class_init (constrained_class);
1690 method = *cil_method;
1691 original_sig = sig = mono_method_signature (method);
1693 mono_loader_unlock ();
1697 if (method->is_inflated && sig->generic_param_count) {
1698 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1699 sig = mono_method_signature (imethod->declaring); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1700 method_context = mono_method_get_context (method);
1704 * We must inflate the signature with the class instantiation to work on
1705 * cases where a class inherit from a generic type and the override replaces
1706 * any type argument which a concrete type. See #325283.
1708 if (method_context->class_inst) {
1710 MonoGenericContext ctx;
1711 ctx.method_inst = NULL;
1712 ctx.class_inst = method_context->class_inst;
1713 /*Fixme, property propagate this error*/
1714 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, &error);
1715 if (!mono_error_ok (&error)) {
1716 mono_loader_unlock ();
1717 mono_error_cleanup (&error);
1723 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1726 result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1727 if (sig != original_sig)
1728 mono_metadata_free_inflated_signature (sig);
1731 g_warning ("Missing method %s.%s.%s in assembly %s token %x", method->klass->name_space,
1732 method->klass->name, method->name, image->name, token);
1733 mono_loader_unlock ();
1738 result = mono_class_inflate_generic_method (result, method_context);
1740 mono_loader_unlock ();
1745 mono_free_method (MonoMethod *method)
1747 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1748 mono_profiler_method_free (method);
1750 /* FIXME: This hack will go away when the profiler will support freeing methods */
1751 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1754 if (method->signature) {
1756 * FIXME: This causes crashes because the types inside signatures and
1757 * locals are shared.
1759 /* mono_metadata_free_method_signature (method->signature); */
1760 /* g_free (method->signature); */
1763 if (method->dynamic) {
1764 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1767 mono_marshal_free_dynamic_wrappers (method);
1769 mono_image_property_remove (method->klass->image, method);
1771 g_free ((char*)method->name);
1773 g_free ((char*)mw->header->code);
1774 for (i = 0; i < mw->header->num_locals; ++i)
1775 g_free (mw->header->locals [i]);
1776 g_free (mw->header->clauses);
1777 g_free (mw->header);
1779 g_free (mw->method_data);
1780 g_free (method->signature);
1786 mono_method_get_param_names (MonoMethod *method, const char **names)
1790 MonoTableInfo *methodt;
1791 MonoTableInfo *paramt;
1792 MonoMethodSignature *signature;
1795 if (method->is_inflated)
1796 method = ((MonoMethodInflated *) method)->declaring;
1798 signature = mono_method_signature (method);
1799 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
1800 number of arguments and allocate a properly sized array. */
1801 if (signature == NULL)
1804 if (!signature->param_count)
1807 for (i = 0; i < signature->param_count; ++i)
1810 klass = method->klass;
1814 mono_class_init (klass);
1816 if (klass->image->dynamic) {
1817 MonoReflectionMethodAux *method_aux =
1818 g_hash_table_lookup (
1819 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1820 if (method_aux && method_aux->param_names) {
1821 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1822 if (method_aux->param_names [i + 1])
1823 names [i] = method_aux->param_names [i + 1];
1828 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1829 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1830 idx = mono_method_get_index (method);
1832 guint32 cols [MONO_PARAM_SIZE];
1835 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1837 if (idx < methodt->rows)
1838 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1840 lastp = paramt->rows + 1;
1841 for (i = param_index; i < lastp; ++i) {
1842 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1843 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
1844 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1850 mono_method_get_param_token (MonoMethod *method, int index)
1852 MonoClass *klass = method->klass;
1853 MonoTableInfo *methodt;
1856 mono_class_init (klass);
1858 if (klass->image->dynamic) {
1859 g_assert_not_reached ();
1862 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1863 idx = mono_method_get_index (method);
1865 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1869 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
1871 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1878 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1881 MonoClass *klass = method->klass;
1882 MonoTableInfo *methodt;
1883 MonoTableInfo *paramt;
1884 MonoMethodSignature *signature;
1887 signature = mono_method_signature (method);
1888 g_assert (signature); /*FIXME there is no way to signal error from this function*/
1890 for (i = 0; i < signature->param_count + 1; ++i)
1893 if (method->klass->image->dynamic) {
1894 MonoReflectionMethodAux *method_aux =
1895 g_hash_table_lookup (
1896 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1897 if (method_aux && method_aux->param_marshall) {
1898 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1899 for (i = 0; i < signature->param_count + 1; ++i)
1900 if (dyn_specs [i]) {
1901 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1902 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1903 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
1904 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
1910 mono_class_init (klass);
1912 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1913 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1914 idx = mono_method_get_index (method);
1916 guint32 cols [MONO_PARAM_SIZE];
1917 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1919 if (idx < methodt->rows)
1920 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1922 lastp = paramt->rows + 1;
1924 for (i = param_index; i < lastp; ++i) {
1925 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1927 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
1929 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1931 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1940 mono_method_has_marshal_info (MonoMethod *method)
1943 MonoClass *klass = method->klass;
1944 MonoTableInfo *methodt;
1945 MonoTableInfo *paramt;
1948 if (method->klass->image->dynamic) {
1949 MonoReflectionMethodAux *method_aux =
1950 g_hash_table_lookup (
1951 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1952 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1954 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1961 mono_class_init (klass);
1963 methodt = &klass->image->tables [MONO_TABLE_METHOD];
1964 paramt = &klass->image->tables [MONO_TABLE_PARAM];
1965 idx = mono_method_get_index (method);
1967 guint32 cols [MONO_PARAM_SIZE];
1968 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1970 if (idx + 1 < methodt->rows)
1971 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1973 lastp = paramt->rows + 1;
1975 for (i = param_index; i < lastp; ++i) {
1976 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1978 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1987 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1990 g_assert (method != NULL);
1991 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1993 if (method->is_inflated)
1994 method = ((MonoMethodInflated *) method)->declaring;
1995 data = ((MonoMethodWrapper *)method)->method_data;
1996 g_assert (data != NULL);
1997 g_assert (id <= GPOINTER_TO_UINT (*data));
2002 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
2003 g_error ("stack walk not installed");
2006 static MonoStackWalkImpl stack_walk = default_stack_walk;
2009 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2011 stack_walk (func, TRUE, user_data);
2015 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2017 stack_walk (func, FALSE, user_data);
2021 mono_install_stack_walk (MonoStackWalkImpl func)
2027 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2029 MonoMethod **dest = data;
2031 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2037 mono_method_get_last_managed (void)
2039 MonoMethod *m = NULL;
2040 stack_walk (last_managed, FALSE, &m);
2044 static gboolean loader_lock_track_ownership = FALSE;
2049 * See docs/thread-safety.txt for the locking strategy.
2052 mono_loader_lock (void)
2054 mono_locks_acquire (&loader_mutex, LoaderLock);
2055 if (G_UNLIKELY (loader_lock_track_ownership)) {
2056 TlsSetValue (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) + 1));
2061 mono_loader_unlock (void)
2063 mono_locks_release (&loader_mutex, LoaderLock);
2064 if (G_UNLIKELY (loader_lock_track_ownership)) {
2065 TlsSetValue (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) - 1));
2070 * mono_loader_lock_track_ownership:
2072 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2073 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2074 * thread owns the loader lock.
2077 mono_loader_lock_track_ownership (gboolean track)
2079 loader_lock_track_ownership = track;
2083 * mono_loader_lock_is_owned_by_self:
2085 * Return whenever the current thread owns the loader lock.
2086 * This is useful to avoid blocking operations while holding the loader lock.
2089 mono_loader_lock_is_owned_by_self (void)
2091 g_assert (loader_lock_track_ownership);
2093 return GPOINTER_TO_UINT (TlsGetValue (loader_lock_nest_id)) > 0;
2097 * mono_loader_lock_if_inited:
2099 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2100 * be used in runtime initialization code which can be executed before mono_loader_init ().
2103 mono_loader_lock_if_inited (void)
2105 if (loader_lock_inited)
2106 mono_loader_lock ();
2110 mono_loader_unlock_if_inited (void)
2112 if (loader_lock_inited)
2113 mono_loader_unlock ();
2117 * mono_method_signature:
2119 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2121 MonoMethodSignature*
2122 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2128 gboolean can_cache_signature;
2129 MonoGenericContainer *container;
2130 MonoMethodSignature *signature = NULL;
2133 /* We need memory barriers below because of the double-checked locking pattern */
2135 mono_error_init (error);
2138 return m->signature;
2140 mono_loader_lock ();
2143 mono_loader_unlock ();
2144 return m->signature;
2147 if (m->is_inflated) {
2148 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2149 /* the lock is recursive */
2150 signature = mono_method_signature (imethod->declaring);
2151 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2152 if (!mono_error_ok (error)) {
2153 mono_loader_unlock ();
2157 inflated_signatures_size += mono_metadata_signature_size (signature);
2159 mono_memory_barrier ();
2160 m->signature = signature;
2161 mono_loader_unlock ();
2162 return m->signature;
2165 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2166 idx = mono_metadata_token_index (m->token);
2167 img = m->klass->image;
2169 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2171 g_assert (!m->klass->generic_class);
2172 container = mono_method_get_generic_container (m);
2174 container = m->klass->generic_container;
2176 /* Generic signatures depend on the container so they cannot be cached */
2177 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2178 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2180 /* If the method has parameter attributes, that can modify the signature */
2181 if (mono_metadata_method_has_param_attrs (img, idx))
2182 can_cache_signature = FALSE;
2184 if (can_cache_signature)
2185 signature = g_hash_table_lookup (img->method_signatures, sig);
2188 const char *sig_body;
2189 /*TODO we should cache the failure result somewhere*/
2190 if (!mono_verifier_verify_method_signature (img, sig_offset, NULL)) {
2191 mono_loader_unlock ();
2192 mono_error_set_method_load (error, m->klass, m->name, "");
2196 size = mono_metadata_decode_blob_size (sig, &sig_body);
2198 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
2200 mono_loader_unlock ();
2201 mono_error_set_method_load (error, m->klass, m->name, "");
2205 if (can_cache_signature)
2206 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2209 /* Verify metadata consistency */
2210 if (signature->generic_param_count) {
2211 if (!container || !container->is_method) {
2212 mono_loader_unlock ();
2213 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);
2216 if (container->type_argc != signature->generic_param_count) {
2217 mono_loader_unlock ();
2218 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);
2221 } else if (container && container->is_method && container->type_argc) {
2222 mono_loader_unlock ();
2223 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);
2226 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2227 signature->pinvoke = 1;
2228 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2229 MonoCallConvention conv = 0;
2230 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2231 signature->pinvoke = 1;
2233 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2234 case 0: /* no call conv, so using default */
2235 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2236 conv = MONO_CALL_DEFAULT;
2238 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2241 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2242 conv = MONO_CALL_STDCALL;
2244 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2245 conv = MONO_CALL_THISCALL;
2247 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2248 conv = MONO_CALL_FASTCALL;
2250 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2251 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2253 mono_loader_unlock ();
2254 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);
2257 signature->call_convention = conv;
2260 mono_memory_barrier ();
2261 m->signature = signature;
2263 mono_loader_unlock ();
2264 return m->signature;
2268 * mono_method_signature:
2270 * Return the signature of the method M. On failure, returns NULL.
2272 MonoMethodSignature*
2273 mono_method_signature (MonoMethod *m)
2276 MonoMethodSignature *sig;
2278 sig = mono_method_signature_checked (m, &error);
2280 g_warning ("Could not load signature due to: %s", mono_error_get_message (&error));
2281 mono_error_cleanup (&error);
2288 mono_method_get_name (MonoMethod *method)
2290 return method->name;
2294 mono_method_get_class (MonoMethod *method)
2296 return method->klass;
2300 mono_method_get_token (MonoMethod *method)
2302 return method->token;
2306 mono_method_get_header (MonoMethod *method)
2312 MonoMethodHeader *header;
2314 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))
2317 if (method->is_inflated) {
2318 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2319 MonoMethodHeader *header;
2321 mono_loader_lock ();
2323 if (imethod->header) {
2324 mono_loader_unlock ();
2325 return imethod->header;
2328 header = mono_method_get_header (imethod->declaring);
2332 imethod->header = inflate_generic_header (header, mono_method_get_context (method));
2333 mono_loader_unlock ();
2334 mono_metadata_free_mh (header);
2335 return imethod->header;
2338 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2339 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2340 g_assert (mw->header);
2345 * We don't need locks here: the new header is allocated from malloc memory
2346 * and is not stored anywhere in the runtime, the user needs to free it.
2348 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2349 idx = mono_metadata_token_index (method->token);
2350 img = method->klass->image;
2351 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2353 if (!mono_verifier_verify_method_header (img, rva, NULL))
2356 loc = mono_image_rva_map (img, rva);
2360 header = mono_metadata_parse_mh_full (img, mono_method_get_generic_container (method), loc);
2366 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2369 *iflags = method->iflags;
2370 return method->flags;
2374 * Find the method index in the metadata methodDef table.
2377 mono_method_get_index (MonoMethod *method) {
2378 MonoClass *klass = method->klass;
2382 return mono_metadata_token_index (method->token);
2384 mono_class_setup_methods (klass);
2385 if (klass->exception_type)
2387 for (i = 0; i < klass->method.count; ++i) {
2388 if (method == klass->methods [i]) {
2389 if (klass->image->uncompressed_metadata)
2390 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2392 return klass->method.first + i + 1;