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.
26 #include <mono/metadata/metadata.h>
27 #include <mono/metadata/image.h>
28 #include <mono/metadata/assembly.h>
29 #include <mono/metadata/tokentype.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/metadata-internals.h>
32 #include <mono/metadata/loader.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/debug-helpers.h>
35 #include <mono/metadata/reflection.h>
36 #include <mono/metadata/profiler.h>
37 #include <mono/metadata/profiler-private.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/marshal.h>
40 #include <mono/metadata/lock-tracer.h>
41 #include <mono/metadata/verify-internals.h>
42 #include <mono/utils/mono-logger-internal.h>
43 #include <mono/utils/mono-dl.h>
44 #include <mono/utils/mono-membar.h>
45 #include <mono/utils/mono-counters.h>
46 #include <mono/utils/mono-error-internals.h>
47 #include <mono/utils/mono-tls.h>
48 #include <mono/utils/mono-path.h>
50 MonoDefaults mono_defaults;
53 * This lock protects the hash tables inside MonoImage used by the metadata
54 * loading functions in class.c and loader.c.
56 * See domain-internals.h for locking policy in combination with the
59 static mono_mutex_t loader_mutex, global_loader_data_mutex;
60 static gboolean loader_lock_inited;
63 static guint32 inflated_signatures_size;
64 static guint32 memberref_sig_cache_size;
65 static guint32 methods_size;
66 static guint32 signatures_size;
69 * This TLS variable contains the last type load error encountered by the loader.
71 MonoNativeTlsKey loader_error_thread_id;
74 * This TLS variable holds how many times the current thread has acquired the loader
77 MonoNativeTlsKey loader_lock_nest_id;
79 static void dllmap_cleanup (void);
83 global_loader_data_lock (void)
85 mono_locks_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
89 global_loader_data_unlock (void)
91 mono_locks_release (&global_loader_data_mutex, LoaderGlobalDataLock);
97 static gboolean inited;
100 mono_mutex_init_recursive (&loader_mutex);
101 mono_mutex_init_recursive (&global_loader_data_mutex);
102 loader_lock_inited = TRUE;
104 mono_native_tls_alloc (&loader_error_thread_id, NULL);
105 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
107 mono_counters_init ();
108 mono_counters_register ("Inflated signatures size",
109 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
110 mono_counters_register ("Memberref signature cache size",
111 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
112 mono_counters_register ("MonoMethod size",
113 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
114 mono_counters_register ("MonoMethodSignature size",
115 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
122 mono_loader_cleanup (void)
126 mono_native_tls_free (loader_error_thread_id);
127 mono_native_tls_free (loader_lock_nest_id);
129 mono_mutex_destroy (&loader_mutex);
130 mono_mutex_destroy (&global_loader_data_mutex);
131 loader_lock_inited = FALSE;
135 * Handling of type load errors should be done as follows:
137 * If something could not be loaded, the loader should call one of the
138 * mono_loader_set_error_XXX functions ()
139 * with the appropriate arguments, then return NULL to report the failure. The error
140 * should be propagated until it reaches code which can throw managed exceptions. At that
141 * point, an exception should be thrown based on the information returned by
142 * mono_loader_get_last_error (). Then the error should be cleared by calling
143 * mono_loader_clear_error ().
147 set_loader_error (MonoLoaderError *error)
149 mono_loader_clear_error ();
150 mono_native_tls_set_value (loader_error_thread_id, error);
154 * mono_loader_set_error_assembly_load:
156 * Set the loader error for this thread.
159 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
161 MonoLoaderError *error;
163 if (mono_loader_get_last_error ())
166 error = g_new0 (MonoLoaderError, 1);
167 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
168 error->assembly_name = g_strdup (assembly_name);
169 error->ref_only = ref_only;
172 * This is not strictly needed, but some (most) of the loader code still
173 * can't deal with load errors, and this message is more helpful than an
177 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);
179 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
181 set_loader_error (error);
185 * mono_loader_set_error_type_load:
187 * Set the loader error for this thread.
190 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
192 MonoLoaderError *error;
194 if (mono_loader_get_last_error ())
197 error = g_new0 (MonoLoaderError, 1);
198 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
199 error->class_name = g_strdup (class_name);
200 error->assembly_name = g_strdup (assembly_name);
203 * This is not strictly needed, but some (most) of the loader code still
204 * can't deal with load errors, and this message is more helpful than an
207 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
209 set_loader_error (error);
213 * mono_loader_set_error_method_load:
215 * Set the loader error for this thread. MEMBER_NAME should point to a string
219 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
221 MonoLoaderError *error;
223 /* FIXME: Store the signature as well */
224 if (mono_loader_get_last_error ())
227 error = g_new0 (MonoLoaderError, 1);
228 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
229 error->class_name = g_strdup (class_name);
230 error->member_name = member_name;
232 set_loader_error (error);
236 * mono_loader_set_error_field_load:
238 * Set the loader error for this thread. MEMBER_NAME should point to a string
242 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
244 MonoLoaderError *error;
246 /* FIXME: Store the signature as well */
247 if (mono_loader_get_last_error ())
250 error = g_new0 (MonoLoaderError, 1);
251 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
252 error->klass = klass;
253 error->member_name = member_name;
255 set_loader_error (error);
259 * mono_loader_set_error_bad_image:
261 * Set the loader error for this thread.
264 mono_loader_set_error_bad_image (char *msg)
266 MonoLoaderError *error;
268 if (mono_loader_get_last_error ())
271 error = g_new0 (MonoLoaderError, 1);
272 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
275 set_loader_error (error);
280 * mono_loader_get_last_error:
282 * Returns information about the last type load exception encountered by the loader, or
283 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
286 mono_loader_get_last_error (void)
288 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
292 mono_loader_assert_no_error (void)
294 MonoLoaderError *error = mono_loader_get_last_error ();
297 g_print ("Unhandled loader error: %x, %s %s %s\n", error->exception_type, error->msg, error->assembly_name, error->class_name);
298 g_assert_not_reached ();
303 * mono_loader_clear_error:
305 * Disposes any loader error messages on this thread
308 mono_loader_clear_error (void)
310 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
313 g_free (ex->class_name);
314 g_free (ex->assembly_name);
318 mono_native_tls_set_value (loader_error_thread_id, NULL);
323 * mono_loader_error_prepare_exception:
324 * @error: The MonoLoaderError to turn into an exception
326 * This turns a MonoLoaderError into an exception that can be thrown
327 * and resets the Mono Loader Error state during this process.
331 mono_loader_error_prepare_exception (MonoLoaderError *error)
333 MonoException *ex = NULL;
335 switch (error->exception_type) {
336 case MONO_EXCEPTION_TYPE_LOAD: {
337 char *cname = g_strdup (error->class_name);
338 char *aname = g_strdup (error->assembly_name);
339 MonoString *class_name;
341 mono_loader_clear_error ();
343 class_name = mono_string_new (mono_domain_get (), cname);
345 ex = mono_get_exception_type_load (class_name, aname);
350 case MONO_EXCEPTION_MISSING_METHOD: {
351 char *cname = g_strdup (error->class_name);
352 char *aname = g_strdup (error->member_name);
354 mono_loader_clear_error ();
355 ex = mono_get_exception_missing_method (cname, aname);
361 case MONO_EXCEPTION_MISSING_FIELD: {
363 char *cmembername = g_strdup (error->member_name);
365 class_name = mono_type_get_full_name (error->klass);
367 class_name = g_strdup ("");
369 mono_loader_clear_error ();
371 ex = mono_get_exception_missing_field (class_name, cmembername);
373 g_free (cmembername);
377 case MONO_EXCEPTION_FILE_NOT_FOUND: {
382 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);
384 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
385 filename = g_strdup (error->assembly_name);
386 /* Has to call this before calling anything which might call mono_class_init () */
387 mono_loader_clear_error ();
388 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
394 case MONO_EXCEPTION_BAD_IMAGE: {
395 char *msg = g_strdup (error->msg);
396 mono_loader_clear_error ();
397 ex = mono_get_exception_bad_image_format (msg);
403 g_assert_not_reached ();
410 * find_cached_memberref_sig:
412 * Return a cached copy of the memberref signature identified by SIG_IDX.
413 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
414 * A cache is needed since the type/signature parsing routines allocate everything
415 * from a mempool, so without a cache, multiple requests for the same signature would
416 * lead to unbounded memory growth. For normal methods/fields this is not a problem
417 * since the resulting methods/fields are cached, but inflated methods/fields cannot
419 * LOCKING: Acquires the loader lock.
422 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
426 mono_image_lock (image);
427 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
428 mono_image_unlock (image);
434 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
438 mono_image_lock (image);
439 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
441 /* Somebody got in before us */
445 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
446 /* An approximation based on glib 2.18 */
447 memberref_sig_cache_size += sizeof (gpointer) * 4;
449 mono_image_unlock (image);
454 static MonoClassField*
455 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
456 MonoGenericContext *context, MonoError *error)
458 MonoClass *klass = NULL;
459 MonoClassField *field;
460 MonoTableInfo *tables = image->tables;
463 guint32 nindex, class;
466 guint32 idx = mono_metadata_token_index (token);
468 mono_error_init (error);
470 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
471 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
472 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
474 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
476 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
477 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class, token);
482 case MONO_MEMBERREF_PARENT_TYPEDEF:
483 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
485 case MONO_MEMBERREF_PARENT_TYPEREF:
486 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
488 case MONO_MEMBERREF_PARENT_TYPESPEC:
489 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
492 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class, token);
498 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
499 mono_metadata_decode_blob_size (ptr, &ptr);
500 /* we may want to check the signature here... */
503 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class, fname, token);
507 /* FIXME: This needs a cache, especially for generic instances, since
508 * mono_metadata_parse_type () allocates everything from a mempool.
510 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
512 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
513 if (sig_type == NULL) {
514 mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x", fname, token);
517 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
520 mono_class_init (klass); /*FIXME is this really necessary?*/
523 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
526 mono_loader_assert_no_error ();
527 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
534 * mono_field_from_token:
535 * @deprecated use the _checked variant
538 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
541 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
542 mono_loader_assert_no_error ();
543 if (!mono_error_ok (&error)) {
544 mono_loader_set_error_from_mono_error (&error);
545 mono_error_cleanup (&error);
551 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
555 MonoClassField *field;
557 mono_error_init (error);
559 if (image_is_dynamic (image)) {
560 MonoClassField *result;
561 MonoClass *handle_class;
564 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
565 // This checks the memberref type as well
566 if (!result || handle_class != mono_defaults.fieldhandle_class) {
567 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
570 *retklass = result->parent;
574 if ((field = mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
575 *retklass = field->parent;
579 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
580 field = field_from_memberref (image, token, retklass, context, error);
581 mono_loader_assert_no_error ();
583 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
585 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
588 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
595 field = mono_class_get_field (k, token);
597 if (mono_loader_get_last_error ())
598 mono_error_set_from_loader_error (error);
600 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
604 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container) {
605 mono_image_lock (image);
606 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
607 mono_image_unlock (image);
610 mono_loader_assert_no_error ();
615 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
619 if (sig1->hasthis != sig2->hasthis ||
620 sig1->sentinelpos != sig2->sentinelpos)
623 for (i = 0; i < sig1->sentinelpos; i++) {
624 MonoType *p1 = sig1->params[i];
625 MonoType *p2 = sig2->params[i];
627 /*if (p1->attrs != p2->attrs)
630 if (!mono_metadata_type_equal (p1, p2))
634 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
640 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
641 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
645 /* Search directly in the metadata to avoid calling setup_methods () */
646 mono_error_init (error);
648 /* FIXME: !from_class->generic_class condition causes test failures. */
649 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
650 for (i = 0; i < klass->method.count; ++i) {
651 guint32 cols [MONO_METHOD_SIZE];
654 MonoMethodSignature *other_sig;
656 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
658 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
660 if (!((fqname && !strcmp (m_name, fqname)) ||
661 (qname && !strcmp (m_name, qname)) ||
662 (name && !strcmp (m_name, name))))
665 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
666 if (!mono_error_ok (error)) //bail out if we hit a loader error
669 other_sig = mono_method_signature_checked (method, error);
670 if (!mono_error_ok (error)) //bail out if we hit a loader error
672 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
678 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
680 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
681 See mono/tests/generic-type-load-exception.2.il
682 FIXME we should better report this error to the caller
684 if (!klass->methods || klass->exception_type) {
685 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
689 for (i = 0; i < klass->method.count; ++i) {
690 MonoMethod *m = klass->methods [i];
691 MonoMethodSignature *msig;
693 /* We must cope with failing to load some of the types. */
697 if (!((fqname && !strcmp (m->name, fqname)) ||
698 (qname && !strcmp (m->name, qname)) ||
699 (name && !strcmp (m->name, name))))
701 msig = mono_method_signature_checked (m, error);
702 if (!mono_error_ok (error)) //bail out if we hit a loader error
708 if (sig->call_convention == MONO_CALL_VARARG) {
709 if (mono_metadata_signature_vararg_match (sig, msig))
712 if (mono_metadata_signature_equal (sig, msig))
717 if (i < klass->method.count)
718 return mono_class_get_method_by_index (from_class, i);
723 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
726 char *qname, *fqname, *class_name;
727 gboolean is_interface;
728 MonoMethod *result = NULL;
729 MonoClass *initial_class = in_class;
731 mono_error_init (error);
732 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
735 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
737 qname = g_strconcat (class_name, ".", name, NULL);
738 if (ic->name_space && ic->name_space [0])
739 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
743 class_name = qname = fqname = NULL;
746 g_assert (from_class);
747 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
748 if (result || !mono_error_ok (error))
751 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
755 * This happens when we fail to lazily load the interfaces of one of the types.
756 * On such case we can't just bail out since user code depends on us trying harder.
758 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
759 in_class = in_class->parent;
760 from_class = from_class->parent;
764 for (i = 0; i < in_class->interface_offsets_count; i++) {
765 MonoClass *in_ic = in_class->interfaces_packed [i];
766 MonoClass *from_ic = from_class->interfaces_packed [i];
767 char *ic_qname, *ic_fqname, *ic_class_name;
769 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
770 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
771 if (in_ic->name_space && in_ic->name_space [0])
772 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
776 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
777 g_free (ic_class_name);
780 if (result || !mono_error_ok (error))
784 in_class = in_class->parent;
785 from_class = from_class->parent;
787 g_assert (!in_class == !from_class);
790 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
792 //we did not find the method
793 if (!result && mono_error_ok (error)) {
794 char *desc = mono_signature_get_desc (sig, FALSE);
795 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
806 static MonoMethodSignature*
807 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
809 MonoMethodSignature *res;
813 mono_error_init (error);
817 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
818 res->param_count = sig->param_count;
819 res->sentinelpos = -1;
820 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
821 if (!mono_error_ok (error))
823 is_open = mono_class_is_open_constructed_type (res->ret);
824 for (i = 0; i < sig->param_count; ++i) {
825 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
826 if (!mono_error_ok (error))
830 is_open = mono_class_is_open_constructed_type (res->params [i]);
832 res->hasthis = sig->hasthis;
833 res->explicit_this = sig->explicit_this;
834 res->call_convention = sig->call_convention;
835 res->pinvoke = sig->pinvoke;
836 res->generic_param_count = sig->generic_param_count;
837 res->sentinelpos = sig->sentinelpos;
838 res->has_type_parameters = is_open;
839 res->is_inflated = 1;
844 mono_metadata_free_type (res->ret);
845 for (i = 0; i < sig->param_count; ++i) {
847 mono_metadata_free_type (res->params [i]);
854 * mono_inflate_generic_signature:
856 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
859 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
861 MonoMethodSignature *res, *cached;
863 res = inflate_generic_signature_checked (NULL, sig, context, error);
864 if (!mono_error_ok (error))
866 cached = mono_metadata_get_inflated_signature (res, context);
868 mono_metadata_free_inflated_signature (res);
872 static MonoMethodHeader*
873 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
875 MonoMethodHeader *res;
877 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
878 res->code = header->code;
879 res->code_size = header->code_size;
880 res->max_stack = header->max_stack;
881 res->num_clauses = header->num_clauses;
882 res->init_locals = header->init_locals;
883 res->num_locals = header->num_locals;
884 res->clauses = header->clauses;
885 for (i = 0; i < header->num_locals; ++i)
886 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
887 if (res->num_clauses) {
888 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
889 for (i = 0; i < header->num_clauses; ++i) {
890 MonoExceptionClause *clause = &res->clauses [i];
891 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
893 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
900 * token is the method_ref/def/spec token used in a call IL instruction.
903 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
906 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
908 mono_loader_assert_no_error ();
911 g_assert (!mono_error_ok (&error));
912 mono_loader_set_error_from_mono_error (&error);
913 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
919 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
921 int table = mono_metadata_token_table (token);
922 int idx = mono_metadata_token_index (token);
924 guint32 cols [MONO_MEMBERREF_SIZE];
925 MonoMethodSignature *sig;
928 mono_error_init (error);
930 /* !table is for wrappers: we should really assign their own token to them */
931 if (!table || table == MONO_TABLE_METHOD)
932 return mono_method_signature_checked (method, error);
934 if (table == MONO_TABLE_METHODSPEC) {
935 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
936 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
939 return mono_method_signature_checked (method, error);
942 if (method->klass->generic_class)
943 return mono_method_signature_checked (method, error);
945 if (image_is_dynamic (image)) {
946 sig = mono_reflection_lookup_signature (image, method, token, error);
950 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
951 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
953 sig = find_cached_memberref_sig (image, sig_idx);
955 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
956 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
957 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
959 //FIXME include the verification error
960 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
964 ptr = mono_metadata_blob_heap (image, sig_idx);
965 mono_metadata_decode_blob_size (ptr, &ptr);
967 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
971 sig = cache_memberref_sig (image, sig_idx, sig);
973 /* FIXME: we probably should verify signature compat in the dynamic case too*/
974 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
975 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
976 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
978 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", class, fname, token);
984 MonoMethodSignature *cached;
986 /* This signature is not owned by a MonoMethod, so need to cache */
987 sig = inflate_generic_signature_checked (image, sig, context, error);
988 if (!mono_error_ok (error))
991 cached = mono_metadata_get_inflated_signature (sig, context);
993 mono_metadata_free_inflated_signature (sig);
995 inflated_signatures_size += mono_metadata_signature_size (cached);
999 g_assert (mono_error_ok (error));
1003 MonoMethodSignature*
1004 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
1007 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
1009 mono_loader_assert_no_error ();
1012 g_assert (!mono_error_ok (&error));
1013 mono_loader_set_error_from_mono_error (&error);
1014 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
1019 /* this is only for the typespec array methods */
1021 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1025 mono_class_setup_methods (klass);
1026 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
1027 for (i = 0; i < klass->method.count; ++i) {
1028 MonoMethod *method = klass->methods [i];
1029 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1036 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1037 gboolean *used_context, MonoError *error)
1039 MonoClass *klass = NULL;
1040 MonoMethod *method = NULL;
1041 MonoTableInfo *tables = image->tables;
1043 guint32 nindex, class, sig_idx;
1045 MonoMethodSignature *sig;
1048 mono_error_init (error);
1050 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1051 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1052 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1053 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1054 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1056 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1059 * Whether we actually used the `typespec_context' or not.
1060 * This is used to tell our caller whether or not it's safe to insert the returned
1061 * method into a cache.
1064 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
1067 case MONO_MEMBERREF_PARENT_TYPEREF:
1068 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1072 case MONO_MEMBERREF_PARENT_TYPESPEC:
1074 * Parse the TYPESPEC in the parent's context.
1076 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1080 case MONO_MEMBERREF_PARENT_TYPEDEF:
1081 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1085 case MONO_MEMBERREF_PARENT_METHODDEF: {
1086 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1092 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class, nindex);
1097 mono_class_init (klass);
1099 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1101 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1102 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1106 ptr = mono_metadata_blob_heap (image, sig_idx);
1107 mono_metadata_decode_blob_size (ptr, &ptr);
1109 sig = find_cached_memberref_sig (image, sig_idx);
1111 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1115 sig = cache_memberref_sig (image, sig_idx, sig);
1119 case MONO_MEMBERREF_PARENT_TYPEREF:
1120 case MONO_MEMBERREF_PARENT_TYPEDEF:
1121 method = find_method (klass, NULL, mname, sig, klass, error);
1124 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1127 type = &klass->byval_arg;
1129 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1130 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1131 method = find_method (in_class, NULL, mname, sig, klass, error);
1135 /* we're an array and we created these methods already in klass in mono_class_init () */
1136 method = mono_method_search_in_array_class (klass, mname, sig);
1140 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class, nindex);
1144 if (!method && mono_error_ok (error)) {
1145 char *msig = mono_signature_get_desc (sig, FALSE);
1146 GString *s = g_string_new (mname);
1147 if (sig->generic_param_count)
1148 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1149 g_string_append_printf (s, "(%s)", msig);
1151 msig = g_string_free (s, FALSE);
1153 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1154 mono_error_set_from_loader_error (error);
1156 mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1161 mono_loader_assert_no_error ();
1165 mono_loader_assert_no_error ();
1166 g_assert (!mono_error_ok (error));
1171 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1175 MonoTableInfo *tables = image->tables;
1176 MonoGenericContext new_context;
1177 MonoGenericInst *inst;
1179 guint32 cols [MONO_METHODSPEC_SIZE];
1180 guint32 token, nindex, param_count;
1182 mono_error_init (error);
1184 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1185 token = cols [MONO_METHODSPEC_METHOD];
1186 nindex = token >> MONO_METHODDEFORREF_BITS;
1188 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1189 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1193 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1195 mono_metadata_decode_value (ptr, &ptr);
1197 param_count = mono_metadata_decode_value (ptr, &ptr);
1199 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr, error);
1203 if (context && inst->is_open) {
1204 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1205 if (!mono_error_ok (error))
1209 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1210 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1214 method = method_from_memberref (image, nindex, context, NULL, error);
1220 klass = method->klass;
1222 if (klass->generic_class) {
1223 g_assert (method->is_inflated);
1224 method = ((MonoMethodInflated *) method)->declaring;
1227 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1228 new_context.method_inst = inst;
1230 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1231 mono_loader_assert_no_error ();
1235 struct _MonoDllMap {
1243 static MonoDllMap *global_dll_map;
1246 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1254 global_loader_data_lock ();
1257 * we use the first entry we find that matches, since entries from
1258 * the config file are prepended to the list and we document that the
1259 * later entries win.
1261 for (; dll_map; dll_map = dll_map->next) {
1262 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1263 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1265 } else if (strcmp (dll_map->dll, dll)) {
1268 if (!found && dll_map->target) {
1269 *rdll = dll_map->target;
1271 /* we don't quit here, because we could find a full
1272 * entry that matches also function and that has priority.
1275 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1276 *rfunc = dll_map->target_func;
1281 global_loader_data_unlock ();
1286 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1289 if (assembly && assembly->dll_map) {
1290 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1294 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1298 * mono_dllmap_insert:
1299 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1300 * @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
1301 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1302 * @tdll: The name of the library to map the specified @dll if it matches.
1303 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1305 * LOCKING: Acquires the loader lock.
1307 * This function is used to programatically add DllImport remapping in either
1308 * a specific assembly, or as a global remapping. This is done by remapping
1309 * references in a DllImport attribute from the @dll library name into the @tdll
1310 * name. If the @dll name contains the prefix "i:", the comparison of the
1311 * library name is done without case sensitivity.
1313 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1314 * or the name of the function as determined by DllImport. If you pass @func, you
1315 * must also pass @tfunc which is the name of the target function to invoke on a match.
1318 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1320 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1321 * the contents of relocated_demo_path for all assemblies in the Mono process.
1323 * NOTE: This can be called before the runtime is initialized, for example from
1324 * mono_config_parse ().
1327 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1331 mono_loader_init ();
1334 entry = g_malloc0 (sizeof (MonoDllMap));
1335 entry->dll = dll? g_strdup (dll): NULL;
1336 entry->target = tdll? g_strdup (tdll): NULL;
1337 entry->func = func? g_strdup (func): NULL;
1338 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1340 global_loader_data_lock ();
1341 entry->next = global_dll_map;
1342 global_dll_map = entry;
1343 global_loader_data_unlock ();
1345 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1346 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1347 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1348 entry->func = func? mono_image_strdup (assembly, func): NULL;
1349 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1351 mono_image_lock (assembly);
1352 entry->next = assembly->dll_map;
1353 assembly->dll_map = entry;
1354 mono_image_unlock (assembly);
1359 free_dllmap (MonoDllMap *map)
1362 MonoDllMap *next = map->next;
1365 g_free (map->target);
1367 g_free (map->target_func);
1374 dllmap_cleanup (void)
1376 free_dllmap (global_dll_map);
1377 global_dll_map = NULL;
1380 static GHashTable *global_module_map;
1383 cached_module_load (const char *name, int flags, char **err)
1389 global_loader_data_lock ();
1390 if (!global_module_map)
1391 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1392 res = g_hash_table_lookup (global_module_map, name);
1394 global_loader_data_unlock ();
1397 res = mono_dl_open (name, flags, err);
1399 g_hash_table_insert (global_module_map, g_strdup (name), res);
1400 global_loader_data_unlock ();
1404 static MonoDl *internal_module;
1407 is_absolute_path (const char *path)
1409 #ifdef PLATFORM_MACOSX
1410 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1411 !strncmp (path, "@rpath/", 7))
1414 return g_path_is_absolute (path);
1418 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1420 MonoImage *image = method->klass->image;
1421 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1422 MonoTableInfo *tables = image->tables;
1423 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1424 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1425 guint32 im_cols [MONO_IMPLMAP_SIZE];
1426 guint32 scope_token;
1427 const char *import = NULL;
1428 const char *orig_scope;
1429 const char *new_scope;
1431 char *full_name, *file_name, *found_name = NULL;
1433 MonoDl *module = NULL;
1434 gboolean cached = FALSE;
1436 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1444 return piinfo->addr;
1446 if (image_is_dynamic (method->klass->image)) {
1447 MonoReflectionMethodAux *method_aux =
1448 g_hash_table_lookup (
1449 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1453 import = method_aux->dllentry;
1454 orig_scope = method_aux->dll;
1457 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1460 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1462 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1465 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1466 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1467 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1468 orig_scope = mono_metadata_string_heap (image, scope_token);
1471 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1474 mono_image_lock (image);
1475 if (!image->pinvoke_scopes) {
1476 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1477 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1479 module = g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1480 found_name = g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1481 mono_image_unlock (image);
1485 found_name = g_strdup (found_name);
1489 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1490 "DllImport attempting to load: '%s'.", new_scope);
1492 /* we allow a special name to dlopen from the running process namespace */
1493 if (strcmp (new_scope, "__Internal") == 0){
1494 if (internal_module == NULL)
1495 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1496 module = internal_module;
1501 * Try loading the module using a variety of names
1503 for (i = 0; i < 5; ++i) {
1504 char *base_name = NULL, *dir_name = NULL;
1505 gboolean is_absolute = is_absolute_path (new_scope);
1509 /* Try the original name */
1510 file_name = g_strdup (new_scope);
1513 /* Try trimming the .dll extension */
1514 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1515 file_name = g_strdup (new_scope);
1516 file_name [strlen (new_scope) - 4] = '\0';
1523 dir_name = g_path_get_dirname (new_scope);
1524 base_name = g_path_get_basename (new_scope);
1525 if (strstr (base_name, "lib") != base_name) {
1526 char *tmp = g_strdup_printf ("lib%s", base_name);
1529 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1532 } else if (strstr (new_scope, "lib") != new_scope) {
1533 file_name = g_strdup_printf ("lib%s", new_scope);
1538 if (!is_absolute && mono_dl_get_system_dir ()) {
1539 dir_name = (char*)mono_dl_get_system_dir ();
1540 file_name = g_path_get_basename (new_scope);
1546 #ifndef TARGET_WIN32
1547 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1548 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1549 !g_ascii_strcasecmp ("user32", new_scope) ||
1550 !g_ascii_strcasecmp ("kernel", new_scope)) {
1551 file_name = g_strdup ("libMonoSupportW.so");
1555 #ifndef TARGET_WIN32
1562 dir_name = g_path_get_dirname (file_name);
1564 base_name = g_path_get_basename (file_name);
1567 if (!module && is_absolute) {
1568 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1570 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1571 "DllImport error loading library '%s': '%s'.",
1572 file_name, error_msg);
1575 found_name = g_strdup (file_name);
1579 if (!module && !is_absolute) {
1583 for (j = 0; j < 3; ++j) {
1588 mdirname = g_path_get_dirname (image->name);
1590 case 1: /* @executable_path@/../lib */
1594 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1596 char *base, *newbase;
1599 resolvedname = mono_path_resolve_symlinks (buf);
1601 base = g_path_get_dirname (resolvedname);
1602 newbase = g_path_get_dirname(base);
1603 mdirname = g_strdup_printf ("%s/lib", newbase);
1605 g_free (resolvedname);
1612 case 2: /* @executable_path@/../Libraries */
1616 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1618 char *base, *newbase;
1621 resolvedname = mono_path_resolve_symlinks (buf);
1623 base = g_path_get_dirname (resolvedname);
1624 newbase = g_path_get_dirname(base);
1625 mdirname = g_strdup_printf ("%s/Libraries", newbase);
1627 g_free (resolvedname);
1639 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1640 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1642 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1643 "DllImport error loading library '%s': '%s'.",
1644 full_name, error_msg);
1647 found_name = g_strdup (full_name);
1663 char *file_or_base = is_absolute ? base_name : file_name;
1664 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1665 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1667 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1668 "DllImport error loading library '%s': '%s'.",
1669 full_name, error_msg);
1672 found_name = g_strdup (full_name);
1681 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1683 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1684 "DllImport error loading library '%s': '%s'.",
1685 file_name, error_msg);
1687 found_name = g_strdup (file_name);
1702 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1703 "DllImport unable to load library '%s'.",
1708 *exc_class = "DllNotFoundException";
1709 *exc_arg = new_scope;
1715 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1716 "DllImport loaded library '%s'.", found_name);
1717 mono_image_lock (image);
1718 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1719 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1720 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1722 mono_image_unlock (image);
1725 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1726 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1727 g_free (found_name);
1730 if (import && import [0] == '#' && isdigit (import [1])) {
1734 id = strtol (import + 1, &end, 10);
1735 if (id > 0 && *end == '\0')
1739 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1740 "Searching for '%s'.", import);
1742 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1743 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1745 char *mangled_name = NULL, *mangled_name2 = NULL;
1748 int mangle_param_count;
1754 * Search using a variety of mangled names
1756 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1757 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1758 gboolean need_param_count = FALSE;
1760 if (mangle_stdcall > 0)
1761 need_param_count = TRUE;
1763 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1768 mangled_name = (char*)import;
1769 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1770 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1771 /* Try the mangled name first */
1772 if (mangle_charset == 0)
1773 mangled_name = g_strconcat (import, "W", NULL);
1775 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1777 if (mangle_charset == 0)
1778 mangled_name = g_strconcat (import, "W", NULL);
1780 /* Try the mangled name last */
1781 if (mangle_charset == 1)
1782 mangled_name = g_strconcat (import, "A", NULL);
1785 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1787 /* Try the mangled name last */
1788 if (mangle_charset == 1)
1789 mangled_name = g_strconcat (import, "A", NULL);
1794 if (mangle_param_count == 0)
1795 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1797 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1798 param_count = mangle_param_count;
1800 /* Try the stdcall mangled name */
1802 * gcc under windows creates mangled names without the underscore, but MS.NET
1803 * doesn't support it, so we doesn't support it either.
1805 if (mangle_stdcall == 1)
1806 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1808 mangled_name2 = mangled_name;
1810 mangled_name2 = mangled_name;
1813 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1814 "Probing '%s'.", mangled_name2);
1816 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1819 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1820 "Found as '%s'.", mangled_name2);
1822 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1823 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1828 if (mangled_name != mangled_name2)
1829 g_free (mangled_name2);
1830 if (mangled_name != import)
1831 g_free (mangled_name);
1837 if (!piinfo->addr) {
1840 *exc_class = "EntryPointNotFoundException";
1845 return piinfo->addr;
1849 * LOCKING: assumes the loader lock to be taken.
1852 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1853 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1856 int table = mono_metadata_token_table (token);
1857 int idx = mono_metadata_token_index (token);
1858 MonoTableInfo *tables = image->tables;
1859 MonoGenericContainer *generic_container = NULL, *container = NULL;
1860 const char *sig = NULL;
1861 guint32 cols [MONO_TYPEDEF_SIZE];
1863 mono_error_init (error);
1865 if (image_is_dynamic (image)) {
1866 MonoClass *handle_class;
1868 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1869 mono_loader_assert_no_error ();
1871 // This checks the memberref type as well
1872 if (result && handle_class != mono_defaults.methodhandle_class) {
1873 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1879 if (table != MONO_TABLE_METHOD) {
1880 if (table == MONO_TABLE_METHODSPEC) {
1881 if (used_context) *used_context = TRUE;
1882 return method_from_methodspec (image, context, idx, error);
1884 if (table != MONO_TABLE_MEMBERREF) {
1885 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1888 return method_from_memberref (image, idx, context, used_context, error);
1891 if (used_context) *used_context = FALSE;
1893 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1894 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1899 guint32 type = mono_metadata_typedef_from_method (image, token);
1901 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1904 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1909 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1911 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1912 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1913 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1915 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1916 methods_size += sizeof (MonoMethod);
1919 mono_stats.method_count ++;
1922 result->klass = klass;
1923 result->flags = cols [2];
1924 result->iflags = cols [1];
1925 result->token = token;
1926 result->name = mono_metadata_string_heap (image, cols [3]);
1928 if (!sig) /* already taken from the methodref */
1929 sig = mono_metadata_blob_heap (image, cols [4]);
1930 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1932 container = klass->generic_container;
1935 * load_generic_params does a binary search so only call it if the method
1939 generic_container = mono_metadata_load_generic_params (image, token, container);
1940 mono_loader_assert_no_error (); /* FIXME don't swallow this error. */
1942 if (generic_container) {
1943 result->is_generic = TRUE;
1944 generic_container->owner.method = result;
1945 /*FIXME put this before the image alloc*/
1946 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1949 container = generic_container;
1952 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1953 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1954 result->string_ctor = 1;
1955 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1956 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1959 /* IJW is P/Invoke with a predefined function pointer. */
1960 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1961 piinfo->addr = mono_image_rva_map (image, cols [0]);
1962 g_assert (piinfo->addr);
1965 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1966 /* Native methods can have no map. */
1967 if (piinfo->implmap_idx)
1968 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1971 if (generic_container)
1972 mono_method_set_generic_container (result, generic_container);
1974 mono_loader_assert_no_error ();
1979 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1981 return mono_get_method_full (image, token, klass, NULL);
1985 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1986 MonoGenericContext *context)
1989 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
1990 mono_loader_assert_no_error ();
1991 if (!mono_error_ok (&error)) {
1992 mono_loader_set_error_from_mono_error (&error);
1993 mono_error_cleanup (&error);
1999 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
2001 MonoMethod *result = NULL;
2002 gboolean used_context = FALSE;
2004 /* We do everything inside the lock to prevent creation races */
2006 mono_error_init (error);
2008 mono_image_lock (image);
2010 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
2011 if (!image->method_cache)
2012 image->method_cache = g_hash_table_new (NULL, NULL);
2013 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2014 } else if (!image_is_dynamic (image)) {
2015 if (!image->methodref_cache)
2016 image->methodref_cache = g_hash_table_new (NULL, NULL);
2017 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2019 mono_image_unlock (image);
2025 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
2029 mono_image_lock (image);
2030 if (!used_context && !result->is_inflated) {
2031 MonoMethod *result2 = NULL;
2033 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2034 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2035 else if (!image_is_dynamic (image))
2036 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2039 mono_image_unlock (image);
2043 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2044 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
2045 else if (!image_is_dynamic (image))
2046 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
2049 mono_image_unlock (image);
2055 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
2058 MonoClass *ic = NULL;
2059 MonoGenericContext *method_context = NULL;
2060 MonoMethodSignature *sig, *original_sig;
2062 mono_error_init (error);
2064 mono_class_init (constrained_class);
2065 original_sig = sig = mono_method_signature_checked (method, error);
2070 if (method->is_inflated && sig->generic_param_count) {
2071 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2072 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
2075 method_context = mono_method_get_context (method);
2079 * We must inflate the signature with the class instantiation to work on
2080 * cases where a class inherit from a generic type and the override replaces
2081 * any type argument which a concrete type. See #325283.
2083 if (method_context->class_inst) {
2084 MonoGenericContext ctx;
2085 ctx.method_inst = NULL;
2086 ctx.class_inst = method_context->class_inst;
2087 /*Fixme, property propagate this error*/
2088 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2094 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2097 result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2098 if (sig != original_sig)
2099 mono_metadata_free_inflated_signature (sig);
2104 if (method_context) {
2105 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2114 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2115 MonoGenericContext *context, MonoError *error)
2119 return get_method_constrained (image, method, constrained_class, context, error);
2123 * mono_get_method_constrained:
2125 * This is used when JITing the `constrained.' opcode.
2127 * This returns two values: the contrained method, which has been inflated
2128 * as the function return value; And the original CIL-stream method as
2129 * declared in cil_method. The later is used for verification.
2132 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2133 MonoGenericContext *context, MonoMethod **cil_method)
2136 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2138 mono_loader_assert_no_error ();
2139 if (!mono_error_ok (&error)) {
2140 mono_loader_set_error_from_mono_error (&error);
2141 mono_error_cleanup (&error);
2147 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2149 mono_error_init (error);
2151 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2155 return get_method_constrained (image, *cil_method, constrained_class, context, error);
2159 mono_free_method (MonoMethod *method)
2161 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2162 mono_profiler_method_free (method);
2164 /* FIXME: This hack will go away when the profiler will support freeing methods */
2165 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2168 if (method->signature) {
2170 * FIXME: This causes crashes because the types inside signatures and
2171 * locals are shared.
2173 /* mono_metadata_free_method_signature (method->signature); */
2174 /* g_free (method->signature); */
2177 if (method_is_dynamic (method)) {
2178 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2181 mono_marshal_free_dynamic_wrappers (method);
2183 mono_image_property_remove (method->klass->image, method);
2185 g_free ((char*)method->name);
2187 g_free ((char*)mw->header->code);
2188 for (i = 0; i < mw->header->num_locals; ++i)
2189 g_free (mw->header->locals [i]);
2190 g_free (mw->header->clauses);
2191 g_free (mw->header);
2193 g_free (mw->method_data);
2194 g_free (method->signature);
2200 mono_method_get_param_names (MonoMethod *method, const char **names)
2204 MonoTableInfo *methodt;
2205 MonoTableInfo *paramt;
2206 MonoMethodSignature *signature;
2209 if (method->is_inflated)
2210 method = ((MonoMethodInflated *) method)->declaring;
2212 signature = mono_method_signature (method);
2213 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2214 number of arguments and allocate a properly sized array. */
2215 if (signature == NULL)
2218 if (!signature->param_count)
2221 for (i = 0; i < signature->param_count; ++i)
2224 klass = method->klass;
2228 mono_class_init (klass);
2230 if (image_is_dynamic (klass->image)) {
2231 MonoReflectionMethodAux *method_aux =
2232 g_hash_table_lookup (
2233 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2234 if (method_aux && method_aux->param_names) {
2235 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2236 if (method_aux->param_names [i + 1])
2237 names [i] = method_aux->param_names [i + 1];
2242 if (method->wrapper_type) {
2243 char **pnames = NULL;
2245 mono_image_lock (klass->image);
2246 if (klass->image->wrapper_param_names)
2247 pnames = g_hash_table_lookup (klass->image->wrapper_param_names, method);
2248 mono_image_unlock (klass->image);
2251 for (i = 0; i < signature->param_count; ++i)
2252 names [i] = pnames [i];
2257 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2258 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2259 idx = mono_method_get_index (method);
2261 guint32 cols [MONO_PARAM_SIZE];
2264 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2266 if (idx < methodt->rows)
2267 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2269 lastp = paramt->rows + 1;
2270 for (i = param_index; i < lastp; ++i) {
2271 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2272 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2273 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2279 mono_method_get_param_token (MonoMethod *method, int index)
2281 MonoClass *klass = method->klass;
2282 MonoTableInfo *methodt;
2285 mono_class_init (klass);
2287 if (image_is_dynamic (klass->image))
2288 g_assert_not_reached ();
2290 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2291 idx = mono_method_get_index (method);
2293 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2297 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2299 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2306 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2309 MonoClass *klass = method->klass;
2310 MonoTableInfo *methodt;
2311 MonoTableInfo *paramt;
2312 MonoMethodSignature *signature;
2315 signature = mono_method_signature (method);
2316 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2318 for (i = 0; i < signature->param_count + 1; ++i)
2321 if (image_is_dynamic (method->klass->image)) {
2322 MonoReflectionMethodAux *method_aux =
2323 g_hash_table_lookup (
2324 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2325 if (method_aux && method_aux->param_marshall) {
2326 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2327 for (i = 0; i < signature->param_count + 1; ++i)
2328 if (dyn_specs [i]) {
2329 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2330 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2331 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2332 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2338 mono_class_init (klass);
2340 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2341 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2342 idx = mono_method_get_index (method);
2344 guint32 cols [MONO_PARAM_SIZE];
2345 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2347 if (idx < methodt->rows)
2348 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2350 lastp = paramt->rows + 1;
2352 for (i = param_index; i < lastp; ++i) {
2353 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2355 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2357 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2359 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2368 mono_method_has_marshal_info (MonoMethod *method)
2371 MonoClass *klass = method->klass;
2372 MonoTableInfo *methodt;
2373 MonoTableInfo *paramt;
2376 if (image_is_dynamic (method->klass->image)) {
2377 MonoReflectionMethodAux *method_aux =
2378 g_hash_table_lookup (
2379 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2380 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2382 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2389 mono_class_init (klass);
2391 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2392 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2393 idx = mono_method_get_index (method);
2395 guint32 cols [MONO_PARAM_SIZE];
2396 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2398 if (idx + 1 < methodt->rows)
2399 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2401 lastp = paramt->rows + 1;
2403 for (i = param_index; i < lastp; ++i) {
2404 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2406 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2415 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2418 g_assert (method != NULL);
2419 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2421 if (method->is_inflated)
2422 method = ((MonoMethodInflated *) method)->declaring;
2423 data = ((MonoMethodWrapper *)method)->method_data;
2424 g_assert (data != NULL);
2425 g_assert (id <= GPOINTER_TO_UINT (*data));
2432 } StackWalkUserData;
2435 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2437 StackWalkUserData *d = data;
2439 switch (frame->type) {
2440 case FRAME_TYPE_DEBUGGER_INVOKE:
2441 case FRAME_TYPE_MANAGED_TO_NATIVE:
2442 case FRAME_TYPE_TRAMPOLINE:
2444 case FRAME_TYPE_MANAGED:
2445 g_assert (frame->ji);
2446 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2449 g_assert_not_reached ();
2455 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2457 StackWalkUserData ud = { func, user_data };
2458 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2462 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2464 StackWalkUserData ud = { func, user_data };
2465 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2469 MonoStackWalkAsyncSafe func;
2471 } AsyncStackWalkUserData;
2475 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2477 AsyncStackWalkUserData *d = data;
2479 switch (frame->type) {
2480 case FRAME_TYPE_DEBUGGER_INVOKE:
2481 case FRAME_TYPE_MANAGED_TO_NATIVE:
2482 case FRAME_TYPE_TRAMPOLINE:
2484 case FRAME_TYPE_MANAGED:
2487 if (frame->ji->async) {
2488 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2490 return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2494 g_assert_not_reached ();
2501 * mono_stack_walk_async_safe:
2503 * Async safe version callable from signal handlers.
2506 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2509 AsyncStackWalkUserData ud = { func, user_data };
2511 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2512 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2516 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2518 MonoMethod **dest = data;
2520 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2526 mono_method_get_last_managed (void)
2528 MonoMethod *m = NULL;
2529 mono_stack_walk_no_il (last_managed, &m);
2533 static gboolean loader_lock_track_ownership = FALSE;
2538 * See docs/thread-safety.txt for the locking strategy.
2541 mono_loader_lock (void)
2544 mono_locks_acquire (&loader_mutex, LoaderLock);
2545 MONO_FINISH_TRY_BLOCKING;
2547 if (G_UNLIKELY (loader_lock_track_ownership)) {
2548 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));
2553 mono_loader_unlock (void)
2555 mono_locks_release (&loader_mutex, LoaderLock);
2556 if (G_UNLIKELY (loader_lock_track_ownership)) {
2557 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));
2562 * mono_loader_lock_track_ownership:
2564 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2565 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2566 * thread owns the loader lock.
2569 mono_loader_lock_track_ownership (gboolean track)
2571 loader_lock_track_ownership = track;
2575 * mono_loader_lock_is_owned_by_self:
2577 * Return whenever the current thread owns the loader lock.
2578 * This is useful to avoid blocking operations while holding the loader lock.
2581 mono_loader_lock_is_owned_by_self (void)
2583 g_assert (loader_lock_track_ownership);
2585 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2589 * mono_loader_lock_if_inited:
2591 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2592 * be used in runtime initialization code which can be executed before mono_loader_init ().
2595 mono_loader_lock_if_inited (void)
2597 if (loader_lock_inited)
2598 mono_loader_lock ();
2602 mono_loader_unlock_if_inited (void)
2604 if (loader_lock_inited)
2605 mono_loader_unlock ();
2609 * mono_method_signature:
2611 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2613 MonoMethodSignature*
2614 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2619 gboolean can_cache_signature;
2620 MonoGenericContainer *container;
2621 MonoMethodSignature *signature = NULL, *sig2;
2624 /* We need memory barriers below because of the double-checked locking pattern */
2626 mono_error_init (error);
2629 return m->signature;
2631 img = m->klass->image;
2633 if (m->is_inflated) {
2634 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2635 /* the lock is recursive */
2636 signature = mono_method_signature (imethod->declaring);
2637 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2638 if (!mono_error_ok (error))
2641 inflated_signatures_size += mono_metadata_signature_size (signature);
2643 mono_image_lock (img);
2645 mono_memory_barrier ();
2647 m->signature = signature;
2649 mono_image_unlock (img);
2651 return m->signature;
2654 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2655 idx = mono_metadata_token_index (m->token);
2657 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2659 g_assert (!m->klass->generic_class);
2660 container = mono_method_get_generic_container (m);
2662 container = m->klass->generic_container;
2664 /* Generic signatures depend on the container so they cannot be cached */
2665 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2666 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2668 /* If the method has parameter attributes, that can modify the signature */
2669 if (mono_metadata_method_has_param_attrs (img, idx))
2670 can_cache_signature = FALSE;
2672 if (can_cache_signature) {
2673 mono_image_lock (img);
2674 signature = g_hash_table_lookup (img->method_signatures, sig);
2675 mono_image_unlock (img);
2679 const char *sig_body;
2680 /*TODO we should cache the failure result somewhere*/
2681 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2684 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2686 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2690 if (can_cache_signature) {
2691 mono_image_lock (img);
2692 sig2 = g_hash_table_lookup (img->method_signatures, sig);
2694 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2695 mono_image_unlock (img);
2698 signatures_size += mono_metadata_signature_size (signature);
2701 /* Verify metadata consistency */
2702 if (signature->generic_param_count) {
2703 if (!container || !container->is_method) {
2704 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);
2707 if (container->type_argc != signature->generic_param_count) {
2708 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);
2711 } else if (container && container->is_method && container->type_argc) {
2712 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);
2715 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2716 signature->pinvoke = 1;
2717 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2718 MonoCallConvention conv = 0;
2719 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2720 signature->pinvoke = 1;
2722 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2723 case 0: /* no call conv, so using default */
2724 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2725 conv = MONO_CALL_DEFAULT;
2727 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2730 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2731 conv = MONO_CALL_STDCALL;
2733 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2734 conv = MONO_CALL_THISCALL;
2736 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2737 conv = MONO_CALL_FASTCALL;
2739 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2740 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2742 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);
2745 signature->call_convention = conv;
2748 mono_image_lock (img);
2750 mono_memory_barrier ();
2752 m->signature = signature;
2754 mono_image_unlock (img);
2756 return m->signature;
2760 * mono_method_signature:
2762 * Return the signature of the method M. On failure, returns NULL.
2764 MonoMethodSignature*
2765 mono_method_signature (MonoMethod *m)
2768 MonoMethodSignature *sig;
2770 sig = mono_method_signature_checked (m, &error);
2772 char *type_name = mono_type_get_full_name (m->klass);
2773 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2775 mono_error_cleanup (&error);
2782 mono_method_get_name (MonoMethod *method)
2784 return method->name;
2788 mono_method_get_class (MonoMethod *method)
2790 return method->klass;
2794 mono_method_get_token (MonoMethod *method)
2796 return method->token;
2800 mono_method_get_header (MonoMethod *method)
2806 MonoMethodHeader *header;
2807 MonoGenericContainer *container;
2809 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))
2812 img = method->klass->image;
2814 if (method->is_inflated) {
2815 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2816 MonoMethodHeader *header, *iheader;
2818 header = mono_method_get_header (imethod->declaring);
2822 iheader = inflate_generic_header (header, mono_method_get_context (method));
2823 mono_metadata_free_mh (header);
2825 mono_image_lock (img);
2827 if (imethod->header) {
2828 mono_metadata_free_mh (iheader);
2829 mono_image_unlock (img);
2830 return imethod->header;
2833 mono_memory_barrier ();
2834 imethod->header = iheader;
2836 mono_image_unlock (img);
2838 return imethod->header;
2841 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2842 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2843 g_assert (mw->header);
2848 * We don't need locks here: the new header is allocated from malloc memory
2849 * and is not stored anywhere in the runtime, the user needs to free it.
2851 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2852 idx = mono_metadata_token_index (method->token);
2853 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2855 if (!mono_verifier_verify_method_header (img, rva, NULL))
2858 loc = mono_image_rva_map (img, rva);
2863 * When parsing the types of local variables, we must pass any container available
2864 * to ensure that both VAR and MVAR will get the right owner.
2866 container = mono_method_get_generic_container (method);
2868 container = method->klass->generic_container;
2869 header = mono_metadata_parse_mh_full (img, container, loc);
2875 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2878 *iflags = method->iflags;
2879 return method->flags;
2883 * Find the method index in the metadata methodDef table.
2886 mono_method_get_index (MonoMethod *method)
2888 MonoClass *klass = method->klass;
2892 /* constructed array methods are not in the MethodDef table */
2896 return mono_metadata_token_index (method->token);
2898 mono_class_setup_methods (klass);
2899 if (klass->exception_type)
2901 for (i = 0; i < klass->method.count; ++i) {
2902 if (method == klass->methods [i]) {
2903 if (klass->image->uncompressed_metadata)
2904 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2906 return klass->method.first + i + 1;