[amd64] Remove the callee saved registers from MonoLMF, save/restore them normally...
[mono-project.git] / mono / metadata / loader.c
blobf950055953eaa5f728b435c793012fb8ac6f895d
1 /*
2 * loader.c: Image Loader
4 * Authors:
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
15 * kinds of `Refs'.
17 * TODO:
18 * This should keep track of the assembly versions that we are loading.
21 #include <config.h>
22 #include <glib.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
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
56 * domain lock.
58 static CRITICAL_SECTION loader_mutex;
59 static gboolean loader_lock_inited;
61 /* Statistics */
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
74 * lock.
76 MonoNativeTlsKey loader_lock_nest_id;
78 static void dllmap_cleanup (void);
80 void
81 mono_loader_init ()
83 static gboolean inited;
85 if (!inited) {
86 InitializeCriticalSection (&loader_mutex);
87 loader_lock_inited = TRUE;
89 mono_native_tls_alloc (&loader_error_thread_id, NULL);
90 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
92 mono_counters_register ("Inflated signatures size",
93 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
94 mono_counters_register ("Memberref signature cache size",
95 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
96 mono_counters_register ("MonoMethod size",
97 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
98 mono_counters_register ("MonoMethodSignature size",
99 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
101 inited = TRUE;
105 void
106 mono_loader_cleanup (void)
108 dllmap_cleanup ();
110 mono_native_tls_free (loader_error_thread_id);
111 mono_native_tls_free (loader_lock_nest_id);
113 DeleteCriticalSection (&loader_mutex);
114 loader_lock_inited = FALSE;
118 * Handling of type load errors should be done as follows:
120 * If something could not be loaded, the loader should call one of the
121 * mono_loader_set_error_XXX functions ()
122 * with the appropriate arguments, then return NULL to report the failure. The error
123 * should be propagated until it reaches code which can throw managed exceptions. At that
124 * point, an exception should be thrown based on the information returned by
125 * mono_loader_get_last_error (). Then the error should be cleared by calling
126 * mono_loader_clear_error ().
129 static void
130 set_loader_error (MonoLoaderError *error)
132 mono_loader_clear_error ();
133 mono_native_tls_set_value (loader_error_thread_id, error);
137 * mono_loader_set_error_assembly_load:
139 * Set the loader error for this thread.
141 void
142 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
144 MonoLoaderError *error;
146 if (mono_loader_get_last_error ())
147 return;
149 error = g_new0 (MonoLoaderError, 1);
150 error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
151 error->assembly_name = g_strdup (assembly_name);
152 error->ref_only = ref_only;
155 * This is not strictly needed, but some (most) of the loader code still
156 * can't deal with load errors, and this message is more helpful than an
157 * assert.
159 if (ref_only)
160 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);
161 else
162 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
164 set_loader_error (error);
168 * mono_loader_set_error_type_load:
170 * Set the loader error for this thread.
172 void
173 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
175 MonoLoaderError *error;
177 if (mono_loader_get_last_error ())
178 return;
180 error = g_new0 (MonoLoaderError, 1);
181 error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
182 error->class_name = g_strdup (class_name);
183 error->assembly_name = g_strdup (assembly_name);
186 * This is not strictly needed, but some (most) of the loader code still
187 * can't deal with load errors, and this message is more helpful than an
188 * assert.
190 mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
192 set_loader_error (error);
196 * mono_loader_set_error_method_load:
198 * Set the loader error for this thread. MEMBER_NAME should point to a string
199 * inside metadata.
201 void
202 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
204 MonoLoaderError *error;
206 /* FIXME: Store the signature as well */
207 if (mono_loader_get_last_error ())
208 return;
210 error = g_new0 (MonoLoaderError, 1);
211 error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
212 error->class_name = g_strdup (class_name);
213 error->member_name = member_name;
215 set_loader_error (error);
219 * mono_loader_set_error_field_load:
221 * Set the loader error for this thread. MEMBER_NAME should point to a string
222 * inside metadata.
224 void
225 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
227 MonoLoaderError *error;
229 /* FIXME: Store the signature as well */
230 if (mono_loader_get_last_error ())
231 return;
233 error = g_new0 (MonoLoaderError, 1);
234 error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
235 error->klass = klass;
236 error->member_name = member_name;
238 set_loader_error (error);
242 * mono_loader_set_error_bad_image:
244 * Set the loader error for this thread.
246 void
247 mono_loader_set_error_bad_image (char *msg)
249 MonoLoaderError *error;
251 if (mono_loader_get_last_error ())
252 return;
254 error = g_new0 (MonoLoaderError, 1);
255 error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
256 error->msg = msg;
258 set_loader_error (error);
263 * mono_loader_get_last_error:
265 * Returns information about the last type load exception encountered by the loader, or
266 * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
268 MonoLoaderError*
269 mono_loader_get_last_error (void)
271 return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
275 * mono_loader_clear_error:
277 * Disposes any loader error messages on this thread
279 void
280 mono_loader_clear_error (void)
282 MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
284 if (ex) {
285 g_free (ex->class_name);
286 g_free (ex->assembly_name);
287 g_free (ex->msg);
288 g_free (ex);
290 mono_native_tls_set_value (loader_error_thread_id, NULL);
295 * mono_loader_error_prepare_exception:
296 * @error: The MonoLoaderError to turn into an exception
298 * This turns a MonoLoaderError into an exception that can be thrown
299 * and resets the Mono Loader Error state during this process.
302 MonoException *
303 mono_loader_error_prepare_exception (MonoLoaderError *error)
305 MonoException *ex = NULL;
307 switch (error->exception_type) {
308 case MONO_EXCEPTION_TYPE_LOAD: {
309 char *cname = g_strdup (error->class_name);
310 char *aname = g_strdup (error->assembly_name);
311 MonoString *class_name;
313 mono_loader_clear_error ();
315 class_name = mono_string_new (mono_domain_get (), cname);
317 ex = mono_get_exception_type_load (class_name, aname);
318 g_free (cname);
319 g_free (aname);
320 break;
322 case MONO_EXCEPTION_MISSING_METHOD: {
323 char *cname = g_strdup (error->class_name);
324 char *aname = g_strdup (error->member_name);
326 mono_loader_clear_error ();
327 ex = mono_get_exception_missing_method (cname, aname);
328 g_free (cname);
329 g_free (aname);
330 break;
333 case MONO_EXCEPTION_MISSING_FIELD: {
334 char *class_name;
335 char *cmembername = g_strdup (error->member_name);
336 if (error->klass)
337 class_name = mono_type_get_full_name (error->klass);
338 else
339 class_name = g_strdup ("");
341 mono_loader_clear_error ();
343 ex = mono_get_exception_missing_field (class_name, cmembername);
344 g_free (class_name);
345 g_free (cmembername);
346 break;
349 case MONO_EXCEPTION_FILE_NOT_FOUND: {
350 char *msg;
351 char *filename;
353 if (error->ref_only)
354 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);
355 else
356 msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
357 filename = g_strdup (error->assembly_name);
358 /* Has to call this before calling anything which might call mono_class_init () */
359 mono_loader_clear_error ();
360 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
361 g_free (msg);
362 g_free (filename);
363 break;
366 case MONO_EXCEPTION_BAD_IMAGE: {
367 char *msg = g_strdup (error->msg);
368 mono_loader_clear_error ();
369 ex = mono_get_exception_bad_image_format (msg);
370 g_free (msg);
371 break;
374 default:
375 g_assert_not_reached ();
378 return ex;
382 * find_cached_memberref_sig:
384 * Return a cached copy of the memberref signature identified by SIG_IDX.
385 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
386 * A cache is needed since the type/signature parsing routines allocate everything
387 * from a mempool, so without a cache, multiple requests for the same signature would
388 * lead to unbounded memory growth. For normal methods/fields this is not a problem
389 * since the resulting methods/fields are cached, but inflated methods/fields cannot
390 * be cached.
391 * LOCKING: Acquires the loader lock.
393 static gpointer
394 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
396 gpointer res;
398 mono_loader_lock ();
399 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
400 mono_loader_unlock ();
402 return res;
405 static gpointer
406 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
408 gpointer prev_sig;
410 mono_loader_lock ();
411 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
412 if (prev_sig) {
413 /* Somebody got in before us */
414 sig = prev_sig;
416 else {
417 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
418 /* An approximation based on glib 2.18 */
419 memberref_sig_cache_size += sizeof (gpointer) * 4;
422 mono_loader_unlock ();
424 return sig;
427 static MonoClassField*
428 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
429 MonoGenericContext *context)
431 MonoClass *klass;
432 MonoClassField *field;
433 MonoTableInfo *tables = image->tables;
434 MonoType *sig_type;
435 guint32 cols[6];
436 guint32 nindex, class, class_table;
437 const char *fname;
438 const char *ptr;
439 guint32 idx = mono_metadata_token_index (token);
441 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
442 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
443 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
445 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
447 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
448 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field signature class token 0x%08x field name %s token 0x%08x on image %s", class, fname, token, image->name));
449 return NULL;
452 switch (class) {
453 case MONO_MEMBERREF_PARENT_TYPEDEF:
454 class_table = MONO_TOKEN_TYPE_DEF;
455 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
456 break;
457 case MONO_MEMBERREF_PARENT_TYPEREF:
458 class_table = MONO_TOKEN_TYPE_REF;
459 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
460 break;
461 case MONO_MEMBERREF_PARENT_TYPESPEC:
462 class_table = MONO_TOKEN_TYPE_SPEC;
463 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
464 break;
465 default:
466 /*FIXME this must set a loader error!*/
467 g_warning ("field load from %x", class);
468 return NULL;
471 if (!klass) {
472 char *name = mono_class_name_from_token (image, class_table | nindex);
473 g_warning ("Missing field %s in class %s (type token %d)", fname, name, class_table | nindex);
474 mono_loader_set_error_type_load (name, image->assembly_name);
475 g_free (name);
476 return NULL;
479 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
480 mono_metadata_decode_blob_size (ptr, &ptr);
481 /* we may want to check the signature here... */
483 if (*ptr++ != 0x6) {
484 g_warning ("Bad field signature class token %08x field name %s token %08x", class, fname, token);
485 mono_loader_set_error_field_load (klass, fname);
486 return NULL;
488 /* FIXME: This needs a cache, especially for generic instances, since
489 * mono_metadata_parse_type () allocates everything from a mempool.
491 sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
492 if (!sig_type) {
493 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
494 if (sig_type == NULL) {
495 mono_loader_set_error_field_load (klass, fname);
496 return NULL;
498 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
501 mono_class_init (klass); /*FIXME is this really necessary?*/
502 if (retklass)
503 *retklass = klass;
504 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
506 if (!field)
507 mono_loader_set_error_field_load (klass, fname);
509 return field;
512 MonoClassField*
513 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
514 MonoGenericContext *context)
516 MonoClass *k;
517 guint32 type;
518 MonoClassField *field;
520 if (image->dynamic) {
521 MonoClassField *result;
522 MonoClass *handle_class;
524 *retklass = NULL;
525 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
526 // This checks the memberref type as well
527 if (!result || handle_class != mono_defaults.fieldhandle_class) {
528 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field token 0x%08x on image %s.", token, image->name));
529 return NULL;
531 *retklass = result->parent;
532 return result;
535 mono_image_lock (image);
536 if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
537 *retklass = field->parent;
538 mono_image_unlock (image);
539 return field;
541 mono_image_unlock (image);
543 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
544 field = field_from_memberref (image, token, retklass, context);
545 else {
546 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
547 if (!type)
548 return NULL;
549 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
550 if (!k)
551 return NULL;
552 mono_class_init (k);
553 if (retklass)
554 *retklass = k;
555 field = mono_class_get_field (k, token);
558 mono_image_lock (image);
559 if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
560 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
561 mono_image_unlock (image);
562 return field;
565 static gboolean
566 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
568 int i;
570 if (sig1->hasthis != sig2->hasthis ||
571 sig1->sentinelpos != sig2->sentinelpos)
572 return FALSE;
574 for (i = 0; i < sig1->sentinelpos; i++) {
575 MonoType *p1 = sig1->params[i];
576 MonoType *p2 = sig2->params[i];
578 /*if (p1->attrs != p2->attrs)
579 return FALSE;
581 if (!mono_metadata_type_equal (p1, p2))
582 return FALSE;
585 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
586 return FALSE;
587 return TRUE;
590 static MonoMethod *
591 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
592 MonoMethodSignature *sig, MonoClass *from_class)
594 int i;
596 /* Search directly in the metadata to avoid calling setup_methods () */
598 /* FIXME: !from_class->generic_class condition causes test failures. */
599 if (klass->type_token && !klass->image->dynamic && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
600 for (i = 0; i < klass->method.count; ++i) {
601 guint32 cols [MONO_METHOD_SIZE];
602 MonoMethod *method;
603 const char *m_name;
604 MonoMethodSignature *other_sig;
606 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
608 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
610 if (!((fqname && !strcmp (m_name, fqname)) ||
611 (qname && !strcmp (m_name, qname)) ||
612 (name && !strcmp (m_name, name))))
613 continue;
615 method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
616 if (method) {
617 other_sig = mono_method_signature (method);
618 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
619 return method;
624 mono_class_setup_methods (klass);
626 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
627 See mono/tests/generic-type-load-exception.2.il
628 FIXME we should better report this error to the caller
630 if (!klass->methods)
631 return NULL;
632 for (i = 0; i < klass->method.count; ++i) {
633 MonoMethod *m = klass->methods [i];
634 MonoMethodSignature *msig;
636 /* We must cope with failing to load some of the types. */
637 if (!m)
638 continue;
640 if (!((fqname && !strcmp (m->name, fqname)) ||
641 (qname && !strcmp (m->name, qname)) ||
642 (name && !strcmp (m->name, name))))
643 continue;
644 msig = mono_method_signature (m);
645 if (!msig)
646 continue;
648 if (sig->call_convention == MONO_CALL_VARARG) {
649 if (mono_metadata_signature_vararg_match (sig, msig))
650 break;
651 } else {
652 if (mono_metadata_signature_equal (sig, msig))
653 break;
657 if (i < klass->method.count)
658 return mono_class_get_method_by_index (from_class, i);
659 return NULL;
662 static MonoMethod *
663 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
665 int i;
666 char *qname, *fqname, *class_name;
667 gboolean is_interface;
668 MonoMethod *result = NULL;
670 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
672 if (ic) {
673 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
675 qname = g_strconcat (class_name, ".", name, NULL);
676 if (ic->name_space && ic->name_space [0])
677 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
678 else
679 fqname = NULL;
680 } else
681 class_name = qname = fqname = NULL;
683 while (in_class) {
684 g_assert (from_class);
685 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
686 if (result)
687 goto out;
689 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
690 break;
693 * This happens when we fail to lazily load the interfaces of one of the types.
694 * On such case we can't just bail out since user code depends on us trying harder.
696 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
697 in_class = in_class->parent;
698 from_class = from_class->parent;
699 continue;
702 for (i = 0; i < in_class->interface_offsets_count; i++) {
703 MonoClass *in_ic = in_class->interfaces_packed [i];
704 MonoClass *from_ic = from_class->interfaces_packed [i];
705 char *ic_qname, *ic_fqname, *ic_class_name;
707 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
708 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
709 if (in_ic->name_space && in_ic->name_space [0])
710 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
711 else
712 ic_fqname = NULL;
714 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic);
715 g_free (ic_class_name);
716 g_free (ic_fqname);
717 g_free (ic_qname);
718 if (result)
719 goto out;
722 in_class = in_class->parent;
723 from_class = from_class->parent;
725 g_assert (!in_class == !from_class);
727 if (is_interface)
728 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
730 out:
731 g_free (class_name);
732 g_free (fqname);
733 g_free (qname);
734 return result;
737 static MonoMethodSignature*
738 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
740 MonoMethodSignature *res;
741 gboolean is_open;
742 int i;
744 mono_error_init (error);
745 if (!context)
746 return sig;
748 res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
749 res->param_count = sig->param_count;
750 res->sentinelpos = -1;
751 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
752 if (!mono_error_ok (error))
753 goto fail;
754 is_open = mono_class_is_open_constructed_type (res->ret);
755 for (i = 0; i < sig->param_count; ++i) {
756 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
757 if (!mono_error_ok (error))
758 goto fail;
760 if (!is_open)
761 is_open = mono_class_is_open_constructed_type (res->params [i]);
763 res->hasthis = sig->hasthis;
764 res->explicit_this = sig->explicit_this;
765 res->call_convention = sig->call_convention;
766 res->pinvoke = sig->pinvoke;
767 res->generic_param_count = sig->generic_param_count;
768 res->sentinelpos = sig->sentinelpos;
769 res->has_type_parameters = is_open;
770 res->is_inflated = 1;
771 return res;
773 fail:
774 if (res->ret)
775 mono_metadata_free_type (res->ret);
776 for (i = 0; i < sig->param_count; ++i) {
777 if (res->params [i])
778 mono_metadata_free_type (res->params [i]);
780 g_free (res);
781 return NULL;
785 * mono_inflate_generic_signature:
787 * Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
789 MonoMethodSignature*
790 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
792 MonoMethodSignature *res, *cached;
794 res = inflate_generic_signature_checked (NULL, sig, context, error);
795 if (!mono_error_ok (error))
796 return NULL;
797 cached = mono_metadata_get_inflated_signature (res, context);
798 if (cached != res)
799 mono_metadata_free_inflated_signature (res);
800 return cached;
803 static MonoMethodHeader*
804 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
806 MonoMethodHeader *res;
807 int i;
808 res = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
809 res->code = header->code;
810 res->code_size = header->code_size;
811 res->max_stack = header->max_stack;
812 res->num_clauses = header->num_clauses;
813 res->init_locals = header->init_locals;
814 res->num_locals = header->num_locals;
815 res->clauses = header->clauses;
816 for (i = 0; i < header->num_locals; ++i)
817 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
818 if (res->num_clauses) {
819 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
820 for (i = 0; i < header->num_clauses; ++i) {
821 MonoExceptionClause *clause = &res->clauses [i];
822 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
823 continue;
824 clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
827 return res;
831 * token is the method_ref/def/spec token used in a call IL instruction.
833 MonoMethodSignature*
834 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
836 int table = mono_metadata_token_table (token);
837 int idx = mono_metadata_token_index (token);
838 int sig_idx;
839 guint32 cols [MONO_MEMBERREF_SIZE];
840 MonoMethodSignature *sig;
841 const char *ptr;
843 /* !table is for wrappers: we should really assign their own token to them */
844 if (!table || table == MONO_TABLE_METHOD)
845 return mono_method_signature (method);
847 if (table == MONO_TABLE_METHODSPEC) {
848 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
849 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated)
850 return NULL;
852 return mono_method_signature (method);
855 if (method->klass->generic_class)
856 return mono_method_signature (method);
858 #ifndef DISABLE_REFLECTION_EMIT
859 if (image->dynamic) {
860 sig = mono_reflection_lookup_signature (image, method, token);
861 } else {
862 #endif
863 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
864 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
866 sig = find_cached_memberref_sig (image, sig_idx);
867 if (!sig) {
868 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
869 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
870 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
872 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));
873 return NULL;
876 ptr = mono_metadata_blob_heap (image, sig_idx);
877 mono_metadata_decode_blob_size (ptr, &ptr);
878 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
879 if (!sig)
880 return NULL;
881 sig = cache_memberref_sig (image, sig_idx, sig);
883 /* FIXME: we probably should verify signature compat in the dynamic case too*/
884 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
885 guint32 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
886 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
888 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));
889 return NULL;
891 #ifndef DISABLE_REFLECTION_EMIT
893 #endif
896 if (context) {
897 MonoError error;
898 MonoMethodSignature *cached;
900 /* This signature is not owned by a MonoMethod, so need to cache */
901 sig = inflate_generic_signature_checked (image, sig, context, &error);
902 if (!mono_error_ok (&error)) {/*XXX bubble up this and kill one use of loader errors */
903 mono_loader_set_error_bad_image (g_strdup_printf ("Could not inflate signature %s", mono_error_get_message (&error)));
904 mono_error_cleanup (&error);
905 return NULL;
908 cached = mono_metadata_get_inflated_signature (sig, context);
909 if (cached != sig)
910 mono_metadata_free_inflated_signature (sig);
911 else
912 inflated_signatures_size += mono_metadata_signature_size (cached);
913 sig = cached;
916 return sig;
919 MonoMethodSignature*
920 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
922 return mono_method_get_signature_full (method, image, token, NULL);
925 /* this is only for the typespec array methods */
926 MonoMethod*
927 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
929 int i;
931 mono_class_setup_methods (klass);
932 g_assert (!klass->exception_type); /*FIXME this should not fail, right?*/
933 for (i = 0; i < klass->method.count; ++i) {
934 MonoMethod *method = klass->methods [i];
935 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
936 return method;
938 return NULL;
941 static MonoMethod *
942 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
943 gboolean *used_context)
945 MonoClass *klass = NULL;
946 MonoMethod *method = NULL;
947 MonoTableInfo *tables = image->tables;
948 guint32 cols[6];
949 guint32 nindex, class, sig_idx;
950 const char *mname;
951 MonoMethodSignature *sig;
952 const char *ptr;
954 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
955 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
956 class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
957 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
958 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
960 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
963 * Whether we actually used the `typespec_context' or not.
964 * This is used to tell our caller whether or not it's safe to insert the returned
965 * method into a cache.
967 if (used_context)
968 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
970 switch (class) {
971 case MONO_MEMBERREF_PARENT_TYPEREF:
972 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
973 if (!klass) {
974 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
975 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
976 mono_loader_set_error_type_load (name, image->assembly_name);
977 g_free (name);
978 return NULL;
980 break;
981 case MONO_MEMBERREF_PARENT_TYPESPEC:
983 * Parse the TYPESPEC in the parent's context.
985 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
986 if (!klass) {
987 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
988 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
989 mono_loader_set_error_type_load (name, image->assembly_name);
990 g_free (name);
991 return NULL;
993 break;
994 case MONO_MEMBERREF_PARENT_TYPEDEF:
995 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
996 if (!klass) {
997 char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
998 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
999 mono_loader_set_error_type_load (name, image->assembly_name);
1000 g_free (name);
1001 return NULL;
1003 break;
1004 case MONO_MEMBERREF_PARENT_METHODDEF:
1005 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
1007 default:
1009 /* This message leaks */
1010 char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
1011 mono_loader_set_error_method_load ("", message);
1012 return NULL;
1016 g_assert (klass);
1017 mono_class_init (klass);
1019 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1021 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1022 mono_loader_set_error_method_load (klass->name, mname);
1023 return NULL;
1026 ptr = mono_metadata_blob_heap (image, sig_idx);
1027 mono_metadata_decode_blob_size (ptr, &ptr);
1029 sig = find_cached_memberref_sig (image, sig_idx);
1030 if (!sig) {
1031 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
1032 if (sig == NULL)
1033 return NULL;
1035 sig = cache_memberref_sig (image, sig_idx, sig);
1038 switch (class) {
1039 case MONO_MEMBERREF_PARENT_TYPEREF:
1040 case MONO_MEMBERREF_PARENT_TYPEDEF:
1041 method = find_method (klass, NULL, mname, sig, klass);
1042 break;
1044 case MONO_MEMBERREF_PARENT_TYPESPEC: {
1045 MonoType *type;
1047 type = &klass->byval_arg;
1049 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1050 MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1051 method = find_method (in_class, NULL, mname, sig, klass);
1052 break;
1055 /* we're an array and we created these methods already in klass in mono_class_init () */
1056 method = mono_method_search_in_array_class (klass, mname, sig);
1057 break;
1059 default:
1060 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
1061 g_assert_not_reached ();
1064 if (!method) {
1065 char *msig = mono_signature_get_desc (sig, FALSE);
1066 char * class_name = mono_type_get_name (&klass->byval_arg);
1067 GString *s = g_string_new (mname);
1068 if (sig->generic_param_count)
1069 g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1070 g_string_append_printf (s, "(%s)", msig);
1071 g_free (msig);
1072 msig = g_string_free (s, FALSE);
1074 g_warning (
1075 "Missing method %s::%s in assembly %s, referenced in assembly %s",
1076 class_name, msig, klass->image->name, image->name);
1077 mono_loader_set_error_method_load (class_name, mname);
1078 g_free (msig);
1079 g_free (class_name);
1082 return method;
1085 static MonoMethod *
1086 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
1088 MonoError error;
1089 MonoMethod *method;
1090 MonoClass *klass;
1091 MonoTableInfo *tables = image->tables;
1092 MonoGenericContext new_context;
1093 MonoGenericInst *inst;
1094 const char *ptr;
1095 guint32 cols [MONO_METHODSPEC_SIZE];
1096 guint32 token, nindex, param_count;
1098 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1099 token = cols [MONO_METHODSPEC_METHOD];
1100 nindex = token >> MONO_METHODDEFORREF_BITS;
1102 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL))
1103 return NULL;
1105 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1107 mono_metadata_decode_value (ptr, &ptr);
1108 ptr++;
1109 param_count = mono_metadata_decode_value (ptr, &ptr);
1110 g_assert (param_count);
1112 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
1113 if (!inst)
1114 return NULL;
1116 if (context && inst->is_open) {
1117 inst = mono_metadata_inflate_generic_inst (inst, context, &error);
1118 if (!mono_error_ok (&error)) {
1119 mono_error_cleanup (&error); /*FIXME don't swallow error message.*/
1120 return NULL;
1124 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
1125 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
1126 else
1127 method = method_from_memberref (image, nindex, context, NULL);
1129 if (!method)
1130 return NULL;
1132 klass = method->klass;
1134 if (klass->generic_class) {
1135 g_assert (method->is_inflated);
1136 method = ((MonoMethodInflated *) method)->declaring;
1139 new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1140 new_context.method_inst = inst;
1142 return mono_class_inflate_generic_method_full (method, klass, &new_context);
1145 struct _MonoDllMap {
1146 char *dll;
1147 char *target;
1148 char *func;
1149 char *target_func;
1150 MonoDllMap *next;
1153 static MonoDllMap *global_dll_map;
1155 static int
1156 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1157 int found = 0;
1159 *rdll = dll;
1161 if (!dll_map)
1162 return 0;
1164 mono_loader_lock ();
1167 * we use the first entry we find that matches, since entries from
1168 * the config file are prepended to the list and we document that the
1169 * later entries win.
1171 for (; dll_map; dll_map = dll_map->next) {
1172 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1173 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1174 continue;
1175 } else if (strcmp (dll_map->dll, dll)) {
1176 continue;
1178 if (!found && dll_map->target) {
1179 *rdll = dll_map->target;
1180 found = 1;
1181 /* we don't quit here, because we could find a full
1182 * entry that matches also function and that has priority.
1185 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1186 *rfunc = dll_map->target_func;
1187 break;
1191 mono_loader_unlock ();
1192 return found;
1195 static int
1196 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1198 int res;
1199 if (assembly && assembly->dll_map) {
1200 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1201 if (res)
1202 return res;
1204 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1208 * mono_dllmap_insert:
1209 * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1210 * @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
1211 * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1212 * @tdll: The name of the library to map the specified @dll if it matches.
1213 * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1215 * LOCKING: Acquires the loader lock.
1217 * This function is used to programatically add DllImport remapping in either
1218 * a specific assembly, or as a global remapping. This is done by remapping
1219 * references in a DllImport attribute from the @dll library name into the @tdll
1220 * name. If the @dll name contains the prefix "i:", the comparison of the
1221 * library name is done without case sensitivity.
1223 * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1224 * or the name of the function as determined by DllImport. If you pass @func, you
1225 * must also pass @tfunc which is the name of the target function to invoke on a match.
1227 * Example:
1228 * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1230 * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1231 * the contents of relocated_demo_path for all assemblies in the Mono process.
1233 * NOTE: This can be called before the runtime is initialized, for example from
1234 * mono_config_parse ().
1236 void
1237 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1239 MonoDllMap *entry;
1241 mono_loader_init ();
1243 mono_loader_lock ();
1245 if (!assembly) {
1246 entry = g_malloc0 (sizeof (MonoDllMap));
1247 entry->dll = dll? g_strdup (dll): NULL;
1248 entry->target = tdll? g_strdup (tdll): NULL;
1249 entry->func = func? g_strdup (func): NULL;
1250 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1251 entry->next = global_dll_map;
1252 global_dll_map = entry;
1253 } else {
1254 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1255 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1256 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1257 entry->func = func? mono_image_strdup (assembly, func): NULL;
1258 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1259 entry->next = assembly->dll_map;
1260 assembly->dll_map = entry;
1263 mono_loader_unlock ();
1266 static void
1267 free_dllmap (MonoDllMap *map)
1269 while (map) {
1270 MonoDllMap *next = map->next;
1272 g_free (map->dll);
1273 g_free (map->target);
1274 g_free (map->func);
1275 g_free (map->target_func);
1276 g_free (map);
1277 map = next;
1281 static void
1282 dllmap_cleanup (void)
1284 free_dllmap (global_dll_map);
1285 global_dll_map = NULL;
1288 static GHashTable *global_module_map;
1290 static MonoDl*
1291 cached_module_load (const char *name, int flags, char **err)
1293 MonoDl *res;
1295 if (err)
1296 *err = NULL;
1297 mono_loader_lock ();
1298 if (!global_module_map)
1299 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1300 res = g_hash_table_lookup (global_module_map, name);
1301 if (res) {
1302 mono_loader_unlock ();
1303 return res;
1305 res = mono_dl_open (name, flags, err);
1306 if (res)
1307 g_hash_table_insert (global_module_map, g_strdup (name), res);
1308 mono_loader_unlock ();
1309 return res;
1312 static MonoDl *internal_module;
1314 static gboolean
1315 is_absolute_path (const char *path)
1317 #ifdef PLATFORM_MACOSX
1318 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1319 !strncmp (path, "@rpath/", 7))
1320 return TRUE;
1321 #endif
1322 return g_path_is_absolute (path);
1325 gpointer
1326 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1328 MonoImage *image = method->klass->image;
1329 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1330 MonoTableInfo *tables = image->tables;
1331 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1332 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1333 guint32 im_cols [MONO_IMPLMAP_SIZE];
1334 guint32 scope_token;
1335 const char *import = NULL;
1336 const char *orig_scope;
1337 const char *new_scope;
1338 char *error_msg;
1339 char *full_name, *file_name, *found_name = NULL;
1340 int i;
1341 MonoDl *module = NULL;
1342 gboolean cached = FALSE;
1344 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1346 if (exc_class) {
1347 *exc_class = NULL;
1348 *exc_arg = NULL;
1351 if (piinfo->addr)
1352 return piinfo->addr;
1354 if (method->klass->image->dynamic) {
1355 MonoReflectionMethodAux *method_aux =
1356 g_hash_table_lookup (
1357 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1358 if (!method_aux)
1359 return NULL;
1361 import = method_aux->dllentry;
1362 orig_scope = method_aux->dll;
1364 else {
1365 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1366 return NULL;
1368 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1370 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1371 return NULL;
1373 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1374 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1375 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1376 orig_scope = mono_metadata_string_heap (image, scope_token);
1379 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1381 if (!module) {
1382 mono_loader_lock ();
1383 if (!image->pinvoke_scopes) {
1384 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1385 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1387 module = g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1388 found_name = g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1389 mono_loader_unlock ();
1390 if (module)
1391 cached = TRUE;
1392 if (found_name)
1393 found_name = g_strdup (found_name);
1396 if (!module) {
1397 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1398 "DllImport attempting to load: '%s'.", new_scope);
1400 /* we allow a special name to dlopen from the running process namespace */
1401 if (strcmp (new_scope, "__Internal") == 0){
1402 if (internal_module == NULL)
1403 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1404 module = internal_module;
1409 * Try loading the module using a variety of names
1411 for (i = 0; i < 4; ++i) {
1412 char *base_name = NULL, *dir_name = NULL;
1413 gboolean is_absolute = is_absolute_path (new_scope);
1415 switch (i) {
1416 case 0:
1417 /* Try the original name */
1418 file_name = g_strdup (new_scope);
1419 break;
1420 case 1:
1421 /* Try trimming the .dll extension */
1422 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1423 file_name = g_strdup (new_scope);
1424 file_name [strlen (new_scope) - 4] = '\0';
1426 else
1427 continue;
1428 break;
1429 case 2:
1430 if (is_absolute) {
1431 dir_name = g_path_get_dirname (new_scope);
1432 base_name = g_path_get_basename (new_scope);
1433 if (strstr (base_name, "lib") != base_name) {
1434 char *tmp = g_strdup_printf ("lib%s", base_name);
1435 g_free (base_name);
1436 base_name = tmp;
1437 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1438 break;
1440 } else if (strstr (new_scope, "lib") != new_scope) {
1441 file_name = g_strdup_printf ("lib%s", new_scope);
1442 break;
1444 continue;
1445 default:
1446 #ifndef TARGET_WIN32
1447 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1448 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1449 !g_ascii_strcasecmp ("user32", new_scope) ||
1450 !g_ascii_strcasecmp ("kernel", new_scope)) {
1451 file_name = g_strdup ("libMonoSupportW.so");
1452 } else
1453 #endif
1454 continue;
1455 #ifndef TARGET_WIN32
1456 break;
1457 #endif
1460 if (is_absolute) {
1461 if (!dir_name)
1462 dir_name = g_path_get_dirname (file_name);
1463 if (!base_name)
1464 base_name = g_path_get_basename (file_name);
1467 if (!module && is_absolute) {
1468 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1469 if (!module) {
1470 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1471 "DllImport error loading library '%s': '%s'.",
1472 file_name, error_msg);
1473 g_free (error_msg);
1474 } else {
1475 found_name = g_strdup (file_name);
1479 if (!module && !is_absolute) {
1480 void *iter = NULL;
1481 char *mdirname = g_path_get_dirname (image->name);
1482 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1483 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1484 if (!module) {
1485 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1486 "DllImport error loading library '%s': '%s'.",
1487 full_name, error_msg);
1488 g_free (error_msg);
1489 } else {
1490 found_name = g_strdup (full_name);
1492 g_free (full_name);
1493 if (module)
1494 break;
1496 g_free (mdirname);
1499 if (!module) {
1500 void *iter = NULL;
1501 char *file_or_base = is_absolute ? base_name : file_name;
1502 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1503 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1504 if (!module) {
1505 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1506 "DllImport error loading library '%s': '%s'.",
1507 full_name, error_msg);
1508 g_free (error_msg);
1509 } else {
1510 found_name = g_strdup (full_name);
1512 g_free (full_name);
1513 if (module)
1514 break;
1518 if (!module) {
1519 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1520 if (!module) {
1521 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1522 "DllImport error loading library '%s': '%s'.",
1523 file_name, error_msg);
1524 } else {
1525 found_name = g_strdup (file_name);
1529 g_free (file_name);
1530 if (is_absolute) {
1531 g_free (base_name);
1532 g_free (dir_name);
1535 if (module)
1536 break;
1539 if (!module) {
1540 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1541 "DllImport unable to load library '%s'.",
1542 error_msg);
1543 g_free (error_msg);
1545 if (exc_class) {
1546 *exc_class = "DllNotFoundException";
1547 *exc_arg = new_scope;
1549 return NULL;
1552 if (!cached) {
1553 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1554 "DllImport loaded library '%s'.", found_name);
1555 mono_loader_lock ();
1556 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1557 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1558 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1560 mono_loader_unlock ();
1563 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1564 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1565 g_free (found_name);
1567 #ifdef TARGET_WIN32
1568 if (import && import [0] == '#' && isdigit (import [1])) {
1569 char *end;
1570 long id;
1572 id = strtol (import + 1, &end, 10);
1573 if (id > 0 && *end == '\0')
1574 import++;
1576 #endif
1577 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1578 "Searching for '%s'.", import);
1580 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1581 error_msg = mono_dl_symbol (module, import, &piinfo->addr);
1582 } else {
1583 char *mangled_name = NULL, *mangled_name2 = NULL;
1584 int mangle_charset;
1585 int mangle_stdcall;
1586 int mangle_param_count;
1587 #ifdef TARGET_WIN32
1588 int param_count;
1589 #endif
1592 * Search using a variety of mangled names
1594 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1595 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1596 gboolean need_param_count = FALSE;
1597 #ifdef TARGET_WIN32
1598 if (mangle_stdcall > 0)
1599 need_param_count = TRUE;
1600 #endif
1601 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1603 if (piinfo->addr)
1604 continue;
1606 mangled_name = (char*)import;
1607 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1608 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1609 /* Try the mangled name first */
1610 if (mangle_charset == 0)
1611 mangled_name = g_strconcat (import, "W", NULL);
1612 break;
1613 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1614 #ifdef TARGET_WIN32
1615 if (mangle_charset == 0)
1616 mangled_name = g_strconcat (import, "W", NULL);
1617 #else
1618 /* Try the mangled name last */
1619 if (mangle_charset == 1)
1620 mangled_name = g_strconcat (import, "A", NULL);
1621 #endif
1622 break;
1623 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1624 default:
1625 /* Try the mangled name last */
1626 if (mangle_charset == 1)
1627 mangled_name = g_strconcat (import, "A", NULL);
1628 break;
1631 #ifdef TARGET_WIN32
1632 if (mangle_param_count == 0)
1633 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1634 else
1635 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1636 param_count = mangle_param_count;
1638 /* Try the stdcall mangled name */
1640 * gcc under windows creates mangled names without the underscore, but MS.NET
1641 * doesn't support it, so we doesn't support it either.
1643 if (mangle_stdcall == 1)
1644 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1645 else
1646 mangled_name2 = mangled_name;
1647 #else
1648 mangled_name2 = mangled_name;
1649 #endif
1651 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1652 "Probing '%s'.", mangled_name2);
1654 error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1655 g_free (error_msg);
1656 error_msg = NULL;
1658 if (piinfo->addr)
1659 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1660 "Found as '%s'.", mangled_name2);
1662 if (mangled_name != mangled_name2)
1663 g_free (mangled_name2);
1664 if (mangled_name != import)
1665 g_free (mangled_name);
1671 if (!piinfo->addr) {
1672 g_free (error_msg);
1673 if (exc_class) {
1674 *exc_class = "EntryPointNotFoundException";
1675 *exc_arg = import;
1677 return NULL;
1679 return piinfo->addr;
1683 * LOCKING: assumes the loader lock to be taken.
1685 static MonoMethod *
1686 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1687 MonoGenericContext *context, gboolean *used_context)
1689 MonoMethod *result;
1690 int table = mono_metadata_token_table (token);
1691 int idx = mono_metadata_token_index (token);
1692 MonoTableInfo *tables = image->tables;
1693 MonoGenericContainer *generic_container = NULL, *container = NULL;
1694 const char *sig = NULL;
1695 int size;
1696 guint32 cols [MONO_TYPEDEF_SIZE];
1698 if (image->dynamic) {
1699 MonoClass *handle_class;
1701 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1702 // This checks the memberref type as well
1703 if (result && handle_class != mono_defaults.methodhandle_class) {
1704 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1705 return NULL;
1707 return result;
1710 if (table != MONO_TABLE_METHOD) {
1711 if (table == MONO_TABLE_METHODSPEC) {
1712 if (used_context) *used_context = TRUE;
1713 return method_from_methodspec (image, context, idx);
1715 if (table != MONO_TABLE_MEMBERREF) {
1716 g_warning ("got wrong token: 0x%08x\n", token);
1717 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1718 return NULL;
1720 return method_from_memberref (image, idx, context, used_context);
1723 if (used_context) *used_context = FALSE;
1725 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1726 mono_loader_set_error_bad_image (g_strdup_printf ("Bad method token 0x%08x on image %s.", token, image->name));
1727 return NULL;
1730 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1732 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1733 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1734 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1735 } else {
1736 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1737 methods_size += sizeof (MonoMethod);
1740 mono_stats.method_count ++;
1742 if (!klass) { /*FIXME put this before the image alloc*/
1743 guint32 type = mono_metadata_typedef_from_method (image, token);
1744 if (!type)
1745 return NULL;
1746 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1747 if (klass == NULL)
1748 return NULL;
1751 result->slot = -1;
1752 result->klass = klass;
1753 result->flags = cols [2];
1754 result->iflags = cols [1];
1755 result->token = token;
1756 result->name = mono_metadata_string_heap (image, cols [3]);
1758 if (!sig) /* already taken from the methodref */
1759 sig = mono_metadata_blob_heap (image, cols [4]);
1760 size = mono_metadata_decode_blob_size (sig, &sig);
1762 container = klass->generic_container;
1765 * load_generic_params does a binary search so only call it if the method
1766 * is generic.
1768 if (*sig & 0x10)
1769 generic_container = mono_metadata_load_generic_params (image, token, container);
1770 if (generic_container) {
1771 result->is_generic = TRUE;
1772 generic_container->owner.method = result;
1773 /*FIXME put this before the image alloc*/
1774 if (!mono_metadata_load_generic_param_constraints_full (image, token, generic_container))
1775 return NULL;
1777 container = generic_container;
1780 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1781 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1782 result->string_ctor = 1;
1783 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1784 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1786 #ifdef TARGET_WIN32
1787 /* IJW is P/Invoke with a predefined function pointer. */
1788 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1789 piinfo->addr = mono_image_rva_map (image, cols [0]);
1790 g_assert (piinfo->addr);
1792 #endif
1793 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1794 /* Native methods can have no map. */
1795 if (piinfo->implmap_idx)
1796 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1799 if (generic_container)
1800 mono_method_set_generic_container (result, generic_container);
1802 return result;
1805 MonoMethod *
1806 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1808 return mono_get_method_full (image, token, klass, NULL);
1811 MonoMethod *
1812 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1813 MonoGenericContext *context)
1815 MonoMethod *result = NULL;
1816 gboolean used_context = FALSE;
1818 /* We do everything inside the lock to prevent creation races */
1820 mono_image_lock (image);
1822 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1823 if (!image->method_cache)
1824 image->method_cache = g_hash_table_new (NULL, NULL);
1825 result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1826 } else if (!image->dynamic) {
1827 if (!image->methodref_cache)
1828 image->methodref_cache = g_hash_table_new (NULL, NULL);
1829 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1831 mono_image_unlock (image);
1833 if (result)
1834 return result;
1837 result = mono_get_method_from_token (image, token, klass, context, &used_context);
1838 if (!result)
1839 return NULL;
1841 mono_image_lock (image);
1842 if (!used_context && !result->is_inflated) {
1843 MonoMethod *result2 = NULL;
1845 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1846 result2 = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1847 else if (!image->dynamic)
1848 result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1850 if (result2) {
1851 mono_image_unlock (image);
1852 return result2;
1855 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1856 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1857 else if (!image->dynamic)
1858 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1861 mono_image_unlock (image);
1863 return result;
1866 static MonoMethod *
1867 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context)
1869 MonoMethod *result;
1870 MonoClass *ic = NULL;
1871 MonoGenericContext *method_context = NULL;
1872 MonoMethodSignature *sig, *original_sig;
1874 mono_class_init (constrained_class);
1875 original_sig = sig = mono_method_signature (method);
1876 if (sig == NULL) {
1877 return NULL;
1880 if (method->is_inflated && sig->generic_param_count) {
1881 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1882 sig = mono_method_signature (imethod->declaring); /*We assume that if the inflated method signature is valid, the declaring method is too*/
1883 method_context = mono_method_get_context (method);
1885 original_sig = sig;
1887 * We must inflate the signature with the class instantiation to work on
1888 * cases where a class inherit from a generic type and the override replaces
1889 * any type argument which a concrete type. See #325283.
1891 if (method_context->class_inst) {
1892 MonoError error;
1893 MonoGenericContext ctx;
1894 ctx.method_inst = NULL;
1895 ctx.class_inst = method_context->class_inst;
1896 /*Fixme, property propagate this error*/
1897 sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, &error);
1898 if (!mono_error_ok (&error)) {
1899 mono_error_cleanup (&error);
1900 return NULL;
1905 if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1906 ic = method->klass;
1908 result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1909 if (sig != original_sig)
1910 mono_metadata_free_inflated_signature (sig);
1912 if (!result) {
1913 char *m = mono_method_full_name (method, 1);
1914 g_warning ("Missing method %s.%s.%s in assembly %s method %s", method->klass->name_space,
1915 method->klass->name, method->name, image->name, m);
1916 g_free (m);
1917 return NULL;
1920 if (method_context)
1921 result = mono_class_inflate_generic_method (result, method_context);
1923 return result;
1926 MonoMethod *
1927 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
1928 MonoGenericContext *context)
1930 MonoMethod *result;
1932 g_assert (method);
1934 mono_loader_lock ();
1936 result = get_method_constrained (image, method, constrained_class, context);
1938 mono_loader_unlock ();
1939 return result;
1942 * mono_get_method_constrained:
1944 * This is used when JITing the `constrained.' opcode.
1946 * This returns two values: the contrained method, which has been inflated
1947 * as the function return value; And the original CIL-stream method as
1948 * declared in cil_method. The later is used for verification.
1950 MonoMethod *
1951 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1952 MonoGenericContext *context, MonoMethod **cil_method)
1954 MonoMethod *result;
1956 mono_loader_lock ();
1958 *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL);
1959 if (!*cil_method) {
1960 mono_loader_unlock ();
1961 return NULL;
1964 result = get_method_constrained (image, *cil_method, constrained_class, context);
1966 mono_loader_unlock ();
1967 return result;
1970 void
1971 mono_free_method (MonoMethod *method)
1973 if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1974 mono_profiler_method_free (method);
1976 /* FIXME: This hack will go away when the profiler will support freeing methods */
1977 if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1978 return;
1980 if (method->signature) {
1982 * FIXME: This causes crashes because the types inside signatures and
1983 * locals are shared.
1985 /* mono_metadata_free_method_signature (method->signature); */
1986 /* g_free (method->signature); */
1989 if (method->dynamic) {
1990 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1991 int i;
1993 mono_marshal_free_dynamic_wrappers (method);
1995 mono_image_property_remove (method->klass->image, method);
1997 g_free ((char*)method->name);
1998 if (mw->header) {
1999 g_free ((char*)mw->header->code);
2000 for (i = 0; i < mw->header->num_locals; ++i)
2001 g_free (mw->header->locals [i]);
2002 g_free (mw->header->clauses);
2003 g_free (mw->header);
2005 g_free (mw->method_data);
2006 g_free (method->signature);
2007 g_free (method);
2011 void
2012 mono_method_get_param_names (MonoMethod *method, const char **names)
2014 int i, lastp;
2015 MonoClass *klass;
2016 MonoTableInfo *methodt;
2017 MonoTableInfo *paramt;
2018 MonoMethodSignature *signature;
2019 guint32 idx;
2021 if (method->is_inflated)
2022 method = ((MonoMethodInflated *) method)->declaring;
2024 signature = mono_method_signature (method);
2025 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2026 number of arguments and allocate a properly sized array. */
2027 if (signature == NULL)
2028 return;
2030 if (!signature->param_count)
2031 return;
2033 for (i = 0; i < signature->param_count; ++i)
2034 names [i] = "";
2036 klass = method->klass;
2037 if (klass->rank)
2038 return;
2040 mono_class_init (klass);
2042 if (klass->image->dynamic) {
2043 MonoReflectionMethodAux *method_aux =
2044 g_hash_table_lookup (
2045 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2046 if (method_aux && method_aux->param_names) {
2047 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2048 if (method_aux->param_names [i + 1])
2049 names [i] = method_aux->param_names [i + 1];
2051 return;
2054 if (method->wrapper_type) {
2055 char **pnames = NULL;
2057 mono_image_lock (klass->image);
2058 if (klass->image->wrapper_param_names)
2059 pnames = g_hash_table_lookup (klass->image->wrapper_param_names, method);
2060 mono_image_unlock (klass->image);
2062 if (pnames) {
2063 for (i = 0; i < signature->param_count; ++i)
2064 names [i] = pnames [i];
2066 return;
2069 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2070 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2071 idx = mono_method_get_index (method);
2072 if (idx > 0) {
2073 guint32 cols [MONO_PARAM_SIZE];
2074 guint param_index;
2076 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2078 if (idx < methodt->rows)
2079 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2080 else
2081 lastp = paramt->rows + 1;
2082 for (i = param_index; i < lastp; ++i) {
2083 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2084 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2085 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2090 guint32
2091 mono_method_get_param_token (MonoMethod *method, int index)
2093 MonoClass *klass = method->klass;
2094 MonoTableInfo *methodt;
2095 guint32 idx;
2097 mono_class_init (klass);
2099 if (klass->image->dynamic) {
2100 g_assert_not_reached ();
2103 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2104 idx = mono_method_get_index (method);
2105 if (idx > 0) {
2106 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2108 if (index == -1)
2109 /* Return value */
2110 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2111 else
2112 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2115 return 0;
2118 void
2119 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2121 int i, lastp;
2122 MonoClass *klass = method->klass;
2123 MonoTableInfo *methodt;
2124 MonoTableInfo *paramt;
2125 MonoMethodSignature *signature;
2126 guint32 idx;
2128 signature = mono_method_signature (method);
2129 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2131 for (i = 0; i < signature->param_count + 1; ++i)
2132 mspecs [i] = NULL;
2134 if (method->klass->image->dynamic) {
2135 MonoReflectionMethodAux *method_aux =
2136 g_hash_table_lookup (
2137 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2138 if (method_aux && method_aux->param_marshall) {
2139 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2140 for (i = 0; i < signature->param_count + 1; ++i)
2141 if (dyn_specs [i]) {
2142 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2143 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2144 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2145 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2148 return;
2151 mono_class_init (klass);
2153 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2154 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2155 idx = mono_method_get_index (method);
2156 if (idx > 0) {
2157 guint32 cols [MONO_PARAM_SIZE];
2158 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2160 if (idx < methodt->rows)
2161 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2162 else
2163 lastp = paramt->rows + 1;
2165 for (i = param_index; i < lastp; ++i) {
2166 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2168 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2169 const char *tp;
2170 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2171 g_assert (tp);
2172 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2176 return;
2180 gboolean
2181 mono_method_has_marshal_info (MonoMethod *method)
2183 int i, lastp;
2184 MonoClass *klass = method->klass;
2185 MonoTableInfo *methodt;
2186 MonoTableInfo *paramt;
2187 guint32 idx;
2189 if (method->klass->image->dynamic) {
2190 MonoReflectionMethodAux *method_aux =
2191 g_hash_table_lookup (
2192 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2193 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2194 if (dyn_specs) {
2195 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2196 if (dyn_specs [i])
2197 return TRUE;
2199 return FALSE;
2202 mono_class_init (klass);
2204 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2205 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2206 idx = mono_method_get_index (method);
2207 if (idx > 0) {
2208 guint32 cols [MONO_PARAM_SIZE];
2209 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2211 if (idx + 1 < methodt->rows)
2212 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2213 else
2214 lastp = paramt->rows + 1;
2216 for (i = param_index; i < lastp; ++i) {
2217 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2219 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2220 return TRUE;
2222 return FALSE;
2224 return FALSE;
2227 gpointer
2228 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2230 void **data;
2231 g_assert (method != NULL);
2232 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2234 if (method->is_inflated)
2235 method = ((MonoMethodInflated *) method)->declaring;
2236 data = ((MonoMethodWrapper *)method)->method_data;
2237 g_assert (data != NULL);
2238 g_assert (id <= GPOINTER_TO_UINT (*data));
2239 return data [id];
2242 typedef struct {
2243 MonoStackWalk func;
2244 gpointer user_data;
2245 } StackWalkUserData;
2247 static gboolean
2248 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2250 StackWalkUserData *d = data;
2252 switch (frame->type) {
2253 case FRAME_TYPE_DEBUGGER_INVOKE:
2254 case FRAME_TYPE_MANAGED_TO_NATIVE:
2255 return FALSE;
2256 case FRAME_TYPE_MANAGED:
2257 g_assert (frame->ji);
2258 return d->func (mono_jit_info_get_method (frame->ji), frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2259 break;
2260 default:
2261 g_assert_not_reached ();
2262 return FALSE;
2266 void
2267 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2269 StackWalkUserData ud = { func, user_data };
2270 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2273 void
2274 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2276 StackWalkUserData ud = { func, user_data };
2277 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2280 static gboolean
2281 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2283 MonoMethod **dest = data;
2284 *dest = m;
2285 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2287 return managed;
2290 MonoMethod*
2291 mono_method_get_last_managed (void)
2293 MonoMethod *m = NULL;
2294 mono_stack_walk_no_il (last_managed, &m);
2295 return m;
2298 static gboolean loader_lock_track_ownership = FALSE;
2301 * mono_loader_lock:
2303 * See docs/thread-safety.txt for the locking strategy.
2305 void
2306 mono_loader_lock (void)
2308 mono_locks_acquire (&loader_mutex, LoaderLock);
2309 if (G_UNLIKELY (loader_lock_track_ownership)) {
2310 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));
2314 void
2315 mono_loader_unlock (void)
2317 mono_locks_release (&loader_mutex, LoaderLock);
2318 if (G_UNLIKELY (loader_lock_track_ownership)) {
2319 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));
2324 * mono_loader_lock_track_ownership:
2326 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2327 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2328 * thread owns the loader lock.
2330 void
2331 mono_loader_lock_track_ownership (gboolean track)
2333 loader_lock_track_ownership = track;
2337 * mono_loader_lock_is_owned_by_self:
2339 * Return whenever the current thread owns the loader lock.
2340 * This is useful to avoid blocking operations while holding the loader lock.
2342 gboolean
2343 mono_loader_lock_is_owned_by_self (void)
2345 g_assert (loader_lock_track_ownership);
2347 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2351 * mono_loader_lock_if_inited:
2353 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2354 * be used in runtime initialization code which can be executed before mono_loader_init ().
2356 void
2357 mono_loader_lock_if_inited (void)
2359 if (loader_lock_inited)
2360 mono_loader_lock ();
2363 void
2364 mono_loader_unlock_if_inited (void)
2366 if (loader_lock_inited)
2367 mono_loader_unlock ();
2371 * mono_method_signature:
2373 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2375 MonoMethodSignature*
2376 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2378 int idx;
2379 int size;
2380 MonoImage* img;
2381 const char *sig;
2382 gboolean can_cache_signature;
2383 MonoGenericContainer *container;
2384 MonoMethodSignature *signature = NULL;
2385 guint32 sig_offset;
2387 /* We need memory barriers below because of the double-checked locking pattern */
2389 mono_error_init (error);
2391 if (m->signature)
2392 return m->signature;
2394 mono_loader_lock ();
2396 if (m->signature) {
2397 mono_loader_unlock ();
2398 return m->signature;
2401 if (m->is_inflated) {
2402 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2403 /* the lock is recursive */
2404 signature = mono_method_signature (imethod->declaring);
2405 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2406 if (!mono_error_ok (error)) {
2407 mono_loader_unlock ();
2408 return NULL;
2411 inflated_signatures_size += mono_metadata_signature_size (signature);
2413 mono_memory_barrier ();
2414 m->signature = signature;
2415 mono_loader_unlock ();
2416 return m->signature;
2419 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2420 idx = mono_metadata_token_index (m->token);
2421 img = m->klass->image;
2423 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2425 g_assert (!m->klass->generic_class);
2426 container = mono_method_get_generic_container (m);
2427 if (!container)
2428 container = m->klass->generic_container;
2430 /* Generic signatures depend on the container so they cannot be cached */
2431 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2432 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2434 /* If the method has parameter attributes, that can modify the signature */
2435 if (mono_metadata_method_has_param_attrs (img, idx))
2436 can_cache_signature = FALSE;
2438 if (can_cache_signature)
2439 signature = g_hash_table_lookup (img->method_signatures, sig);
2441 if (!signature) {
2442 const char *sig_body;
2443 /*TODO we should cache the failure result somewhere*/
2444 if (!mono_verifier_verify_method_signature (img, sig_offset, error)) {
2445 mono_loader_unlock ();
2446 return NULL;
2449 size = mono_metadata_decode_blob_size (sig, &sig_body);
2451 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
2452 if (!signature) {
2453 mono_error_set_from_loader_error (error);
2454 mono_loader_unlock ();
2455 return NULL;
2458 if (can_cache_signature)
2459 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2461 signatures_size += mono_metadata_signature_size (signature);
2464 /* Verify metadata consistency */
2465 if (signature->generic_param_count) {
2466 if (!container || !container->is_method) {
2467 mono_loader_unlock ();
2468 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);
2469 return NULL;
2471 if (container->type_argc != signature->generic_param_count) {
2472 mono_loader_unlock ();
2473 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);
2474 return NULL;
2476 } else if (container && container->is_method && container->type_argc) {
2477 mono_loader_unlock ();
2478 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);
2479 return NULL;
2481 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2482 signature->pinvoke = 1;
2483 else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2484 MonoCallConvention conv = 0;
2485 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2486 signature->pinvoke = 1;
2488 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2489 case 0: /* no call conv, so using default */
2490 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2491 conv = MONO_CALL_DEFAULT;
2492 break;
2493 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2494 conv = MONO_CALL_C;
2495 break;
2496 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2497 conv = MONO_CALL_STDCALL;
2498 break;
2499 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2500 conv = MONO_CALL_THISCALL;
2501 break;
2502 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2503 conv = MONO_CALL_FASTCALL;
2504 break;
2505 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2506 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2507 default:
2508 mono_loader_unlock ();
2509 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);
2510 return NULL;
2512 signature->call_convention = conv;
2515 mono_memory_barrier ();
2516 m->signature = signature;
2518 mono_loader_unlock ();
2519 return m->signature;
2523 * mono_method_signature:
2525 * Return the signature of the method M. On failure, returns NULL.
2527 MonoMethodSignature*
2528 mono_method_signature (MonoMethod *m)
2530 MonoError error;
2531 MonoMethodSignature *sig;
2533 sig = mono_method_signature_checked (m, &error);
2534 if (!sig) {
2535 char *type_name = mono_type_get_full_name (m->klass);
2536 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2537 g_free (type_name);
2538 mono_error_cleanup (&error);
2541 return sig;
2544 const char*
2545 mono_method_get_name (MonoMethod *method)
2547 return method->name;
2550 MonoClass*
2551 mono_method_get_class (MonoMethod *method)
2553 return method->klass;
2556 guint32
2557 mono_method_get_token (MonoMethod *method)
2559 return method->token;
2562 MonoMethodHeader*
2563 mono_method_get_header (MonoMethod *method)
2565 int idx;
2566 guint32 rva;
2567 MonoImage* img;
2568 gpointer loc;
2569 MonoMethodHeader *header;
2571 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))
2572 return NULL;
2574 if (method->is_inflated) {
2575 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2576 MonoMethodHeader *header;
2578 mono_loader_lock ();
2580 if (imethod->header) {
2581 mono_loader_unlock ();
2582 return imethod->header;
2585 header = mono_method_get_header (imethod->declaring);
2586 if (!header) {
2587 mono_loader_unlock ();
2588 return NULL;
2591 imethod->header = inflate_generic_header (header, mono_method_get_context (method));
2592 mono_loader_unlock ();
2593 mono_metadata_free_mh (header);
2594 return imethod->header;
2597 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2598 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2599 g_assert (mw->header);
2600 return mw->header;
2604 * We don't need locks here: the new header is allocated from malloc memory
2605 * and is not stored anywhere in the runtime, the user needs to free it.
2607 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2608 idx = mono_metadata_token_index (method->token);
2609 img = method->klass->image;
2610 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2612 if (!mono_verifier_verify_method_header (img, rva, NULL))
2613 return NULL;
2615 loc = mono_image_rva_map (img, rva);
2616 if (!loc)
2617 return NULL;
2619 header = mono_metadata_parse_mh_full (img, mono_method_get_generic_container (method), loc);
2621 return header;
2624 guint32
2625 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2627 if (iflags)
2628 *iflags = method->iflags;
2629 return method->flags;
2633 * Find the method index in the metadata methodDef table.
2635 guint32
2636 mono_method_get_index (MonoMethod *method) {
2637 MonoClass *klass = method->klass;
2638 int i;
2640 if (klass->rank)
2641 /* constructed array methods are not in the MethodDef table */
2642 return 0;
2644 if (method->token)
2645 return mono_metadata_token_index (method->token);
2647 mono_class_setup_methods (klass);
2648 if (klass->exception_type)
2649 return 0;
2650 for (i = 0; i < klass->method.count; ++i) {
2651 if (method == klass->methods [i]) {
2652 if (klass->image->uncompressed_metadata)
2653 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2654 else
2655 return klass->method.first + i + 1;
2658 return 0;