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>
49 MonoDefaults mono_defaults;
52 * This lock protects the hash tables inside MonoImage used by the metadata
53 * loading functions in class.c and loader.c.
55 * See domain-internals.h for locking policy in combination with the
58 static mono_mutex_t loader_mutex, global_loader_data_mutex;
59 static gboolean loader_lock_inited;
62 static guint32 inflated_signatures_size;
63 static guint32 memberref_sig_cache_size;
64 static guint32 methods_size;
65 static guint32 signatures_size;
68 * This TLS variable contains the last type load error encountered by the loader.
70 MonoNativeTlsKey loader_error_thread_id;
73 * This TLS variable holds how many times the current thread has acquired the loader
76 MonoNativeTlsKey loader_lock_nest_id;
78 static void dllmap_cleanup (void);
82 global_loader_data_lock (void)
84 mono_locks_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
88 global_loader_data_unlock (void)
90 mono_locks_release (&global_loader_data_mutex, LoaderGlobalDataLock);
96 static gboolean inited;
99 mono_mutex_init_recursive (&loader_mutex);
100 mono_mutex_init_recursive (&global_loader_data_mutex);
101 loader_lock_inited = TRUE;
103 mono_native_tls_alloc (&loader_error_thread_id, NULL);
104 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
106 mono_counters_register ("Inflated signatures size",
107 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
108 mono_counters_register ("Memberref signature cache size",
109 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
110 mono_counters_register ("MonoMethod size",
111 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
112 mono_counters_register ("MonoMethodSignature size",
113 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
120 mono_loader_cleanup (void)
124 mono_native_tls_free (loader_error_thread_id);
125 mono_native_tls_free (loader_lock_nest_id);
127 mono_mutex_destroy (&loader_mutex);
128 mono_mutex_destroy (&global_loader_data_mutex);
129 loader_lock_inited = FALSE;
133 * Handling of type load errors should be done as follows:
135 * If something could not be loaded, the loader should call one of the
136 * mono_loader_set_error_XXX functions ()
137 * with the appropriate arguments, then return NULL to report the failure. The error
138 * should be propagated until it reaches code which can throw managed exceptions. At that
139 * point, an exception should be thrown based on the information returned by
140 * mono_loader_get_last_error (). Then the error should be cleared by calling
141 * mono_loader_clear_error ().
145 set_loader_error (MonoLoaderError *error)
147 mono_loader_clear_error ();
148 mono_native_tls_set_value (loader_error_thread_id, error);
152 * mono_loader_set_error_assembly_load:
154 * Set the loader error for this thread.
157 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
159 MonoLoaderError *error;
161 if (mono_loader_get_last_error ())
164 error = g_new0 (MonoLoaderError, 1);
165 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
166 error->assembly_name = g_strdup (assembly_name);
167 error->ref_only = ref_only;
170 * This is not strictly needed, but some (most) of the loader code still
171 * can't deal with load errors, and this message is more helpful than an
175 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);
177 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
179 set_loader_error (error);
183 * mono_loader_set_error_type_load:
185 * Set the loader error for this thread.
188 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
190 MonoLoaderError *error;
192 if (mono_loader_get_last_error ())
195 error = g_new0 (MonoLoaderError, 1);
196 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
197 error->class_name = g_strdup (class_name);
198 error->assembly_name = g_strdup (assembly_name);
201 * This is not strictly needed, but some (most) of the loader code still
202 * can't deal with load errors, and this message is more helpful than an
205 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
207 set_loader_error (error);
211 * mono_loader_set_error_method_load:
213 * Set the loader error for this thread. MEMBER_NAME should point to a string
217 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
219 MonoLoaderError *error;
221 /* FIXME: Store the signature as well */
222 if (mono_loader_get_last_error ())
225 error = g_new0 (MonoLoaderError, 1);
226 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
227 error->class_name = g_strdup (class_name);
228 error->member_name = member_name;
230 set_loader_error (error);
234 * mono_loader_set_error_field_load:
236 * Set the loader error for this thread. MEMBER_NAME should point to a string
240 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
242 MonoLoaderError *error;
244 /* FIXME: Store the signature as well */
245 if (mono_loader_get_last_error ())
248 error = g_new0 (MonoLoaderError, 1);
249 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
250 error->klass = klass;
251 error->member_name = member_name;
253 set_loader_error (error);
257 * mono_loader_set_error_bad_image:
259 * Set the loader error for this thread.
262 mono_loader_set_error_bad_image (char *msg)
264 MonoLoaderError *error;
266 if (mono_loader_get_last_error ())
269 error = g_new0 (MonoLoaderError, 1);
270 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
273 set_loader_error (error);
278 * mono_loader_get_last_error:
280 * Returns information about the last type load exception encountered by the loader, or
281 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
284 mono_loader_get_last_error (void)
286 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
290 * mono_loader_clear_error:
292 * Disposes any loader error messages on this thread
295 mono_loader_clear_error (void)
297 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
300 g_free (ex->class_name);
301 g_free (ex->assembly_name);
305 mono_native_tls_set_value (loader_error_thread_id, NULL);
310 * mono_loader_error_prepare_exception:
311 * @error: The MonoLoaderError to turn into an exception
313 * This turns a MonoLoaderError into an exception that can be thrown
314 * and resets the Mono Loader Error state during this process.
318 mono_loader_error_prepare_exception (MonoLoaderError *error)
320 MonoException *ex = NULL;
322 switch (error->exception_type) {
323 case MONO_EXCEPTION_TYPE_LOAD: {
324 char *cname = g_strdup (error->class_name);
325 char *aname = g_strdup (error->assembly_name);
326 MonoString *class_name;
328 mono_loader_clear_error ();
330 class_name = mono_string_new (mono_domain_get (), cname);
332 ex = mono_get_exception_type_load (class_name, aname);
337 case MONO_EXCEPTION_MISSING_METHOD: {
338 char *cname = g_strdup (error->class_name);
339 char *aname = g_strdup (error->member_name);
341 mono_loader_clear_error ();
342 ex = mono_get_exception_missing_method (cname, aname);
348 case MONO_EXCEPTION_MISSING_FIELD: {
350 char *cmembername = g_strdup (error->member_name);
352 class_name = mono_type_get_full_name (error->klass);
354 class_name = g_strdup ("");
356 mono_loader_clear_error ();
358 ex = mono_get_exception_missing_field (class_name, cmembername);
360 g_free (cmembername);
364 case MONO_EXCEPTION_FILE_NOT_FOUND: {
369 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);
371 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
372 filename = g_strdup (error->assembly_name);
373 /* Has to call this before calling anything which might call mono_class_init () */
374 mono_loader_clear_error ();
375 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
381 case MONO_EXCEPTION_BAD_IMAGE: {
382 char *msg = g_strdup (error->msg);
383 mono_loader_clear_error ();
384 ex = mono_get_exception_bad_image_format (msg);
390 g_assert_not_reached ();
397 * find_cached_memberref_sig:
399 * Return a cached copy of the memberref signature identified by SIG_IDX.
400 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
401 * A cache is needed since the type/signature parsing routines allocate everything
402 * from a mempool, so without a cache, multiple requests for the same signature would
403 * lead to unbounded memory growth. For normal methods/fields this is not a problem
404 * since the resulting methods/fields are cached, but inflated methods/fields cannot
406 * LOCKING: Acquires the loader lock.
409 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
413 mono_image_lock (image);
414 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
415 mono_image_unlock (image);
421 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
425 mono_image_lock (image);
426 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
428 /* Somebody got in before us */
432 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
433 /* An approximation based on glib 2.18 */
434 memberref_sig_cache_size += sizeof (gpointer) * 4;
436 mono_image_unlock (image);
441 static MonoClassField*
442 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
443 MonoGenericContext *context, MonoError *error)
445 MonoClass *klass = NULL;
446 MonoClassField *field;
447 MonoTableInfo *tables = image->tables;
450 guint32 nindex, class, class_table;
453 guint32 idx = mono_metadata_token_index (token);
455 mono_error_init (error);
457 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
458 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
459 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
461 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
463 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
464 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class, token);
469 case MONO_MEMBERREF_PARENT_TYPEDEF:
470 class_table = MONO_TOKEN_TYPE_DEF;
471 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
473 case MONO_MEMBERREF_PARENT_TYPEREF:
474 class_table = MONO_TOKEN_TYPE_REF;
475 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
477 case MONO_MEMBERREF_PARENT_TYPESPEC:
478 class_table = MONO_TOKEN_TYPE_SPEC;
479 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
482 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class, token);
488 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
489 mono_metadata_decode_blob_size (ptr, &ptr);
490 /* we may want to check the signature here... */
493 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class, fname, token);
497 /* FIXME: This needs a cache, especially for generic instances, since
498 * mono_metadata_parse_type () allocates everything from a mempool.
500 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
502 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
503 if (sig_type == NULL) {
504 mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x", fname, token);
507 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
510 mono_class_init (klass); /*FIXME is this really necessary?*/
513 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
516 g_assert (!mono_loader_get_last_error ());
517 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
524 * mono_field_from_token:
525 * @deprecated use the _checked variant
528 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
531 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
532 g_assert (!mono_loader_get_last_error ());
533 if (!mono_error_ok (&error)) {
534 mono_loader_set_error_from_mono_error (&error);
535 mono_error_cleanup (&error);
541 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
545 MonoClassField *field;
547 mono_error_init (error);
549 if (image_is_dynamic (image)) {
550 MonoClassField *result;
551 MonoClass *handle_class;
554 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
555 // This checks the memberref type as well
556 if (!result || handle_class != mono_defaults.fieldhandle_class) {
557 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
560 *retklass = result->parent;
564 if ((field = mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
565 *retklass = field->parent;
569 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
570 field = field_from_memberref (image, token, retklass, context, error);
571 g_assert (!mono_loader_get_last_error ());
573 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
575 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
578 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
585 field = mono_class_get_field (k, token);
587 if (mono_loader_get_last_error ())
588 mono_loader_set_error_from_mono_error (error);
590 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
594 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
595 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
597 g_assert (!mono_loader_get_last_error ());
602 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
606 if (sig1->hasthis != sig2->hasthis ||
607 sig1->sentinelpos != sig2->sentinelpos)
610 for (i = 0; i < sig1->sentinelpos; i++) {
611 MonoType *p1 = sig1->params[i];
612 MonoType *p2 = sig2->params[i];
614 /*if (p1->attrs != p2->attrs)
617 if (!mono_metadata_type_equal (p1, p2))
621 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
627 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
628 MonoMethodSignature *sig, MonoClass *from_class)
632 /* Search directly in the metadata to avoid calling setup_methods () */
634 /* FIXME: !from_class->generic_class condition causes test failures. */
635 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
636 for (i = 0; i < klass->method.count; ++i) {
637 guint32 cols [MONO_METHOD_SIZE];
640 MonoMethodSignature *other_sig;
642 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
644 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
646 if (!((fqname && !strcmp (m_name, fqname)) ||
647 (qname && !strcmp (m_name, qname)) ||
648 (name && !strcmp (m_name, name))))
651 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
653 other_sig = mono_method_signature (method);
654 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
660 mono_class_setup_methods (klass);
662 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
663 See mono/tests/generic-type-load-exception.2.il
664 FIXME we should better report this error to the caller
668 for (i = 0; i < klass->method.count; ++i) {
669 MonoMethod *m = klass->methods [i];
670 MonoMethodSignature *msig;
672 /* We must cope with failing to load some of the types. */
676 if (!((fqname && !strcmp (m->name, fqname)) ||
677 (qname && !strcmp (m->name, qname)) ||
678 (name && !strcmp (m->name, name))))
680 msig = mono_method_signature (m);
684 if (sig->call_convention == MONO_CALL_VARARG) {
685 if (mono_metadata_signature_vararg_match (sig, msig))
688 if (mono_metadata_signature_equal (sig, msig))
693 if (i < klass->method.count)
694 return mono_class_get_method_by_index (from_class, i);
699 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
702 char *qname, *fqname, *class_name;
703 gboolean is_interface;
704 MonoMethod *result = NULL;
706 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
709 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
711 qname = g_strconcat (class_name, ".", name, NULL);
712 if (ic->name_space && ic->name_space [0])
713 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
717 class_name = qname = fqname = NULL;
720 g_assert (from_class);
721 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
725 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
729 * This happens when we fail to lazily load the interfaces of one of the types.
730 * On such case we can't just bail out since user code depends on us trying harder.
732 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
733 in_class = in_class->parent;
734 from_class = from_class->parent;
738 for (i = 0; i < in_class->interface_offsets_count; i++) {
739 MonoClass *in_ic = in_class->interfaces_packed [i];
740 MonoClass *from_ic = from_class->interfaces_packed [i];
741 char *ic_qname, *ic_fqname, *ic_class_name;
743 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
744 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
745 if (in_ic->name_space && in_ic->name_space [0])
746 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
750 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic);
751 g_free (ic_class_name);
758 in_class = in_class->parent;
759 from_class = from_class->parent;
761 g_assert (!in_class == !from_class);
764 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
773 static MonoMethodSignature*
774 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
776 MonoMethodSignature *res;
780 mono_error_init (error);
784 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
785 res->param_count = sig->param_count;
786 res->sentinelpos = -1;
787 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
788 if (!mono_error_ok (error))
790 is_open = mono_class_is_open_constructed_type (res->ret);
791 for (i = 0; i < sig->param_count; ++i) {
792 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
793 if (!mono_error_ok (error))
797 is_open = mono_class_is_open_constructed_type (res->params [i]);
799 res->hasthis = sig->hasthis;
800 res->explicit_this = sig->explicit_this;
801 res->call_convention = sig->call_convention;
802 res->pinvoke = sig->pinvoke;
803 res->generic_param_count = sig->generic_param_count;
804 res->sentinelpos = sig->sentinelpos;
805 res->has_type_parameters = is_open;
806 res->is_inflated = 1;
811 mono_metadata_free_type (res->ret);
812 for (i = 0; i < sig->param_count; ++i) {
814 mono_metadata_free_type (res->params [i]);
821 * mono_inflate_generic_signature:
823 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
826 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
828 MonoMethodSignature *res, *cached;
830 res = inflate_generic_signature_checked (NULL, sig, context, error);
831 if (!mono_error_ok (error))
833 cached = mono_metadata_get_inflated_signature (res, context);
835 mono_metadata_free_inflated_signature (res);
839 static MonoMethodHeader*
840 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
842 MonoMethodHeader *res;
844 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
845 res->code = header->code;
846 res->code_size = header->code_size;
847 res->max_stack = header->max_stack;
848 res->num_clauses = header->num_clauses;
849 res->init_locals = header->init_locals;
850 res->num_locals = header->num_locals;
851 res->clauses = header->clauses;
852 for (i = 0; i < header->num_locals; ++i)
853 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
854 if (res->num_clauses) {
855 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
856 for (i = 0; i < header->num_clauses; ++i) {
857 MonoExceptionClause *clause = &res->clauses [i];
858 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
860 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
867 * token is the method_ref/def/spec token used in a call IL instruction.
870 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
872 int table = mono_metadata_token_table (token);
873 int idx = mono_metadata_token_index (token);
875 guint32 cols [MONO_MEMBERREF_SIZE];
876 MonoMethodSignature *sig;
879 /* !table is for wrappers: we should really assign their own token to them */
880 if (!table || table == MONO_TABLE_METHOD)
881 return mono_method_signature (method);
883 if (table == MONO_TABLE_METHODSPEC) {
884 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
885 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
888 return mono_method_signature (method);
891 if (method->klass->generic_class)
892 return mono_method_signature (method);
894 if (image_is_dynamic (image)) {
895 sig = mono_reflection_lookup_signature (image, method, token);
897 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
898 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
900 sig = find_cached_memberref_sig (image, sig_idx);
902 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
903 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
904 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
906 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
910 ptr = mono_metadata_blob_heap (image, sig_idx);
911 mono_metadata_decode_blob_size (ptr, &ptr);
912 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
915 sig = cache_memberref_sig (image, sig_idx, sig);
917 /* FIXME: we probably should verify signature compat in the dynamic case too*/
918 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
919 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
920 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
922 mono_loader_set_error_bad_image (g_strdup_printf ("Incompatible method signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
929 MonoMethodSignature *cached;
931 /* This signature is not owned by a MonoMethod, so need to cache */
932 sig = inflate_generic_signature_checked (image, sig, context, &error);
933 if (!mono_error_ok (&error)) {/*XXX bubble up this and kill one use of loader errors */
934 mono_loader_set_error_bad_image (g_strdup_printf ("Could not inflate signature %s", mono_error_get_message (&error)));
935 mono_error_cleanup (&error);
939 cached = mono_metadata_get_inflated_signature (sig, context);
941 mono_metadata_free_inflated_signature (sig);
943 inflated_signatures_size += mono_metadata_signature_size (cached);
951 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
953 return mono_method_get_signature_full (method, image, token, NULL);
956 /* this is only for the typespec array methods */
958 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
962 mono_class_setup_methods (klass);
963 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
964 for (i = 0; i < klass->method.count; ++i) {
965 MonoMethod *method = klass->methods [i];
966 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
973 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
974 gboolean *used_context)
976 MonoClass *klass = NULL;
977 MonoMethod *method = NULL;
978 MonoTableInfo *tables = image->tables;
980 guint32 nindex, class, sig_idx;
982 MonoMethodSignature *sig;
986 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
987 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
988 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
989 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
990 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
992 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
995 * Whether we actually used the `typespec_context' or not.
996 * This is used to tell our caller whether or not it's safe to insert the returned
997 * method into a cache.
1000 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
1003 case MONO_MEMBERREF_PARENT_TYPEREF:
1004 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, &error);
1006 mono_loader_set_error_from_mono_error (&error);
1007 mono_error_cleanup (&error); /* FIXME Don't swallow the error */
1011 case MONO_MEMBERREF_PARENT_TYPESPEC:
1013 * Parse the TYPESPEC in the parent's context.
1015 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, &error);
1017 mono_loader_set_error_from_mono_error (&error);
1018 mono_error_cleanup (&error); /*FIXME don't swallow the error message*/
1022 case MONO_MEMBERREF_PARENT_TYPEDEF:
1023 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, &error);
1025 mono_loader_set_error_from_mono_error (&error);
1026 mono_error_cleanup (&error); /*FIXME don't swallow the error message*/
1030 case MONO_MEMBERREF_PARENT_METHODDEF:
1031 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
1035 /* This message leaks */
1036 char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
1037 mono_loader_set_error_method_load ("", message);
1043 mono_class_init (klass);
1045 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1047 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1048 mono_loader_set_error_method_load (klass->name, mname);
1052 ptr = mono_metadata_blob_heap (image, sig_idx);
1053 mono_metadata_decode_blob_size (ptr, &ptr);
1055 sig = find_cached_memberref_sig (image, sig_idx);
1057 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
1061 sig = cache_memberref_sig (image, sig_idx, sig);
1065 case MONO_MEMBERREF_PARENT_TYPEREF:
1066 case MONO_MEMBERREF_PARENT_TYPEDEF:
1067 method = find_method (klass, NULL, mname, sig, klass);
1070 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1073 type = &klass->byval_arg;
1075 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1076 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1077 method = find_method (in_class, NULL, mname, sig, klass);
1081 /* we're an array and we created these methods already in klass in mono_class_init () */
1082 method = mono_method_search_in_array_class (klass, mname, sig);
1086 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
1087 g_assert_not_reached ();
1091 char *msig = mono_signature_get_desc (sig, FALSE);
1092 char * class_name = mono_type_get_name (&klass->byval_arg);
1093 GString *s = g_string_new (mname);
1094 if (sig->generic_param_count)
1095 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1096 g_string_append_printf (s, "(%s)", msig);
1098 msig = g_string_free (s, FALSE);
1101 "Missing method %s::%s in assembly %s, referenced in assembly %s",
1102 class_name, msig, klass->image->name, image->name);
1103 mono_loader_set_error_method_load (class_name, mname);
1105 g_free (class_name);
1112 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
1117 MonoTableInfo *tables = image->tables;
1118 MonoGenericContext new_context;
1119 MonoGenericInst *inst;
1121 guint32 cols [MONO_METHODSPEC_SIZE];
1122 guint32 token, nindex, param_count;
1124 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1125 token = cols [MONO_METHODSPEC_METHOD];
1126 nindex = token >> MONO_METHODDEFORREF_BITS;
1128 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL))
1131 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1133 mono_metadata_decode_value (ptr, &ptr);
1135 param_count = mono_metadata_decode_value (ptr, &ptr);
1137 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1141 if (context && inst->is_open) {
1142 inst = mono_metadata_inflate_generic_inst (inst, context, &error);
1143 if (!mono_error_ok (&error)) {
1144 mono_error_cleanup (&error); /*FIXME don't swallow error message.*/
1149 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
1150 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
1152 method = method_from_memberref (image, nindex, context, NULL);
1157 klass = method->klass;
1159 if (klass->generic_class) {
1160 g_assert (method->is_inflated);
1161 method = ((MonoMethodInflated *) method)->declaring;
1164 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1165 new_context.method_inst = inst;
1167 return mono_class_inflate_generic_method_full (method, klass, &new_context);
1170 struct _MonoDllMap {
1178 static MonoDllMap *global_dll_map;
1181 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1189 global_loader_data_lock ();
1192 * we use the first entry we find that matches, since entries from
1193 * the config file are prepended to the list and we document that the
1194 * later entries win.
1196 for (; dll_map; dll_map = dll_map->next) {
1197 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1198 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1200 } else if (strcmp (dll_map->dll, dll)) {
1203 if (!found && dll_map->target) {
1204 *rdll = dll_map->target;
1206 /* we don't quit here, because we could find a full
1207 * entry that matches also function and that has priority.
1210 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1211 *rfunc = dll_map->target_func;
1216 global_loader_data_unlock ();
1221 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1224 if (assembly && assembly->dll_map) {
1225 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1229 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1233 * mono_dllmap_insert:
1234 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1235 * @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
1236 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1237 * @tdll: The name of the library to map the specified @dll if it matches.
1238 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1240 * LOCKING: Acquires the loader lock.
1242 * This function is used to programatically add DllImport remapping in either
1243 * a specific assembly, or as a global remapping. This is done by remapping
1244 * references in a DllImport attribute from the @dll library name into the @tdll
1245 * name. If the @dll name contains the prefix "i:", the comparison of the
1246 * library name is done without case sensitivity.
1248 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1249 * or the name of the function as determined by DllImport. If you pass @func, you
1250 * must also pass @tfunc which is the name of the target function to invoke on a match.
1253 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1255 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1256 * the contents of relocated_demo_path for all assemblies in the Mono process.
1258 * NOTE: This can be called before the runtime is initialized, for example from
1259 * mono_config_parse ().
1262 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1266 mono_loader_init ();
1269 entry = g_malloc0 (sizeof (MonoDllMap));
1270 entry->dll = dll? g_strdup (dll): NULL;
1271 entry->target = tdll? g_strdup (tdll): NULL;
1272 entry->func = func? g_strdup (func): NULL;
1273 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1275 global_loader_data_lock ();
1276 entry->next = global_dll_map;
1277 global_dll_map = entry;
1278 global_loader_data_unlock ();
1280 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1281 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1282 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1283 entry->func = func? mono_image_strdup (assembly, func): NULL;
1284 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1286 mono_image_lock (assembly);
1287 entry->next = assembly->dll_map;
1288 assembly->dll_map = entry;
1289 mono_image_unlock (assembly);
1294 free_dllmap (MonoDllMap *map)
1297 MonoDllMap *next = map->next;
1300 g_free (map->target);
1302 g_free (map->target_func);
1309 dllmap_cleanup (void)
1311 free_dllmap (global_dll_map);
1312 global_dll_map = NULL;
1315 static GHashTable *global_module_map;
1318 cached_module_load (const char *name, int flags, char **err)
1324 global_loader_data_lock ();
1325 if (!global_module_map)
1326 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1327 res = g_hash_table_lookup (global_module_map, name);
1329 global_loader_data_unlock ();
1332 res = mono_dl_open (name, flags, err);
1334 g_hash_table_insert (global_module_map, g_strdup (name), res);
1335 global_loader_data_unlock ();
1339 static MonoDl *internal_module;
1342 is_absolute_path (const char *path)
1344 #ifdef PLATFORM_MACOSX
1345 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1346 !strncmp (path, "@rpath/", 7))
1349 return g_path_is_absolute (path);
1353 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1355 MonoImage *image = method->klass->image;
1356 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1357 MonoTableInfo *tables = image->tables;
1358 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1359 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1360 guint32 im_cols [MONO_IMPLMAP_SIZE];
1361 guint32 scope_token;
1362 const char *import = NULL;
1363 const char *orig_scope;
1364 const char *new_scope;
1366 char *full_name, *file_name, *found_name = NULL;
1368 MonoDl *module = NULL;
1369 gboolean cached = FALSE;
1371 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1379 return piinfo->addr;
1381 if (image_is_dynamic (method->klass->image)) {
1382 MonoReflectionMethodAux *method_aux =
1383 g_hash_table_lookup (
1384 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1388 import = method_aux->dllentry;
1389 orig_scope = method_aux->dll;
1392 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1395 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1397 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1400 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1401 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1402 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1403 orig_scope = mono_metadata_string_heap (image, scope_token);
1406 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1409 mono_image_lock (image);
1410 if (!image->pinvoke_scopes) {
1411 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1412 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1414 module = g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1415 found_name = g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1416 mono_image_unlock (image);
1420 found_name = g_strdup (found_name);
1424 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1425 "DllImport attempting to load: '%s'.", new_scope);
1427 /* we allow a special name to dlopen from the running process namespace */
1428 if (strcmp (new_scope, "__Internal") == 0){
1429 if (internal_module == NULL)
1430 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1431 module = internal_module;
1436 * Try loading the module using a variety of names
1438 for (i = 0; i < 4; ++i) {
1439 char *base_name = NULL, *dir_name = NULL;
1440 gboolean is_absolute = is_absolute_path (new_scope);
1444 /* Try the original name */
1445 file_name = g_strdup (new_scope);
1448 /* Try trimming the .dll extension */
1449 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1450 file_name = g_strdup (new_scope);
1451 file_name [strlen (new_scope) - 4] = '\0';
1458 dir_name = g_path_get_dirname (new_scope);
1459 base_name = g_path_get_basename (new_scope);
1460 if (strstr (base_name, "lib") != base_name) {
1461 char *tmp = g_strdup_printf ("lib%s", base_name);
1464 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1467 } else if (strstr (new_scope, "lib") != new_scope) {
1468 file_name = g_strdup_printf ("lib%s", new_scope);
1473 #ifndef TARGET_WIN32
1474 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1475 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1476 !g_ascii_strcasecmp ("user32", new_scope) ||
1477 !g_ascii_strcasecmp ("kernel", new_scope)) {
1478 file_name = g_strdup ("libMonoSupportW.so");
1482 #ifndef TARGET_WIN32
1489 dir_name = g_path_get_dirname (file_name);
1491 base_name = g_path_get_basename (file_name);
1494 if (!module && is_absolute) {
1495 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1497 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1498 "DllImport error loading library '%s': '%s'.",
1499 file_name, error_msg);
1502 found_name = g_strdup (file_name);
1506 if (!module && !is_absolute) {
1508 char *mdirname = g_path_get_dirname (image->name);
1509 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1510 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1512 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1513 "DllImport error loading library '%s': '%s'.",
1514 full_name, error_msg);
1517 found_name = g_strdup (full_name);
1528 char *file_or_base = is_absolute ? base_name : file_name;
1529 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1530 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1532 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1533 "DllImport error loading library '%s': '%s'.",
1534 full_name, error_msg);
1537 found_name = g_strdup (full_name);
1546 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1548 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1549 "DllImport error loading library '%s': '%s'.",
1550 file_name, error_msg);
1552 found_name = g_strdup (file_name);
1567 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1568 "DllImport unable to load library '%s'.",
1573 *exc_class = "DllNotFoundException";
1574 *exc_arg = new_scope;
1580 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1581 "DllImport loaded library '%s'.", found_name);
1582 mono_image_lock (image);
1583 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1584 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1585 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1587 mono_image_unlock (image);
1590 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1591 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1592 g_free (found_name);
1595 if (import && import [0] == '#' && isdigit (import [1])) {
1599 id = strtol (import + 1, &end, 10);
1600 if (id > 0 && *end == '\0')
1604 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1605 "Searching for '%s'.", import);
1607 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1608 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1610 char *mangled_name = NULL, *mangled_name2 = NULL;
1613 int mangle_param_count;
1619 * Search using a variety of mangled names
1621 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1622 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1623 gboolean need_param_count = FALSE;
1625 if (mangle_stdcall > 0)
1626 need_param_count = TRUE;
1628 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1633 mangled_name = (char*)import;
1634 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1635 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1636 /* Try the mangled name first */
1637 if (mangle_charset == 0)
1638 mangled_name = g_strconcat (import, "W", NULL);
1640 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1642 if (mangle_charset == 0)
1643 mangled_name = g_strconcat (import, "W", NULL);
1645 /* Try the mangled name last */
1646 if (mangle_charset == 1)
1647 mangled_name = g_strconcat (import, "A", NULL);
1650 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1652 /* Try the mangled name last */
1653 if (mangle_charset == 1)
1654 mangled_name = g_strconcat (import, "A", NULL);
1659 if (mangle_param_count == 0)
1660 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1662 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1663 param_count = mangle_param_count;
1665 /* Try the stdcall mangled name */
1667 * gcc under windows creates mangled names without the underscore, but MS.NET
1668 * doesn't support it, so we doesn't support it either.
1670 if (mangle_stdcall == 1)
1671 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1673 mangled_name2 = mangled_name;
1675 mangled_name2 = mangled_name;
1678 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1679 "Probing '%s'.", mangled_name2);
1681 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1686 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1687 "Found as '%s'.", mangled_name2);
1689 if (mangled_name != mangled_name2)
1690 g_free (mangled_name2);
1691 if (mangled_name != import)
1692 g_free (mangled_name);
1698 if (!piinfo->addr) {
1701 *exc_class = "EntryPointNotFoundException";
1706 return piinfo->addr;
1710 * LOCKING: assumes the loader lock to be taken.
1713 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1714 MonoGenericContext *context, gboolean *used_context)
1718 int table = mono_metadata_token_table (token);
1719 int idx = mono_metadata_token_index (token);
1720 MonoTableInfo *tables = image->tables;
1721 MonoGenericContainer *generic_container = NULL, *container = NULL;
1722 const char *sig = NULL;
1724 guint32 cols [MONO_TYPEDEF_SIZE];
1726 if (image_is_dynamic (image)) {
1727 MonoClass *handle_class;
1729 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1730 // This checks the memberref type as well
1731 if (result && handle_class != mono_defaults.methodhandle_class) {
1732 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1738 if (table != MONO_TABLE_METHOD) {
1739 if (table == MONO_TABLE_METHODSPEC) {
1740 if (used_context) *used_context = TRUE;
1741 return method_from_methodspec (image, context, idx);
1743 if (table != MONO_TABLE_MEMBERREF) {
1744 g_warning ("got wrong token: 0x%08x\n", token);
1745 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1748 return method_from_memberref (image, idx, context, used_context);
1751 if (used_context) *used_context = FALSE;
1753 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1754 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1759 guint32 type = mono_metadata_typedef_from_method (image, token);
1762 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, &error);
1763 if (klass == NULL) {
1764 mono_loader_set_error_from_mono_error (&error);
1765 mono_error_cleanup (&error); /*FIXME don't swallow the error message*/
1770 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1772 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1773 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1774 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1776 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1777 methods_size += sizeof (MonoMethod);
1780 mono_stats.method_count ++;
1783 result->klass = klass;
1784 result->flags = cols [2];
1785 result->iflags = cols [1];
1786 result->token = token;
1787 result->name = mono_metadata_string_heap (image, cols [3]);
1789 if (!sig) /* already taken from the methodref */
1790 sig = mono_metadata_blob_heap (image, cols [4]);
1791 size = mono_metadata_decode_blob_size (sig, &sig);
1793 container = klass->generic_container;
1796 * load_generic_params does a binary search so only call it if the method
1800 generic_container = mono_metadata_load_generic_params (image, token, container);
1801 if (generic_container) {
1803 result->is_generic = TRUE;
1804 generic_container->owner.method = result;
1805 /*FIXME put this before the image alloc*/
1806 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, &error)) {
1807 mono_loader_set_error_from_mono_error (&error);
1808 mono_error_cleanup (&error); /*FIXME don't swallow the error message*/
1812 container = generic_container;
1815 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1816 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1817 result->string_ctor = 1;
1818 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1819 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1822 /* IJW is P/Invoke with a predefined function pointer. */
1823 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1824 piinfo->addr = mono_image_rva_map (image, cols [0]);
1825 g_assert (piinfo->addr);
1828 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1829 /* Native methods can have no map. */
1830 if (piinfo->implmap_idx)
1831 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1834 if (generic_container)
1835 mono_method_set_generic_container (result, generic_container);
1841 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1843 return mono_get_method_full (image, token, klass, NULL);
1847 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1848 MonoGenericContext *context)
1850 MonoMethod *result = NULL;
1851 gboolean used_context = FALSE;
1853 /* We do everything inside the lock to prevent creation races */
1855 mono_image_lock (image);
1857 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1858 if (!image->method_cache)
1859 image->method_cache = g_hash_table_new (NULL, NULL);
1860 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1861 } else if (!image_is_dynamic (image)) {
1862 if (!image->methodref_cache)
1863 image->methodref_cache = g_hash_table_new (NULL, NULL);
1864 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1866 mono_image_unlock (image);
1872 result = mono_get_method_from_token (image, token, klass, context, &used_context);
1876 mono_image_lock (image);
1877 if (!used_context && !result->is_inflated) {
1878 MonoMethod *result2 = NULL;
1880 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1881 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1882 else if (!image_is_dynamic (image))
1883 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1886 mono_image_unlock (image);
1890 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1891 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1892 else if (!image_is_dynamic (image))
1893 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1896 mono_image_unlock (image);
1902 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context)
1905 MonoClass *ic = NULL;
1906 MonoGenericContext *method_context = NULL;
1907 MonoMethodSignature *sig, *original_sig;
1909 mono_class_init (constrained_class);
1910 original_sig = sig = mono_method_signature (method);
1915 if (method->is_inflated && sig->generic_param_count) {
1916 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1917 sig = mono_method_signature (imethod->declaring); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1918 method_context = mono_method_get_context (method);
1922 * We must inflate the signature with the class instantiation to work on
1923 * cases where a class inherit from a generic type and the override replaces
1924 * any type argument which a concrete type. See #325283.
1926 if (method_context->class_inst) {
1928 MonoGenericContext ctx;
1929 ctx.method_inst = NULL;
1930 ctx.class_inst = method_context->class_inst;
1931 /*Fixme, property propagate this error*/
1932 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, &error);
1933 if (!mono_error_ok (&error)) {
1934 mono_error_cleanup (&error);
1940 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1943 result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1944 if (sig != original_sig)
1945 mono_metadata_free_inflated_signature (sig);
1948 char *m = mono_method_full_name (method, 1);
1949 g_warning ("Missing method %s.%s.%s in assembly %s method %s", method->klass->name_space,
1950 method->klass->name, method->name, image->name, m);
1956 result = mono_class_inflate_generic_method (result, method_context);
1962 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
1963 MonoGenericContext *context)
1967 return get_method_constrained (image, method, constrained_class, context);
1971 * mono_get_method_constrained:
1973 * This is used when JITing the `constrained.' opcode.
1975 * This returns two values: the contrained method, which has been inflated
1976 * as the function return value; And the original CIL-stream method as
1977 * declared in cil_method. The later is used for verification.
1980 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1981 MonoGenericContext *context, MonoMethod **cil_method)
1985 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL);
1989 result = get_method_constrained (image, *cil_method, constrained_class, context);
1995 mono_free_method (MonoMethod *method)
1997 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1998 mono_profiler_method_free (method);
2000 /* FIXME: This hack will go away when the profiler will support freeing methods */
2001 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2004 if (method->signature) {
2006 * FIXME: This causes crashes because the types inside signatures and
2007 * locals are shared.
2009 /* mono_metadata_free_method_signature (method->signature); */
2010 /* g_free (method->signature); */
2013 if (method_is_dynamic (method)) {
2014 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2017 mono_marshal_free_dynamic_wrappers (method);
2019 mono_image_property_remove (method->klass->image, method);
2021 g_free ((char*)method->name);
2023 g_free ((char*)mw->header->code);
2024 for (i = 0; i < mw->header->num_locals; ++i)
2025 g_free (mw->header->locals [i]);
2026 g_free (mw->header->clauses);
2027 g_free (mw->header);
2029 g_free (mw->method_data);
2030 g_free (method->signature);
2036 mono_method_get_param_names (MonoMethod *method, const char **names)
2040 MonoTableInfo *methodt;
2041 MonoTableInfo *paramt;
2042 MonoMethodSignature *signature;
2045 if (method->is_inflated)
2046 method = ((MonoMethodInflated *) method)->declaring;
2048 signature = mono_method_signature (method);
2049 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2050 number of arguments and allocate a properly sized array. */
2051 if (signature == NULL)
2054 if (!signature->param_count)
2057 for (i = 0; i < signature->param_count; ++i)
2060 klass = method->klass;
2064 mono_class_init (klass);
2066 if (image_is_dynamic (klass->image)) {
2067 MonoReflectionMethodAux *method_aux =
2068 g_hash_table_lookup (
2069 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2070 if (method_aux && method_aux->param_names) {
2071 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2072 if (method_aux->param_names [i + 1])
2073 names [i] = method_aux->param_names [i + 1];
2078 if (method->wrapper_type) {
2079 char **pnames = NULL;
2081 mono_image_lock (klass->image);
2082 if (klass->image->wrapper_param_names)
2083 pnames = g_hash_table_lookup (klass->image->wrapper_param_names, method);
2084 mono_image_unlock (klass->image);
2087 for (i = 0; i < signature->param_count; ++i)
2088 names [i] = pnames [i];
2093 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2094 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2095 idx = mono_method_get_index (method);
2097 guint32 cols [MONO_PARAM_SIZE];
2100 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2102 if (idx < methodt->rows)
2103 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2105 lastp = paramt->rows + 1;
2106 for (i = param_index; i < lastp; ++i) {
2107 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2108 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2109 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2115 mono_method_get_param_token (MonoMethod *method, int index)
2117 MonoClass *klass = method->klass;
2118 MonoTableInfo *methodt;
2121 mono_class_init (klass);
2123 if (image_is_dynamic (klass->image))
2124 g_assert_not_reached ();
2126 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2127 idx = mono_method_get_index (method);
2129 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2133 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2135 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2142 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2145 MonoClass *klass = method->klass;
2146 MonoTableInfo *methodt;
2147 MonoTableInfo *paramt;
2148 MonoMethodSignature *signature;
2151 signature = mono_method_signature (method);
2152 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2154 for (i = 0; i < signature->param_count + 1; ++i)
2157 if (image_is_dynamic (method->klass->image)) {
2158 MonoReflectionMethodAux *method_aux =
2159 g_hash_table_lookup (
2160 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2161 if (method_aux && method_aux->param_marshall) {
2162 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2163 for (i = 0; i < signature->param_count + 1; ++i)
2164 if (dyn_specs [i]) {
2165 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2166 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2167 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2168 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2174 mono_class_init (klass);
2176 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2177 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2178 idx = mono_method_get_index (method);
2180 guint32 cols [MONO_PARAM_SIZE];
2181 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2183 if (idx < methodt->rows)
2184 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2186 lastp = paramt->rows + 1;
2188 for (i = param_index; i < lastp; ++i) {
2189 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2191 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2193 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2195 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2204 mono_method_has_marshal_info (MonoMethod *method)
2207 MonoClass *klass = method->klass;
2208 MonoTableInfo *methodt;
2209 MonoTableInfo *paramt;
2212 if (image_is_dynamic (method->klass->image)) {
2213 MonoReflectionMethodAux *method_aux =
2214 g_hash_table_lookup (
2215 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2216 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2218 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2225 mono_class_init (klass);
2227 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2228 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2229 idx = mono_method_get_index (method);
2231 guint32 cols [MONO_PARAM_SIZE];
2232 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2234 if (idx + 1 < methodt->rows)
2235 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2237 lastp = paramt->rows + 1;
2239 for (i = param_index; i < lastp; ++i) {
2240 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2242 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2251 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2254 g_assert (method != NULL);
2255 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2257 if (method->is_inflated)
2258 method = ((MonoMethodInflated *) method)->declaring;
2259 data = ((MonoMethodWrapper *)method)->method_data;
2260 g_assert (data != NULL);
2261 g_assert (id <= GPOINTER_TO_UINT (*data));
2268 } StackWalkUserData;
2271 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2273 StackWalkUserData *d = data;
2275 switch (frame->type) {
2276 case FRAME_TYPE_DEBUGGER_INVOKE:
2277 case FRAME_TYPE_MANAGED_TO_NATIVE:
2279 case FRAME_TYPE_MANAGED:
2280 g_assert (frame->ji);
2281 return d->func (mono_jit_info_get_method (frame->ji), frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2284 g_assert_not_reached ();
2290 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2292 StackWalkUserData ud = { func, user_data };
2293 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2297 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2299 StackWalkUserData ud = { func, user_data };
2300 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2304 MonoStackWalkAsyncSafe func;
2306 } AsyncStackWalkUserData;
2310 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2312 AsyncStackWalkUserData *d = data;
2314 switch (frame->type) {
2315 case FRAME_TYPE_DEBUGGER_INVOKE:
2316 case FRAME_TYPE_MANAGED_TO_NATIVE:
2318 case FRAME_TYPE_MANAGED:
2321 if (frame->ji->async)
2322 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2324 return d->func (mono_jit_info_get_method (frame->ji), frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2327 g_assert_not_reached ();
2334 * mono_stack_walk_async_safe:
2336 * Async safe version callable from signal handlers.
2339 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2342 AsyncStackWalkUserData ud = { func, user_data };
2344 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2345 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2349 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2351 MonoMethod **dest = data;
2353 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2359 mono_method_get_last_managed (void)
2361 MonoMethod *m = NULL;
2362 mono_stack_walk_no_il (last_managed, &m);
2366 static gboolean loader_lock_track_ownership = FALSE;
2371 * See docs/thread-safety.txt for the locking strategy.
2374 mono_loader_lock (void)
2376 mono_locks_acquire (&loader_mutex, LoaderLock);
2377 if (G_UNLIKELY (loader_lock_track_ownership)) {
2378 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));
2383 mono_loader_unlock (void)
2385 mono_locks_release (&loader_mutex, LoaderLock);
2386 if (G_UNLIKELY (loader_lock_track_ownership)) {
2387 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));
2392 * mono_loader_lock_track_ownership:
2394 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2395 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2396 * thread owns the loader lock.
2399 mono_loader_lock_track_ownership (gboolean track)
2401 loader_lock_track_ownership = track;
2405 * mono_loader_lock_is_owned_by_self:
2407 * Return whenever the current thread owns the loader lock.
2408 * This is useful to avoid blocking operations while holding the loader lock.
2411 mono_loader_lock_is_owned_by_self (void)
2413 g_assert (loader_lock_track_ownership);
2415 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2419 * mono_loader_lock_if_inited:
2421 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2422 * be used in runtime initialization code which can be executed before mono_loader_init ().
2425 mono_loader_lock_if_inited (void)
2427 if (loader_lock_inited)
2428 mono_loader_lock ();
2432 mono_loader_unlock_if_inited (void)
2434 if (loader_lock_inited)
2435 mono_loader_unlock ();
2439 * mono_method_signature:
2441 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2443 MonoMethodSignature*
2444 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2450 gboolean can_cache_signature;
2451 MonoGenericContainer *container;
2452 MonoMethodSignature *signature = NULL, *sig2;
2455 /* We need memory barriers below because of the double-checked locking pattern */
2457 mono_error_init (error);
2460 return m->signature;
2462 img = m->klass->image;
2464 if (m->is_inflated) {
2465 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2466 /* the lock is recursive */
2467 signature = mono_method_signature (imethod->declaring);
2468 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2469 if (!mono_error_ok (error))
2472 inflated_signatures_size += mono_metadata_signature_size (signature);
2474 mono_image_lock (img);
2476 mono_memory_barrier ();
2478 m->signature = signature;
2480 mono_image_unlock (img);
2482 return m->signature;
2485 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2486 idx = mono_metadata_token_index (m->token);
2488 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2490 g_assert (!m->klass->generic_class);
2491 container = mono_method_get_generic_container (m);
2493 container = m->klass->generic_container;
2495 /* Generic signatures depend on the container so they cannot be cached */
2496 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2497 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2499 /* If the method has parameter attributes, that can modify the signature */
2500 if (mono_metadata_method_has_param_attrs (img, idx))
2501 can_cache_signature = FALSE;
2503 if (can_cache_signature) {
2504 mono_image_lock (img);
2505 signature = g_hash_table_lookup (img->method_signatures, sig);
2506 mono_image_unlock (img);
2510 const char *sig_body;
2511 /*TODO we should cache the failure result somewhere*/
2512 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2515 size = mono_metadata_decode_blob_size (sig, &sig_body);
2517 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
2519 mono_error_set_from_loader_error (error);
2523 if (can_cache_signature) {
2524 mono_image_lock (img);
2525 sig2 = g_hash_table_lookup (img->method_signatures, sig);
2527 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2528 mono_image_unlock (img);
2531 signatures_size += mono_metadata_signature_size (signature);
2534 /* Verify metadata consistency */
2535 if (signature->generic_param_count) {
2536 if (!container || !container->is_method) {
2537 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);
2540 if (container->type_argc != signature->generic_param_count) {
2541 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);
2544 } else if (container && container->is_method && container->type_argc) {
2545 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);
2548 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2549 signature->pinvoke = 1;
2550 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2551 MonoCallConvention conv = 0;
2552 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2553 signature->pinvoke = 1;
2555 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2556 case 0: /* no call conv, so using default */
2557 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2558 conv = MONO_CALL_DEFAULT;
2560 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2563 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2564 conv = MONO_CALL_STDCALL;
2566 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2567 conv = MONO_CALL_THISCALL;
2569 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2570 conv = MONO_CALL_FASTCALL;
2572 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2573 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2575 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);
2578 signature->call_convention = conv;
2581 mono_image_lock (img);
2583 mono_memory_barrier ();
2585 m->signature = signature;
2587 mono_image_unlock (img);
2589 return m->signature;
2593 * mono_method_signature:
2595 * Return the signature of the method M. On failure, returns NULL.
2597 MonoMethodSignature*
2598 mono_method_signature (MonoMethod *m)
2601 MonoMethodSignature *sig;
2603 sig = mono_method_signature_checked (m, &error);
2605 char *type_name = mono_type_get_full_name (m->klass);
2606 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2608 mono_error_cleanup (&error);
2615 mono_method_get_name (MonoMethod *method)
2617 return method->name;
2621 mono_method_get_class (MonoMethod *method)
2623 return method->klass;
2627 mono_method_get_token (MonoMethod *method)
2629 return method->token;
2633 mono_method_get_header (MonoMethod *method)
2639 MonoMethodHeader *header;
2640 MonoGenericContainer *container;
2642 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))
2645 img = method->klass->image;
2647 if (method->is_inflated) {
2648 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2649 MonoMethodHeader *header, *iheader;
2651 header = mono_method_get_header (imethod->declaring);
2655 iheader = inflate_generic_header (header, mono_method_get_context (method));
2656 mono_metadata_free_mh (header);
2658 mono_image_lock (img);
2660 if (imethod->header) {
2661 mono_metadata_free_mh (iheader);
2662 mono_image_unlock (img);
2663 return imethod->header;
2666 mono_memory_barrier ();
2667 imethod->header = iheader;
2669 mono_image_unlock (img);
2671 return imethod->header;
2674 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2675 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2676 g_assert (mw->header);
2681 * We don't need locks here: the new header is allocated from malloc memory
2682 * and is not stored anywhere in the runtime, the user needs to free it.
2684 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2685 idx = mono_metadata_token_index (method->token);
2686 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2688 if (!mono_verifier_verify_method_header (img, rva, NULL))
2691 loc = mono_image_rva_map (img, rva);
2696 * When parsing the types of local variables, we must pass any container available
2697 * to ensure that both VAR and MVAR will get the right owner.
2699 container = mono_method_get_generic_container (method);
2701 container = method->klass->generic_container;
2702 header = mono_metadata_parse_mh_full (img, container, loc);
2708 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2711 *iflags = method->iflags;
2712 return method->flags;
2716 * Find the method index in the metadata methodDef table.
2719 mono_method_get_index (MonoMethod *method)
2721 MonoClass *klass = method->klass;
2725 /* constructed array methods are not in the MethodDef table */
2729 return mono_metadata_token_index (method->token);
2731 mono_class_setup_methods (klass);
2732 if (klass->exception_type)
2734 for (i = 0; i < klass->method.count; ++i) {
2735 if (method == klass->methods [i]) {
2736 if (klass->image->uncompressed_metadata)
2737 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2739 return klass->method.first + i + 1;