2 * loader.c: Image Loader
5 * Paolo Molaro (lupus@ximian.com)
6 * Miguel de Icaza (miguel@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 * This file is used by the interpreter and the JIT engine to locate
14 * assemblies. Used to load AssemblyRef and later to resolve various
18 * This should keep track of the assembly versions that we are loading.
20 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
27 #include <mono/metadata/metadata.h>
28 #include <mono/metadata/image.h>
29 #include <mono/metadata/assembly.h>
30 #include <mono/metadata/tokentype.h>
31 #include <mono/metadata/tabledefs.h>
32 #include <mono/metadata/metadata-internals.h>
33 #include <mono/metadata/loader.h>
34 #include <mono/metadata/class-internals.h>
35 #include <mono/metadata/debug-helpers.h>
36 #include <mono/metadata/reflection.h>
37 #include <mono/metadata/profiler.h>
38 #include <mono/metadata/profiler-private.h>
39 #include <mono/metadata/exception.h>
40 #include <mono/metadata/marshal.h>
41 #include <mono/metadata/lock-tracer.h>
42 #include <mono/metadata/verify-internals.h>
43 #include <mono/utils/mono-logger-internals.h>
44 #include <mono/utils/mono-dl.h>
45 #include <mono/utils/mono-membar.h>
46 #include <mono/utils/mono-counters.h>
47 #include <mono/utils/mono-error-internals.h>
48 #include <mono/utils/mono-tls.h>
49 #include <mono/utils/mono-path.h>
51 MonoDefaults mono_defaults;
54 * This lock protects the hash tables inside MonoImage used by the metadata
55 * loading functions in class.c and loader.c.
57 * See domain-internals.h for locking policy in combination with the
60 static MonoCoopMutex loader_mutex;
61 static mono_mutex_t global_loader_data_mutex;
62 static gboolean loader_lock_inited;
65 static guint32 inflated_signatures_size;
66 static guint32 memberref_sig_cache_size;
67 static guint32 methods_size;
68 static guint32 signatures_size;
71 * This TLS variable contains the last type load error encountered by the loader.
73 MonoNativeTlsKey loader_error_thread_id;
76 * This TLS variable holds how many times the current thread has acquired the loader
79 MonoNativeTlsKey loader_lock_nest_id;
81 static void dllmap_cleanup (void);
85 global_loader_data_lock (void)
87 mono_locks_os_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
91 global_loader_data_unlock (void)
93 mono_locks_os_release (&global_loader_data_mutex, LoaderGlobalDataLock);
99 static gboolean inited;
102 mono_coop_mutex_init_recursive (&loader_mutex);
103 mono_os_mutex_init_recursive (&global_loader_data_mutex);
104 loader_lock_inited = TRUE;
106 mono_native_tls_alloc (&loader_error_thread_id, NULL);
107 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
109 mono_counters_init ();
110 mono_counters_register ("Inflated signatures size",
111 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
112 mono_counters_register ("Memberref signature cache size",
113 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
114 mono_counters_register ("MonoMethod size",
115 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
116 mono_counters_register ("MonoMethodSignature size",
117 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
124 mono_loader_cleanup (void)
128 mono_native_tls_free (loader_error_thread_id);
129 mono_native_tls_free (loader_lock_nest_id);
131 mono_coop_mutex_destroy (&loader_mutex);
132 mono_os_mutex_destroy (&global_loader_data_mutex);
133 loader_lock_inited = FALSE;
137 * Handling of type load errors should be done as follows:
139 * If something could not be loaded, the loader should call one of the
140 * mono_loader_set_error_XXX functions ()
141 * with the appropriate arguments, then return NULL to report the failure. The error
142 * should be propagated until it reaches code which can throw managed exceptions. At that
143 * point, an exception should be thrown based on the information returned by
144 * mono_loader_get_last_error (). Then the error should be cleared by calling
145 * mono_loader_clear_error ().
149 set_loader_error (MonoLoaderError *error)
151 mono_loader_clear_error ();
152 mono_native_tls_set_value (loader_error_thread_id, error);
156 * mono_loader_set_error_assembly_load:
158 * Set the loader error for this thread.
161 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
163 MonoLoaderError *error;
165 if (mono_loader_get_last_error ())
168 error = g_new0 (MonoLoaderError, 1);
169 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
170 error->assembly_name = g_strdup (assembly_name);
171 error->ref_only = ref_only;
174 * This is not strictly needed, but some (most) of the loader code still
175 * can't deal with load errors, and this message is more helpful than an
179 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "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);
181 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
183 set_loader_error (error);
187 * mono_loader_set_error_type_load:
189 * Set the loader error for this thread.
192 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
194 MonoLoaderError *error;
196 if (mono_loader_get_last_error ())
199 error = g_new0 (MonoLoaderError, 1);
200 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
201 error->class_name = g_strdup (class_name);
202 error->assembly_name = g_strdup (assembly_name);
205 * This is not strictly needed, but some (most) of the loader code still
206 * can't deal with load errors, and this message is more helpful than an
209 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
211 set_loader_error (error);
215 * mono_loader_set_error_method_load:
217 * Set the loader error for this thread. MEMBER_NAME should point to a string
221 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
223 MonoLoaderError *error;
225 /* FIXME: Store the signature as well */
226 if (mono_loader_get_last_error ())
229 error = g_new0 (MonoLoaderError, 1);
230 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
231 error->class_name = g_strdup (class_name);
232 error->member_name = member_name;
234 set_loader_error (error);
238 * mono_loader_set_error_field_load:
240 * Set the loader error for this thread. MEMBER_NAME should point to a string
244 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
246 MonoLoaderError *error;
248 /* FIXME: Store the signature as well */
249 if (mono_loader_get_last_error ())
252 error = g_new0 (MonoLoaderError, 1);
253 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
254 error->klass = klass;
255 error->member_name = member_name;
257 set_loader_error (error);
261 * mono_loader_set_error_bad_image:
263 * Set the loader error for this thread.
266 mono_loader_set_error_bad_image (char *msg)
268 MonoLoaderError *error;
270 if (mono_loader_get_last_error ())
273 error = g_new0 (MonoLoaderError, 1);
274 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
277 set_loader_error (error);
282 * mono_loader_get_last_error:
284 * Returns information about the last type load exception encountered by the loader, or
285 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
288 mono_loader_get_last_error (void)
290 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
294 mono_loader_assert_no_error (void)
296 MonoLoaderError *error = mono_loader_get_last_error ();
299 g_print ("Unhandled loader error: %x, %s %s %s\n", error->exception_type, error->msg, error->assembly_name, error->class_name);
300 g_assert_not_reached ();
305 * mono_loader_clear_error:
307 * Disposes any loader error messages on this thread
310 mono_loader_clear_error (void)
312 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
315 g_free (ex->class_name);
316 g_free (ex->assembly_name);
320 mono_native_tls_set_value (loader_error_thread_id, NULL);
325 * mono_loader_error_prepare_exception:
326 * @error: The MonoLoaderError to turn into an exception
328 * This turns a MonoLoaderError into an exception that can be thrown
329 * and resets the Mono Loader Error state during this process.
333 mono_loader_error_prepare_exception (MonoLoaderError *error)
335 MonoException *ex = NULL;
337 switch (error->exception_type) {
338 case MONO_EXCEPTION_TYPE_LOAD: {
339 char *cname = g_strdup (error->class_name);
340 char *aname = g_strdup (error->assembly_name);
341 MonoString *class_name;
343 mono_loader_clear_error ();
345 class_name = mono_string_new (mono_domain_get (), cname);
347 ex = mono_get_exception_type_load (class_name, aname);
352 case MONO_EXCEPTION_MISSING_METHOD: {
353 char *cname = g_strdup (error->class_name);
354 char *aname = g_strdup (error->member_name);
356 mono_loader_clear_error ();
357 ex = mono_get_exception_missing_method (cname, aname);
363 case MONO_EXCEPTION_MISSING_FIELD: {
365 char *cmembername = g_strdup (error->member_name);
367 class_name = mono_type_get_full_name (error->klass);
369 class_name = g_strdup ("");
371 mono_loader_clear_error ();
373 ex = mono_get_exception_missing_field (class_name, cmembername);
375 g_free (cmembername);
379 case MONO_EXCEPTION_FILE_NOT_FOUND: {
384 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);
386 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
387 filename = g_strdup (error->assembly_name);
388 /* Has to call this before calling anything which might call mono_class_init () */
389 mono_loader_clear_error ();
390 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
396 case MONO_EXCEPTION_BAD_IMAGE: {
397 char *msg = g_strdup (error->msg);
398 mono_loader_clear_error ();
399 ex = mono_get_exception_bad_image_format (msg);
405 g_assert_not_reached ();
412 * find_cached_memberref_sig:
414 * Return a cached copy of the memberref signature identified by SIG_IDX.
415 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
416 * A cache is needed since the type/signature parsing routines allocate everything
417 * from a mempool, so without a cache, multiple requests for the same signature would
418 * lead to unbounded memory growth. For normal methods/fields this is not a problem
419 * since the resulting methods/fields are cached, but inflated methods/fields cannot
421 * LOCKING: Acquires the loader lock.
424 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
428 mono_image_lock (image);
429 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
430 mono_image_unlock (image);
436 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
440 mono_image_lock (image);
441 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
443 /* Somebody got in before us */
447 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
448 /* An approximation based on glib 2.18 */
449 memberref_sig_cache_size += sizeof (gpointer) * 4;
451 mono_image_unlock (image);
456 static MonoClassField*
457 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
458 MonoGenericContext *context, MonoError *error)
460 MonoClass *klass = NULL;
461 MonoClassField *field;
462 MonoTableInfo *tables = image->tables;
465 guint32 nindex, class_index;
468 guint32 idx = mono_metadata_token_index (token);
470 mono_error_init (error);
472 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
473 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
474 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
476 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
478 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
479 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class_index, token);
483 switch (class_index) {
484 case MONO_MEMBERREF_PARENT_TYPEDEF:
485 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
487 case MONO_MEMBERREF_PARENT_TYPEREF:
488 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
490 case MONO_MEMBERREF_PARENT_TYPESPEC:
491 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
494 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class_index, token);
500 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
501 mono_metadata_decode_blob_size (ptr, &ptr);
502 /* we may want to check the signature here... */
505 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class_index, fname, token);
509 /* FIXME: This needs a cache, especially for generic instances, since
510 * we ask mono_metadata_parse_type_checked () to allocates everything from a mempool.
511 * FIXME part2, mono_metadata_parse_type_checked actually allows for a transient type instead.
512 * FIXME part3, transient types are not 100% transient, so we need to take care of that first.
514 sig_type = (MonoType *)find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
516 MonoError inner_error;
517 sig_type = mono_metadata_parse_type_checked (image, NULL, 0, FALSE, ptr, &ptr, &inner_error);
518 if (sig_type == NULL) {
519 mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x due to: %s", fname, token, mono_error_get_message (&inner_error));
520 mono_error_cleanup (&inner_error);
523 sig_type = (MonoType *)cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
526 mono_class_init (klass); /*FIXME is this really necessary?*/
529 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
532 mono_loader_assert_no_error ();
533 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
540 * mono_field_from_token:
541 * @deprecated use the _checked variant
542 * Notes: runtime code MUST not use this function
545 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
548 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
549 g_assert (mono_error_ok (&error));
554 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
558 MonoClassField *field;
560 mono_error_init (error);
562 if (image_is_dynamic (image)) {
563 MonoClassField *result;
564 MonoClass *handle_class;
567 result = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
568 // This checks the memberref type as well
569 if (!result || handle_class != mono_defaults.fieldhandle_class) {
570 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
573 *retklass = result->parent;
577 if ((field = (MonoClassField *)mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
578 *retklass = field->parent;
582 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
583 field = field_from_memberref (image, token, retklass, context, error);
584 mono_loader_assert_no_error ();
586 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
588 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
591 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
598 field = mono_class_get_field (k, token);
600 if (mono_loader_get_last_error ())
601 mono_error_set_from_loader_error (error);
603 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
607 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container) {
608 mono_image_lock (image);
609 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
610 mono_image_unlock (image);
613 mono_loader_assert_no_error ();
618 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
622 if (sig1->hasthis != sig2->hasthis ||
623 sig1->sentinelpos != sig2->sentinelpos)
626 for (i = 0; i < sig1->sentinelpos; i++) {
627 MonoType *p1 = sig1->params[i];
628 MonoType *p2 = sig2->params[i];
630 /*if (p1->attrs != p2->attrs)
633 if (!mono_metadata_type_equal (p1, p2))
637 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
643 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
644 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
648 /* Search directly in the metadata to avoid calling setup_methods () */
649 mono_error_init (error);
651 /* FIXME: !from_class->generic_class condition causes test failures. */
652 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
653 for (i = 0; i < klass->method.count; ++i) {
654 guint32 cols [MONO_METHOD_SIZE];
657 MonoMethodSignature *other_sig;
659 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
661 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
663 if (!((fqname && !strcmp (m_name, fqname)) ||
664 (qname && !strcmp (m_name, qname)) ||
665 (name && !strcmp (m_name, name))))
668 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
669 if (!mono_error_ok (error)) //bail out if we hit a loader error
672 other_sig = mono_method_signature_checked (method, error);
673 if (!mono_error_ok (error)) //bail out if we hit a loader error
675 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
681 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
683 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
684 See mono/tests/generic-type-load-exception.2.il
685 FIXME we should better report this error to the caller
687 if (!klass->methods || mono_class_has_failure (klass)) {
688 mono_error_set_type_load_class (error, klass, "Could not find method due to a type load error"); //FIXME get the error from the class
692 for (i = 0; i < klass->method.count; ++i) {
693 MonoMethod *m = klass->methods [i];
694 MonoMethodSignature *msig;
696 /* We must cope with failing to load some of the types. */
700 if (!((fqname && !strcmp (m->name, fqname)) ||
701 (qname && !strcmp (m->name, qname)) ||
702 (name && !strcmp (m->name, name))))
704 msig = mono_method_signature_checked (m, error);
705 if (!mono_error_ok (error)) //bail out if we hit a loader error
711 if (sig->call_convention == MONO_CALL_VARARG) {
712 if (mono_metadata_signature_vararg_match (sig, msig))
715 if (mono_metadata_signature_equal (sig, msig))
720 if (i < klass->method.count)
721 return mono_class_get_method_by_index (from_class, i);
726 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
729 char *qname, *fqname, *class_name;
730 gboolean is_interface;
731 MonoMethod *result = NULL;
732 MonoClass *initial_class = in_class;
734 mono_error_init (error);
735 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
738 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
740 qname = g_strconcat (class_name, ".", name, NULL);
741 if (ic->name_space && ic->name_space [0])
742 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
746 class_name = qname = fqname = NULL;
749 g_assert (from_class);
750 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
751 if (result || !mono_error_ok (error))
754 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
758 * This happens when we fail to lazily load the interfaces of one of the types.
759 * On such case we can't just bail out since user code depends on us trying harder.
761 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
762 in_class = in_class->parent;
763 from_class = from_class->parent;
767 for (i = 0; i < in_class->interface_offsets_count; i++) {
768 MonoClass *in_ic = in_class->interfaces_packed [i];
769 MonoClass *from_ic = from_class->interfaces_packed [i];
770 char *ic_qname, *ic_fqname, *ic_class_name;
772 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
773 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
774 if (in_ic->name_space && in_ic->name_space [0])
775 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
779 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
780 g_free (ic_class_name);
783 if (result || !mono_error_ok (error))
787 in_class = in_class->parent;
788 from_class = from_class->parent;
790 g_assert (!in_class == !from_class);
793 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
795 //we did not find the method
796 if (!result && mono_error_ok (error)) {
797 char *desc = mono_signature_get_desc (sig, FALSE);
798 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
809 static MonoMethodSignature*
810 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
812 MonoMethodSignature *res;
816 mono_error_init (error);
820 res = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
821 res->param_count = sig->param_count;
822 res->sentinelpos = -1;
823 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
824 if (!mono_error_ok (error))
826 is_open = mono_class_is_open_constructed_type (res->ret);
827 for (i = 0; i < sig->param_count; ++i) {
828 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
829 if (!mono_error_ok (error))
833 is_open = mono_class_is_open_constructed_type (res->params [i]);
835 res->hasthis = sig->hasthis;
836 res->explicit_this = sig->explicit_this;
837 res->call_convention = sig->call_convention;
838 res->pinvoke = sig->pinvoke;
839 res->generic_param_count = sig->generic_param_count;
840 res->sentinelpos = sig->sentinelpos;
841 res->has_type_parameters = is_open;
842 res->is_inflated = 1;
847 mono_metadata_free_type (res->ret);
848 for (i = 0; i < sig->param_count; ++i) {
850 mono_metadata_free_type (res->params [i]);
857 * mono_inflate_generic_signature:
859 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
862 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
864 MonoMethodSignature *res, *cached;
866 res = inflate_generic_signature_checked (NULL, sig, context, error);
867 if (!mono_error_ok (error))
869 cached = mono_metadata_get_inflated_signature (res, context);
871 mono_metadata_free_inflated_signature (res);
875 static MonoMethodHeader*
876 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context, MonoError *error)
878 MonoMethodHeader *res;
880 res = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
881 res->code = header->code;
882 res->code_size = header->code_size;
883 res->max_stack = header->max_stack;
884 res->num_clauses = header->num_clauses;
885 res->init_locals = header->init_locals;
886 res->num_locals = header->num_locals;
887 res->clauses = header->clauses;
889 mono_error_init (error);
891 for (i = 0; i < header->num_locals; ++i) {
892 res->locals [i] = mono_class_inflate_generic_type_checked (header->locals [i], context, error);
896 if (res->num_clauses) {
897 res->clauses = (MonoExceptionClause *)g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
898 for (i = 0; i < header->num_clauses; ++i) {
899 MonoExceptionClause *clause = &res->clauses [i];
900 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
902 clause->data.catch_class = mono_class_inflate_generic_class_checked (clause->data.catch_class, context, error);
914 * token is the method_ref/def/spec token used in a call IL instruction.
915 * @deprecated use the _checked variant
916 * Notes: runtime code MUST not use this function
919 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
922 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
923 mono_error_cleanup (&error);
928 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
930 int table = mono_metadata_token_table (token);
931 int idx = mono_metadata_token_index (token);
933 guint32 cols [MONO_MEMBERREF_SIZE];
934 MonoMethodSignature *sig;
937 mono_error_init (error);
939 /* !table is for wrappers: we should really assign their own token to them */
940 if (!table || table == MONO_TABLE_METHOD)
941 return mono_method_signature_checked (method, error);
943 if (table == MONO_TABLE_METHODSPEC) {
944 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
945 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated) {
946 mono_error_set_bad_image (error, image, "Method is a pinvoke or open generic");
950 return mono_method_signature_checked (method, error);
953 if (method->klass->generic_class)
954 return mono_method_signature_checked (method, error);
956 if (image_is_dynamic (image)) {
957 sig = mono_reflection_lookup_signature (image, method, token, error);
961 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
962 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
964 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
966 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
967 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
968 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
970 //FIXME include the verification error
971 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
975 ptr = mono_metadata_blob_heap (image, sig_idx);
976 mono_metadata_decode_blob_size (ptr, &ptr);
978 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
982 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
984 /* FIXME: we probably should verify signature compat in the dynamic case too*/
985 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
986 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
987 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
989 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
995 MonoMethodSignature *cached;
997 /* This signature is not owned by a MonoMethod, so need to cache */
998 sig = inflate_generic_signature_checked (image, sig, context, error);
999 if (!mono_error_ok (error))
1002 cached = mono_metadata_get_inflated_signature (sig, context);
1004 mono_metadata_free_inflated_signature (sig);
1006 inflated_signatures_size += mono_metadata_signature_size (cached);
1010 g_assert (mono_error_ok (error));
1015 * token is the method_ref/def/spec token used in a call IL instruction.
1016 * @deprecated use the _checked variant
1017 * Notes: runtime code MUST not use this function
1019 MonoMethodSignature*
1020 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
1023 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
1024 mono_error_cleanup (&error);
1028 /* this is only for the typespec array methods */
1030 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1034 mono_class_setup_methods (klass);
1035 g_assert (!mono_class_has_failure (klass)); /*FIXME this should not fail, right?*/
1036 for (i = 0; i < klass->method.count; ++i) {
1037 MonoMethod *method = klass->methods [i];
1038 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1045 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1046 gboolean *used_context, MonoError *error)
1048 MonoClass *klass = NULL;
1049 MonoMethod *method = NULL;
1050 MonoTableInfo *tables = image->tables;
1052 guint32 nindex, class_index, sig_idx;
1054 MonoMethodSignature *sig;
1057 mono_error_init (error);
1059 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1060 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1061 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1062 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1063 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1065 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1068 * Whether we actually used the `typespec_context' or not.
1069 * This is used to tell our caller whether or not it's safe to insert the returned
1070 * method into a cache.
1073 *used_context = class_index == MONO_MEMBERREF_PARENT_TYPESPEC;
1075 switch (class_index) {
1076 case MONO_MEMBERREF_PARENT_TYPEREF:
1077 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1081 case MONO_MEMBERREF_PARENT_TYPESPEC:
1083 * Parse the TYPESPEC in the parent's context.
1085 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1089 case MONO_MEMBERREF_PARENT_TYPEDEF:
1090 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1094 case MONO_MEMBERREF_PARENT_METHODDEF: {
1095 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1101 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class_index, nindex);
1106 mono_class_init (klass);
1108 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1110 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1111 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1115 ptr = mono_metadata_blob_heap (image, sig_idx);
1116 mono_metadata_decode_blob_size (ptr, &ptr);
1118 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
1120 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1124 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
1127 switch (class_index) {
1128 case MONO_MEMBERREF_PARENT_TYPEREF:
1129 case MONO_MEMBERREF_PARENT_TYPEDEF:
1130 method = find_method (klass, NULL, mname, sig, klass, error);
1133 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1136 type = &klass->byval_arg;
1138 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1139 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1140 method = find_method (in_class, NULL, mname, sig, klass, error);
1144 /* we're an array and we created these methods already in klass in mono_class_init () */
1145 method = mono_method_search_in_array_class (klass, mname, sig);
1149 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class_index, nindex);
1153 if (!method && mono_error_ok (error)) {
1154 char *msig = mono_signature_get_desc (sig, FALSE);
1155 GString *s = g_string_new (mname);
1156 if (sig->generic_param_count)
1157 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1158 g_string_append_printf (s, "(%s)", msig);
1160 msig = g_string_free (s, FALSE);
1162 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1163 mono_error_set_from_loader_error (error);
1165 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1170 mono_loader_assert_no_error ();
1174 mono_loader_assert_no_error ();
1175 g_assert (!mono_error_ok (error));
1180 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1184 MonoTableInfo *tables = image->tables;
1185 MonoGenericContext new_context;
1186 MonoGenericInst *inst;
1188 guint32 cols [MONO_METHODSPEC_SIZE];
1189 guint32 token, nindex, param_count;
1191 mono_error_init (error);
1193 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1194 token = cols [MONO_METHODSPEC_METHOD];
1195 nindex = token >> MONO_METHODDEFORREF_BITS;
1197 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1198 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1202 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1204 mono_metadata_decode_value (ptr, &ptr);
1206 param_count = mono_metadata_decode_value (ptr, &ptr);
1208 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr, error);
1212 if (context && inst->is_open) {
1213 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1214 if (!mono_error_ok (error))
1218 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1219 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1223 method = method_from_memberref (image, nindex, context, NULL, error);
1229 klass = method->klass;
1231 if (klass->generic_class) {
1232 g_assert (method->is_inflated);
1233 method = ((MonoMethodInflated *) method)->declaring;
1236 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1237 new_context.method_inst = inst;
1239 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1240 mono_loader_assert_no_error ();
1244 struct _MonoDllMap {
1252 static MonoDllMap *global_dll_map;
1255 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1263 global_loader_data_lock ();
1266 * we use the first entry we find that matches, since entries from
1267 * the config file are prepended to the list and we document that the
1268 * later entries win.
1270 for (; dll_map; dll_map = dll_map->next) {
1271 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1272 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1274 } else if (strcmp (dll_map->dll, dll)) {
1277 if (!found && dll_map->target) {
1278 *rdll = dll_map->target;
1280 /* we don't quit here, because we could find a full
1281 * entry that matches also function and that has priority.
1284 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1285 *rfunc = dll_map->target_func;
1290 global_loader_data_unlock ();
1295 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1298 if (assembly && assembly->dll_map) {
1299 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1303 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1307 * mono_dllmap_insert:
1308 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1309 * @dll: The name of the external library, as it would be found in the DllImport declaration. If prefixed with 'i:' the matching of the library name is done without case sensitivity
1310 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1311 * @tdll: The name of the library to map the specified @dll if it matches.
1312 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1314 * LOCKING: Acquires the loader lock.
1316 * This function is used to programatically add DllImport remapping in either
1317 * a specific assembly, or as a global remapping. This is done by remapping
1318 * references in a DllImport attribute from the @dll library name into the @tdll
1319 * name. If the @dll name contains the prefix "i:", the comparison of the
1320 * library name is done without case sensitivity.
1322 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1323 * or the name of the function as determined by DllImport. If you pass @func, you
1324 * must also pass @tfunc which is the name of the target function to invoke on a match.
1327 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1329 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1330 * the contents of relocated_demo_path for all assemblies in the Mono process.
1332 * NOTE: This can be called before the runtime is initialized, for example from
1333 * mono_config_parse ().
1336 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1340 mono_loader_init ();
1343 entry = (MonoDllMap *)g_malloc0 (sizeof (MonoDllMap));
1344 entry->dll = dll? g_strdup (dll): NULL;
1345 entry->target = tdll? g_strdup (tdll): NULL;
1346 entry->func = func? g_strdup (func): NULL;
1347 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1349 global_loader_data_lock ();
1350 entry->next = global_dll_map;
1351 global_dll_map = entry;
1352 global_loader_data_unlock ();
1354 entry = (MonoDllMap *)mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1355 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1356 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1357 entry->func = func? mono_image_strdup (assembly, func): NULL;
1358 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1360 mono_image_lock (assembly);
1361 entry->next = assembly->dll_map;
1362 assembly->dll_map = entry;
1363 mono_image_unlock (assembly);
1368 free_dllmap (MonoDllMap *map)
1371 MonoDllMap *next = map->next;
1374 g_free (map->target);
1376 g_free (map->target_func);
1383 dllmap_cleanup (void)
1385 free_dllmap (global_dll_map);
1386 global_dll_map = NULL;
1389 static GHashTable *global_module_map;
1392 cached_module_load (const char *name, int flags, char **err)
1398 global_loader_data_lock ();
1399 if (!global_module_map)
1400 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1401 res = (MonoDl *)g_hash_table_lookup (global_module_map, name);
1403 global_loader_data_unlock ();
1406 res = mono_dl_open (name, flags, err);
1408 g_hash_table_insert (global_module_map, g_strdup (name), res);
1409 global_loader_data_unlock ();
1413 static MonoDl *internal_module;
1416 is_absolute_path (const char *path)
1418 #ifdef PLATFORM_MACOSX
1419 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1420 !strncmp (path, "@rpath/", 7))
1423 return g_path_is_absolute (path);
1427 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1429 MonoImage *image = method->klass->image;
1430 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1431 MonoTableInfo *tables = image->tables;
1432 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1433 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1434 guint32 im_cols [MONO_IMPLMAP_SIZE];
1435 guint32 scope_token;
1436 const char *import = NULL;
1437 const char *orig_scope;
1438 const char *new_scope;
1440 char *full_name, *file_name, *found_name = NULL;
1442 MonoDl *module = NULL;
1443 gboolean cached = FALSE;
1445 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1453 return piinfo->addr;
1455 if (image_is_dynamic (method->klass->image)) {
1456 MonoReflectionMethodAux *method_aux =
1457 (MonoReflectionMethodAux *)g_hash_table_lookup (
1458 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1462 import = method_aux->dllentry;
1463 orig_scope = method_aux->dll;
1466 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1469 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1471 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1474 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1475 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1476 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1477 orig_scope = mono_metadata_string_heap (image, scope_token);
1480 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1483 mono_image_lock (image);
1484 if (!image->pinvoke_scopes) {
1485 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1486 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1488 module = (MonoDl *)g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1489 found_name = (char *)g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1490 mono_image_unlock (image);
1494 found_name = g_strdup (found_name);
1498 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1499 "DllImport attempting to load: '%s'.", new_scope);
1501 /* we allow a special name to dlopen from the running process namespace */
1502 if (strcmp (new_scope, "__Internal") == 0){
1503 if (internal_module == NULL)
1504 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1505 module = internal_module;
1510 * Try loading the module using a variety of names
1512 for (i = 0; i < 5; ++i) {
1513 char *base_name = NULL, *dir_name = NULL;
1514 gboolean is_absolute = is_absolute_path (new_scope);
1518 /* Try the original name */
1519 file_name = g_strdup (new_scope);
1522 /* Try trimming the .dll extension */
1523 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1524 file_name = g_strdup (new_scope);
1525 file_name [strlen (new_scope) - 4] = '\0';
1532 dir_name = g_path_get_dirname (new_scope);
1533 base_name = g_path_get_basename (new_scope);
1534 if (strstr (base_name, "lib") != base_name) {
1535 char *tmp = g_strdup_printf ("lib%s", base_name);
1538 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1541 } else if (strstr (new_scope, "lib") != new_scope) {
1542 file_name = g_strdup_printf ("lib%s", new_scope);
1547 if (!is_absolute && mono_dl_get_system_dir ()) {
1548 dir_name = (char*)mono_dl_get_system_dir ();
1549 file_name = g_path_get_basename (new_scope);
1555 #ifndef TARGET_WIN32
1556 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1557 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1558 !g_ascii_strcasecmp ("user32", new_scope) ||
1559 !g_ascii_strcasecmp ("kernel", new_scope)) {
1560 file_name = g_strdup ("libMonoSupportW.so");
1564 #ifndef TARGET_WIN32
1571 dir_name = g_path_get_dirname (file_name);
1573 base_name = g_path_get_basename (file_name);
1576 if (!module && is_absolute) {
1577 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1579 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1580 "DllImport error loading library '%s': '%s'.",
1581 file_name, error_msg);
1584 found_name = g_strdup (file_name);
1588 if (!module && !is_absolute) {
1592 for (j = 0; j < 3; ++j) {
1597 mdirname = g_path_get_dirname (image->name);
1599 case 1: /* @executable_path@/../lib */
1603 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1605 char *base, *newbase;
1608 resolvedname = mono_path_resolve_symlinks (buf);
1610 base = g_path_get_dirname (resolvedname);
1611 newbase = g_path_get_dirname(base);
1612 mdirname = g_strdup_printf ("%s/lib", newbase);
1614 g_free (resolvedname);
1621 case 2: /* @executable_path@/../Libraries */
1625 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1627 char *base, *newbase;
1630 resolvedname = mono_path_resolve_symlinks (buf);
1632 base = g_path_get_dirname (resolvedname);
1633 newbase = g_path_get_dirname(base);
1634 mdirname = g_strdup_printf ("%s/Libraries", newbase);
1636 g_free (resolvedname);
1648 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1649 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1651 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1652 "DllImport error loading library '%s': '%s'.",
1653 full_name, error_msg);
1656 found_name = g_strdup (full_name);
1672 char *file_or_base = is_absolute ? base_name : file_name;
1673 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1674 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1676 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1677 "DllImport error loading library '%s': '%s'.",
1678 full_name, error_msg);
1681 found_name = g_strdup (full_name);
1690 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1692 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1693 "DllImport error loading library '%s': '%s'.",
1694 file_name, error_msg);
1696 found_name = g_strdup (file_name);
1711 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1712 "DllImport unable to load library '%s'.",
1717 *exc_class = "DllNotFoundException";
1718 *exc_arg = new_scope;
1724 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1725 "DllImport loaded library '%s'.", found_name);
1726 mono_image_lock (image);
1727 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1728 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1729 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1731 mono_image_unlock (image);
1734 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1735 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1736 g_free (found_name);
1739 if (import && import [0] == '#' && isdigit (import [1])) {
1743 id = strtol (import + 1, &end, 10);
1744 if (id > 0 && *end == '\0')
1748 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1749 "Searching for '%s'.", import);
1751 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1752 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1754 char *mangled_name = NULL, *mangled_name2 = NULL;
1757 int mangle_param_count;
1763 * Search using a variety of mangled names
1765 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1766 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1767 gboolean need_param_count = FALSE;
1769 if (mangle_stdcall > 0)
1770 need_param_count = TRUE;
1772 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1777 mangled_name = (char*)import;
1778 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1779 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1780 /* Try the mangled name first */
1781 if (mangle_charset == 0)
1782 mangled_name = g_strconcat (import, "W", NULL);
1784 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1786 if (mangle_charset == 0)
1787 mangled_name = g_strconcat (import, "W", NULL);
1789 /* Try the mangled name last */
1790 if (mangle_charset == 1)
1791 mangled_name = g_strconcat (import, "A", NULL);
1794 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1796 /* Try the mangled name last */
1797 if (mangle_charset == 1)
1798 mangled_name = g_strconcat (import, "A", NULL);
1803 if (mangle_param_count == 0)
1804 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1806 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1807 param_count = mangle_param_count;
1809 /* Try the stdcall mangled name */
1811 * gcc under windows creates mangled names without the underscore, but MS.NET
1812 * doesn't support it, so we doesn't support it either.
1814 if (mangle_stdcall == 1)
1815 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1817 mangled_name2 = mangled_name;
1819 mangled_name2 = mangled_name;
1822 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1823 "Probing '%s'.", mangled_name2);
1825 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1828 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1829 "Found as '%s'.", mangled_name2);
1831 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1832 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1837 if (mangled_name != mangled_name2)
1838 g_free (mangled_name2);
1839 if (mangled_name != import)
1840 g_free (mangled_name);
1846 if (!piinfo->addr) {
1849 *exc_class = "EntryPointNotFoundException";
1854 return piinfo->addr;
1858 * LOCKING: assumes the loader lock to be taken.
1861 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1862 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1865 int table = mono_metadata_token_table (token);
1866 int idx = mono_metadata_token_index (token);
1867 MonoTableInfo *tables = image->tables;
1868 MonoGenericContainer *generic_container = NULL, *container = NULL;
1869 const char *sig = NULL;
1870 guint32 cols [MONO_TYPEDEF_SIZE];
1872 mono_error_init (error);
1874 if (image_is_dynamic (image)) {
1875 MonoClass *handle_class;
1877 result = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1878 mono_loader_assert_no_error ();
1880 // This checks the memberref type as well
1881 if (result && handle_class != mono_defaults.methodhandle_class) {
1882 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1888 if (table != MONO_TABLE_METHOD) {
1889 if (table == MONO_TABLE_METHODSPEC) {
1890 if (used_context) *used_context = TRUE;
1891 return method_from_methodspec (image, context, idx, error);
1893 if (table != MONO_TABLE_MEMBERREF) {
1894 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1897 return method_from_memberref (image, idx, context, used_context, error);
1900 if (used_context) *used_context = FALSE;
1902 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1903 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1908 guint32 type = mono_metadata_typedef_from_method (image, token);
1910 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1913 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1918 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1920 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1921 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1922 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1924 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1925 methods_size += sizeof (MonoMethod);
1928 mono_stats.method_count ++;
1931 result->klass = klass;
1932 result->flags = cols [2];
1933 result->iflags = cols [1];
1934 result->token = token;
1935 result->name = mono_metadata_string_heap (image, cols [3]);
1937 if (!sig) /* already taken from the methodref */
1938 sig = mono_metadata_blob_heap (image, cols [4]);
1939 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1941 container = klass->generic_container;
1944 * load_generic_params does a binary search so only call it if the method
1948 generic_container = mono_metadata_load_generic_params (image, token, container);
1949 mono_loader_assert_no_error (); /* FIXME don't swallow this error. */
1951 if (generic_container) {
1952 result->is_generic = TRUE;
1953 generic_container->owner.method = result;
1954 generic_container->is_anonymous = FALSE; // Method is now known, container is no longer anonymous
1955 /*FIXME put this before the image alloc*/
1956 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1959 container = generic_container;
1962 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1963 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1964 result->string_ctor = 1;
1965 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1966 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1969 /* IJW is P/Invoke with a predefined function pointer. */
1970 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1971 piinfo->addr = mono_image_rva_map (image, cols [0]);
1972 g_assert (piinfo->addr);
1975 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1976 /* Native methods can have no map. */
1977 if (piinfo->implmap_idx)
1978 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1981 if (generic_container)
1982 mono_method_set_generic_container (result, generic_container);
1984 mono_loader_assert_no_error ();
1989 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1992 MonoMethod *result = mono_get_method_checked (image, token, klass, NULL, &error);
1993 mono_error_cleanup (&error);
1998 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1999 MonoGenericContext *context)
2002 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
2003 mono_error_cleanup (&error);
2008 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
2010 MonoMethod *result = NULL;
2011 gboolean used_context = FALSE;
2013 /* We do everything inside the lock to prevent creation races */
2015 mono_error_init (error);
2017 mono_image_lock (image);
2019 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
2020 if (!image->method_cache)
2021 image->method_cache = g_hash_table_new (NULL, NULL);
2022 result = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2023 } else if (!image_is_dynamic (image)) {
2024 if (!image->methodref_cache)
2025 image->methodref_cache = g_hash_table_new (NULL, NULL);
2026 result = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2028 mono_image_unlock (image);
2034 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
2038 mono_image_lock (image);
2039 if (!used_context && !result->is_inflated) {
2040 MonoMethod *result2 = NULL;
2042 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2043 result2 = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2044 else if (!image_is_dynamic (image))
2045 result2 = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2048 mono_image_unlock (image);
2052 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2053 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
2054 else if (!image_is_dynamic (image))
2055 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
2058 mono_image_unlock (image);
2064 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
2067 MonoClass *ic = NULL;
2068 MonoGenericContext *method_context = NULL;
2069 MonoMethodSignature *sig, *original_sig;
2071 mono_error_init (error);
2073 mono_class_init (constrained_class);
2074 original_sig = sig = mono_method_signature_checked (method, error);
2079 if (method->is_inflated && sig->generic_param_count) {
2080 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2081 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
2084 method_context = mono_method_get_context (method);
2088 * We must inflate the signature with the class instantiation to work on
2089 * cases where a class inherit from a generic type and the override replaces
2090 * any type argument which a concrete type. See #325283.
2092 if (method_context->class_inst) {
2093 MonoGenericContext ctx;
2094 ctx.method_inst = NULL;
2095 ctx.class_inst = method_context->class_inst;
2096 /*Fixme, property propagate this error*/
2097 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2103 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2106 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2107 if (sig != original_sig)
2108 mono_metadata_free_inflated_signature (sig);
2113 if (method_context) {
2114 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2123 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2124 MonoGenericContext *context, MonoError *error)
2128 return get_method_constrained (image, method, constrained_class, context, error);
2132 * mono_get_method_constrained:
2134 * This is used when JITing the `constrained.' opcode.
2136 * This returns two values: the contrained method, which has been inflated
2137 * as the function return value; And the original CIL-stream method as
2138 * declared in cil_method. The later is used for verification.
2141 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2142 MonoGenericContext *context, MonoMethod **cil_method)
2145 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2146 mono_error_cleanup (&error);
2151 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2153 mono_error_init (error);
2155 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2159 return get_method_constrained (image, *cil_method, constrained_class, context, error);
2163 mono_free_method (MonoMethod *method)
2165 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2166 mono_profiler_method_free (method);
2168 /* FIXME: This hack will go away when the profiler will support freeing methods */
2169 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2172 if (method->signature) {
2174 * FIXME: This causes crashes because the types inside signatures and
2175 * locals are shared.
2177 /* mono_metadata_free_method_signature (method->signature); */
2178 /* g_free (method->signature); */
2181 if (method_is_dynamic (method)) {
2182 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2185 mono_marshal_free_dynamic_wrappers (method);
2187 mono_image_property_remove (method->klass->image, method);
2189 g_free ((char*)method->name);
2191 g_free ((char*)mw->header->code);
2192 for (i = 0; i < mw->header->num_locals; ++i)
2193 g_free (mw->header->locals [i]);
2194 g_free (mw->header->clauses);
2195 g_free (mw->header);
2197 g_free (mw->method_data);
2198 g_free (method->signature);
2204 mono_method_get_param_names (MonoMethod *method, const char **names)
2208 MonoTableInfo *methodt;
2209 MonoTableInfo *paramt;
2210 MonoMethodSignature *signature;
2213 if (method->is_inflated)
2214 method = ((MonoMethodInflated *) method)->declaring;
2216 signature = mono_method_signature (method);
2217 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2218 number of arguments and allocate a properly sized array. */
2219 if (signature == NULL)
2222 if (!signature->param_count)
2225 for (i = 0; i < signature->param_count; ++i)
2228 klass = method->klass;
2232 mono_class_init (klass);
2234 if (image_is_dynamic (klass->image)) {
2235 MonoReflectionMethodAux *method_aux =
2236 (MonoReflectionMethodAux *)g_hash_table_lookup (
2237 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2238 if (method_aux && method_aux->param_names) {
2239 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2240 if (method_aux->param_names [i + 1])
2241 names [i] = method_aux->param_names [i + 1];
2246 if (method->wrapper_type) {
2247 char **pnames = NULL;
2249 mono_image_lock (klass->image);
2250 if (klass->image->wrapper_param_names)
2251 pnames = (char **)g_hash_table_lookup (klass->image->wrapper_param_names, method);
2252 mono_image_unlock (klass->image);
2255 for (i = 0; i < signature->param_count; ++i)
2256 names [i] = pnames [i];
2261 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2262 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2263 idx = mono_method_get_index (method);
2265 guint32 cols [MONO_PARAM_SIZE];
2268 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2270 if (idx < methodt->rows)
2271 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2273 lastp = paramt->rows + 1;
2274 for (i = param_index; i < lastp; ++i) {
2275 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2276 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2277 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2283 mono_method_get_param_token (MonoMethod *method, int index)
2285 MonoClass *klass = method->klass;
2286 MonoTableInfo *methodt;
2289 mono_class_init (klass);
2291 if (image_is_dynamic (klass->image))
2292 g_assert_not_reached ();
2294 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2295 idx = mono_method_get_index (method);
2297 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2301 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2303 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2310 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2313 MonoClass *klass = method->klass;
2314 MonoTableInfo *methodt;
2315 MonoTableInfo *paramt;
2316 MonoMethodSignature *signature;
2319 signature = mono_method_signature (method);
2320 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2322 for (i = 0; i < signature->param_count + 1; ++i)
2325 if (image_is_dynamic (method->klass->image)) {
2326 MonoReflectionMethodAux *method_aux =
2327 (MonoReflectionMethodAux *)g_hash_table_lookup (
2328 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2329 if (method_aux && method_aux->param_marshall) {
2330 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2331 for (i = 0; i < signature->param_count + 1; ++i)
2332 if (dyn_specs [i]) {
2333 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2334 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2335 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2336 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2342 mono_class_init (klass);
2344 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2345 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2346 idx = mono_method_get_index (method);
2348 guint32 cols [MONO_PARAM_SIZE];
2349 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2351 if (idx < methodt->rows)
2352 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2354 lastp = paramt->rows + 1;
2356 for (i = param_index; i < lastp; ++i) {
2357 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2359 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2361 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2363 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2372 mono_method_has_marshal_info (MonoMethod *method)
2375 MonoClass *klass = method->klass;
2376 MonoTableInfo *methodt;
2377 MonoTableInfo *paramt;
2380 if (image_is_dynamic (method->klass->image)) {
2381 MonoReflectionMethodAux *method_aux =
2382 (MonoReflectionMethodAux *)g_hash_table_lookup (
2383 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2384 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2386 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2393 mono_class_init (klass);
2395 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2396 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2397 idx = mono_method_get_index (method);
2399 guint32 cols [MONO_PARAM_SIZE];
2400 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2402 if (idx + 1 < methodt->rows)
2403 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2405 lastp = paramt->rows + 1;
2407 for (i = param_index; i < lastp; ++i) {
2408 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2410 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2419 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2422 g_assert (method != NULL);
2423 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2425 if (method->is_inflated)
2426 method = ((MonoMethodInflated *) method)->declaring;
2427 data = (void **)((MonoMethodWrapper *)method)->method_data;
2428 g_assert (data != NULL);
2429 g_assert (id <= GPOINTER_TO_UINT (*data));
2436 } StackWalkUserData;
2439 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2441 StackWalkUserData *d = (StackWalkUserData *)data;
2443 switch (frame->type) {
2444 case FRAME_TYPE_DEBUGGER_INVOKE:
2445 case FRAME_TYPE_MANAGED_TO_NATIVE:
2446 case FRAME_TYPE_TRAMPOLINE:
2448 case FRAME_TYPE_MANAGED:
2449 g_assert (frame->ji);
2450 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2453 g_assert_not_reached ();
2459 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2461 StackWalkUserData ud = { func, user_data };
2462 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2466 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2468 StackWalkUserData ud = { func, user_data };
2469 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2473 MonoStackWalkAsyncSafe func;
2475 } AsyncStackWalkUserData;
2479 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2481 AsyncStackWalkUserData *d = (AsyncStackWalkUserData *)data;
2483 switch (frame->type) {
2484 case FRAME_TYPE_DEBUGGER_INVOKE:
2485 case FRAME_TYPE_MANAGED_TO_NATIVE:
2486 case FRAME_TYPE_TRAMPOLINE:
2488 case FRAME_TYPE_MANAGED:
2491 if (frame->ji->async) {
2492 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2494 return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2498 g_assert_not_reached ();
2505 * mono_stack_walk_async_safe:
2507 * Async safe version callable from signal handlers.
2510 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2513 AsyncStackWalkUserData ud = { func, user_data };
2515 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2516 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2520 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2522 MonoMethod **dest = (MonoMethod **)data;
2524 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2530 mono_method_get_last_managed (void)
2532 MonoMethod *m = NULL;
2533 mono_stack_walk_no_il (last_managed, &m);
2537 static gboolean loader_lock_track_ownership = FALSE;
2542 * See docs/thread-safety.txt for the locking strategy.
2545 mono_loader_lock (void)
2547 mono_locks_coop_acquire (&loader_mutex, LoaderLock);
2548 if (G_UNLIKELY (loader_lock_track_ownership)) {
2549 mono_native_tls_set_value (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) + 1));
2554 mono_loader_unlock (void)
2556 mono_locks_coop_release (&loader_mutex, LoaderLock);
2557 if (G_UNLIKELY (loader_lock_track_ownership)) {
2558 mono_native_tls_set_value (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) - 1));
2563 * mono_loader_lock_track_ownership:
2565 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2566 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2567 * thread owns the loader lock.
2570 mono_loader_lock_track_ownership (gboolean track)
2572 loader_lock_track_ownership = track;
2576 * mono_loader_lock_is_owned_by_self:
2578 * Return whenever the current thread owns the loader lock.
2579 * This is useful to avoid blocking operations while holding the loader lock.
2582 mono_loader_lock_is_owned_by_self (void)
2584 g_assert (loader_lock_track_ownership);
2586 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2590 * mono_loader_lock_if_inited:
2592 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2593 * be used in runtime initialization code which can be executed before mono_loader_init ().
2596 mono_loader_lock_if_inited (void)
2598 if (loader_lock_inited)
2599 mono_loader_lock ();
2603 mono_loader_unlock_if_inited (void)
2605 if (loader_lock_inited)
2606 mono_loader_unlock ();
2610 * mono_method_signature:
2612 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2614 MonoMethodSignature*
2615 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2620 gboolean can_cache_signature;
2621 MonoGenericContainer *container;
2622 MonoMethodSignature *signature = NULL, *sig2;
2625 /* We need memory barriers below because of the double-checked locking pattern */
2627 mono_error_init (error);
2630 return m->signature;
2632 img = m->klass->image;
2634 if (m->is_inflated) {
2635 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2636 /* the lock is recursive */
2637 signature = mono_method_signature (imethod->declaring);
2638 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2639 if (!mono_error_ok (error))
2642 inflated_signatures_size += mono_metadata_signature_size (signature);
2644 mono_image_lock (img);
2646 mono_memory_barrier ();
2648 m->signature = signature;
2650 mono_image_unlock (img);
2652 return m->signature;
2655 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2656 idx = mono_metadata_token_index (m->token);
2658 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2660 g_assert (!m->klass->generic_class);
2661 container = mono_method_get_generic_container (m);
2663 container = m->klass->generic_container;
2665 /* Generic signatures depend on the container so they cannot be cached */
2666 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2667 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2669 /* If the method has parameter attributes, that can modify the signature */
2670 if (mono_metadata_method_has_param_attrs (img, idx))
2671 can_cache_signature = FALSE;
2673 if (can_cache_signature) {
2674 mono_image_lock (img);
2675 signature = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2676 mono_image_unlock (img);
2680 const char *sig_body;
2681 /*TODO we should cache the failure result somewhere*/
2682 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2685 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2687 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2691 if (can_cache_signature) {
2692 mono_image_lock (img);
2693 sig2 = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2695 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2696 mono_image_unlock (img);
2699 signatures_size += mono_metadata_signature_size (signature);
2702 /* Verify metadata consistency */
2703 if (signature->generic_param_count) {
2704 if (!container || !container->is_method) {
2705 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);
2708 if (container->type_argc != signature->generic_param_count) {
2709 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);
2712 } else if (container && container->is_method && container->type_argc) {
2713 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);
2716 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2717 signature->pinvoke = 1;
2718 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2719 MonoCallConvention conv = (MonoCallConvention)0;
2720 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2721 signature->pinvoke = 1;
2723 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2724 case 0: /* no call conv, so using default */
2725 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2726 conv = MONO_CALL_DEFAULT;
2728 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2731 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2732 conv = MONO_CALL_STDCALL;
2734 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2735 conv = MONO_CALL_THISCALL;
2737 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2738 conv = MONO_CALL_FASTCALL;
2740 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2741 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2743 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);
2746 signature->call_convention = conv;
2749 mono_image_lock (img);
2751 mono_memory_barrier ();
2753 m->signature = signature;
2755 mono_image_unlock (img);
2757 return m->signature;
2761 * mono_method_signature:
2763 * Return the signature of the method M. On failure, returns NULL.
2765 MonoMethodSignature*
2766 mono_method_signature (MonoMethod *m)
2769 MonoMethodSignature *sig;
2771 sig = mono_method_signature_checked (m, &error);
2773 char *type_name = mono_type_get_full_name (m->klass);
2774 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2776 mono_error_cleanup (&error);
2783 mono_method_get_name (MonoMethod *method)
2785 return method->name;
2789 mono_method_get_class (MonoMethod *method)
2791 return method->klass;
2795 mono_method_get_token (MonoMethod *method)
2797 return method->token;
2801 mono_method_get_header_checked (MonoMethod *method, MonoError *error)
2807 MonoGenericContainer *container;
2809 mono_error_init (error);
2810 img = method->klass->image;
2812 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)) {
2813 mono_error_set_bad_image (error, img, "Method has no body");
2817 if (method->is_inflated) {
2818 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2819 MonoMethodHeader *header, *iheader;
2821 header = mono_method_get_header_checked (imethod->declaring, error);
2825 iheader = inflate_generic_header (header, mono_method_get_context (method), error);
2826 mono_metadata_free_mh (header);
2831 mono_image_lock (img);
2833 if (imethod->header) {
2834 mono_metadata_free_mh (iheader);
2835 mono_image_unlock (img);
2836 return imethod->header;
2839 mono_memory_barrier ();
2840 imethod->header = iheader;
2842 mono_image_unlock (img);
2844 return imethod->header;
2847 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2848 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2849 g_assert (mw->header);
2854 * We don't need locks here: the new header is allocated from malloc memory
2855 * and is not stored anywhere in the runtime, the user needs to free it.
2857 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2858 idx = mono_metadata_token_index (method->token);
2859 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2861 if (!mono_verifier_verify_method_header (img, rva, NULL)) {
2862 mono_error_set_bad_image (error, img, "Invalid method header, failed verification");
2866 loc = mono_image_rva_map (img, rva);
2868 mono_error_set_bad_image (error, img, "Method has zero rva");
2873 * When parsing the types of local variables, we must pass any container available
2874 * to ensure that both VAR and MVAR will get the right owner.
2876 container = mono_method_get_generic_container (method);
2878 container = method->klass->generic_container;
2879 return mono_metadata_parse_mh_full (img, container, (const char *)loc, error);
2883 mono_method_get_header (MonoMethod *method)
2886 MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
2887 mono_error_cleanup (&error);
2893 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2896 *iflags = method->iflags;
2897 return method->flags;
2901 * Find the method index in the metadata methodDef table.
2904 mono_method_get_index (MonoMethod *method)
2906 MonoClass *klass = method->klass;
2910 /* constructed array methods are not in the MethodDef table */
2914 return mono_metadata_token_index (method->token);
2916 mono_class_setup_methods (klass);
2917 if (mono_class_has_failure (klass))
2919 for (i = 0; i < klass->method.count; ++i) {
2920 if (method == klass->methods [i]) {
2921 if (klass->image->uncompressed_metadata)
2922 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2924 return klass->method.first + i + 1;