1 /**
2 * \file
3 * Image Loader
4 *
5 * Authors:
6 * Paolo Molaro (lupus@ximian.com)
7 * Miguel de Icaza (miguel@ximian.com)
8 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 *
10 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 *
14 * This file is used by the interpreter and the JIT engine to locate
15 * assemblies. Used to load AssemblyRef and later to resolve various
16 * kinds of `Refs'.
17 *
18 * TODO:
19 * This should keep track of the assembly versions that we are loading.
20 *
21 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
22 */
23 #include <config.h>
24 #include <glib.h>
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <mono/metadata/metadata.h>
29 #include <mono/metadata/image.h>
30 #include <mono/metadata/assembly.h>
31 #include <mono/metadata/tokentype.h>
32 #include <mono/metadata/tabledefs.h>
33 #include <mono/metadata/metadata-internals.h>
34 #include <mono/metadata/loader.h>
35 #include <mono/metadata/class-internals.h>
36 #include <mono/metadata/debug-helpers.h>
37 #include <mono/metadata/reflection.h>
38 #include <mono/metadata/profiler-private.h>
39 #include <mono/metadata/exception.h>
40 #include <mono/metadata/marshal.h>
41 #include <mono/metadata/lock-tracer.h>
42 #include <mono/metadata/verify-internals.h>
43 #include <mono/utils/mono-logger-internals.h>
44 #include <mono/utils/mono-dl.h>
45 #include <mono/utils/mono-membar.h>
46 #include <mono/utils/mono-counters.h>
47 #include <mono/utils/mono-error-internals.h>
48 #include <mono/utils/mono-tls.h>
49 #include <mono/utils/mono-path.h>
50
51 MonoDefaults mono_defaults;
52
53 /*
54 * This lock protects the hash tables inside MonoImage used by the metadata
55 * loading functions in class.c and loader.c.
56 *
57 * See domain-internals.h for locking policy in combination with the
58 * domain lock.
59 */
60 static MonoCoopMutex loader_mutex;
61 static mono_mutex_t global_loader_data_mutex;
62 static gboolean loader_lock_inited;
63
64 /* Statistics */
65 static gint32 inflated_signatures_size;
66 static gint32 memberref_sig_cache_size;
67 static gint32 methods_size;
68 static gint32 signatures_size;
69
70 /*
71 * This TLS variable holds how many times the current thread has acquired the loader
72 * lock.
73 */
74 MonoNativeTlsKey loader_lock_nest_id;
75
76 static void dllmap_cleanup (void);
77 static void cached_module_cleanup(void);
78
79 /* Class lazy loading functions */
80 GENERATE_GET_CLASS_WITH_CACHE (appdomain_unloaded_exception, "System", "AppDomainUnloadedException")
81
82 static void
global_loader_data_lock(void)83 global_loader_data_lock (void)
84 {
85 mono_locks_os_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
86 }
87
88 static void
global_loader_data_unlock(void)89 global_loader_data_unlock (void)
90 {
91 mono_locks_os_release (&global_loader_data_mutex, LoaderGlobalDataLock);
92 }
93
94 void
mono_loader_init()95 mono_loader_init ()
96 {
97 static gboolean inited;
98
99 if (!inited) {
100 mono_coop_mutex_init_recursive (&loader_mutex);
101 mono_os_mutex_init_recursive (&global_loader_data_mutex);
102 loader_lock_inited = TRUE;
103
104 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
105
106 mono_counters_init ();
107 mono_counters_register ("Inflated signatures size",
108 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
109 mono_counters_register ("Memberref signature cache size",
110 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
111 mono_counters_register ("MonoMethod size",
112 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
113 mono_counters_register ("MonoMethodSignature size",
114 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
115
116 inited = TRUE;
117 }
118 }
119
120 void
mono_loader_cleanup(void)121 mono_loader_cleanup (void)
122 {
123 dllmap_cleanup ();
124 cached_module_cleanup ();
125
126 mono_native_tls_free (loader_lock_nest_id);
127
128 mono_coop_mutex_destroy (&loader_mutex);
129 mono_os_mutex_destroy (&global_loader_data_mutex);
130 loader_lock_inited = FALSE;
131 }
132
133 /*
134 * find_cached_memberref_sig:
135 *
136 * Return a cached copy of the memberref signature identified by SIG_IDX.
137 * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
138 * A cache is needed since the type/signature parsing routines allocate everything
139 * from a mempool, so without a cache, multiple requests for the same signature would
140 * lead to unbounded memory growth. For normal methods/fields this is not a problem
141 * since the resulting methods/fields are cached, but inflated methods/fields cannot
142 * be cached.
143 * LOCKING: Acquires the loader lock.
144 */
145 static gpointer
find_cached_memberref_sig(MonoImage * image,guint32 sig_idx)146 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
147 {
148 gpointer res;
149
150 mono_image_lock (image);
151 res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
152 mono_image_unlock (image);
153
154 return res;
155 }
156
157 static gpointer
cache_memberref_sig(MonoImage * image,guint32 sig_idx,gpointer sig)158 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
159 {
160 gpointer prev_sig;
161
162 mono_image_lock (image);
163 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
164 if (prev_sig) {
165 /* Somebody got in before us */
166 sig = prev_sig;
167 }
168 else {
169 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
170 /* An approximation based on glib 2.18 */
171 mono_atomic_fetch_add_i32 (&memberref_sig_cache_size, sizeof (gpointer) * 4);
172 }
173 mono_image_unlock (image);
174
175 return sig;
176 }
177
178 static MonoClassField*
field_from_memberref(MonoImage * image,guint32 token,MonoClass ** retklass,MonoGenericContext * context,MonoError * error)179 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
180 MonoGenericContext *context, MonoError *error)
181 {
182 MonoClass *klass = NULL;
183 MonoClassField *field;
184 MonoTableInfo *tables = image->tables;
185 MonoType *sig_type;
186 guint32 cols[6];
187 guint32 nindex, class_index;
188 const char *fname;
189 const char *ptr;
190 guint32 idx = mono_metadata_token_index (token);
191
192 error_init (error);
193
194 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
195 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
196 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
197
198 fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
199
200 if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
201 mono_error_set_bad_image (error, image, "Bad field '%u' signature 0x%08x", class_index, token);
202 return NULL;
203 }
204
205 switch (class_index) {
206 case MONO_MEMBERREF_PARENT_TYPEDEF:
207 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
208 break;
209 case MONO_MEMBERREF_PARENT_TYPEREF:
210 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
211 break;
212 case MONO_MEMBERREF_PARENT_TYPESPEC:
213 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
214 break;
215 default:
216 mono_error_set_bad_image (error, image, "Bad field field '%u' signature 0x%08x", class_index, token);
217 }
218
219 if (!klass)
220 return NULL;
221
222 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
223 mono_metadata_decode_blob_size (ptr, &ptr);
224 /* we may want to check the signature here... */
225
226 if (*ptr++ != 0x6) {
227 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class_index, fname, token);
228 return NULL;
229 }
230
231 /* FIXME: This needs a cache, especially for generic instances, since
232 * we ask mono_metadata_parse_type_checked () to allocates everything from a mempool.
233 * FIXME part2, mono_metadata_parse_type_checked actually allows for a transient type instead.
234 * FIXME part3, transient types are not 100% transient, so we need to take care of that first.
235 */
236 sig_type = (MonoType *)find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
237 if (!sig_type) {
238 MonoError inner_error;
239 sig_type = mono_metadata_parse_type_checked (image, NULL, 0, FALSE, ptr, &ptr, &inner_error);
240 if (sig_type == NULL) {
241 mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x due to: %s", fname, token, mono_error_get_message (&inner_error));
242 mono_error_cleanup (&inner_error);
243 return NULL;
244 }
245 sig_type = (MonoType *)cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
246 }
247
248 mono_class_init (klass); /*FIXME is this really necessary?*/
249 if (retklass)
250 *retklass = klass;
251 field = mono_class_get_field_from_name_full (klass, fname, sig_type);
252
253 if (!field) {
254 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
255 }
256
257 return field;
258 }
259
260 /**
261 * mono_field_from_token:
262 * \deprecated use the \c _checked variant
263 * Notes: runtime code MUST not use this function
264 */
265 MonoClassField*
mono_field_from_token(MonoImage * image,guint32 token,MonoClass ** retklass,MonoGenericContext * context)266 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
267 {
268 MonoError error;
269 MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
270 g_assert (mono_error_ok (&error));
271 return res;
272 }
273
274 MonoClassField*
mono_field_from_token_checked(MonoImage * image,guint32 token,MonoClass ** retklass,MonoGenericContext * context,MonoError * error)275 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
276 {
277 MonoClass *k;
278 guint32 type;
279 MonoClassField *field;
280
281 error_init (error);
282
283 if (image_is_dynamic (image)) {
284 MonoClassField *result;
285 MonoClass *handle_class;
286
287 *retklass = NULL;
288 MonoError inner_error;
289 result = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, &inner_error);
290 mono_error_cleanup (&inner_error);
291 // This checks the memberref type as well
292 if (!result || handle_class != mono_defaults.fieldhandle_class) {
293 mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
294 return NULL;
295 }
296 *retklass = result->parent;
297 return result;
298 }
299
300 if ((field = (MonoClassField *)mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
301 *retklass = field->parent;
302 return field;
303 }
304
305 if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
306 field = field_from_memberref (image, token, retklass, context, error);
307 } else {
308 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
309 if (!type) {
310 mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
311 return NULL;
312 }
313 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
314 if (!k)
315 return NULL;
316
317 mono_class_init (k);
318 if (retklass)
319 *retklass = k;
320 if (mono_class_has_failure (k)) {
321 MonoError causedby_error;
322 error_init (&causedby_error);
323 mono_error_set_for_class_failure (&causedby_error, k);
324 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x, due to: %s", token, mono_error_get_message (&causedby_error));
325 mono_error_cleanup (&causedby_error);
326 } else {
327 field = mono_class_get_field (k, token);
328 if (!field) {
329 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
330 }
331 }
332 }
333
334 if (field && field->parent && !mono_class_is_ginst (field->parent) && !mono_class_is_gtd (field->parent)) {
335 mono_image_lock (image);
336 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
337 mono_image_unlock (image);
338 }
339
340 return field;
341 }
342
343 static gboolean
mono_metadata_signature_vararg_match(MonoMethodSignature * sig1,MonoMethodSignature * sig2)344 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
345 {
346 int i;
347
348 if (sig1->hasthis != sig2->hasthis ||
349 sig1->sentinelpos != sig2->sentinelpos)
350 return FALSE;
351
352 for (i = 0; i < sig1->sentinelpos; i++) {
353 MonoType *p1 = sig1->params[i];
354 MonoType *p2 = sig2->params[i];
355
356 /*if (p1->attrs != p2->attrs)
357 return FALSE;
358 */
359 if (!mono_metadata_type_equal (p1, p2))
360 return FALSE;
361 }
362
363 if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
364 return FALSE;
365 return TRUE;
366 }
367
368 static MonoMethod *
find_method_in_class(MonoClass * klass,const char * name,const char * qname,const char * fqname,MonoMethodSignature * sig,MonoClass * from_class,MonoError * error)369 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
370 MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
371 {
372 int i;
373
374 /* Search directly in the metadata to avoid calling setup_methods () */
375 error_init (error);
376
377 /* FIXME: !mono_class_is_ginst (from_class) condition causes test failures. */
378 if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !mono_class_is_ginst (from_class)) {
379 int first_idx = mono_class_get_first_method_idx (klass);
380 int mcount = mono_class_get_method_count (klass);
381 for (i = 0; i < mcount; ++i) {
382 guint32 cols [MONO_METHOD_SIZE];
383 MonoMethod *method;
384 const char *m_name;
385 MonoMethodSignature *other_sig;
386
387 mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, first_idx + i, cols, MONO_METHOD_SIZE);
388
389 m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
390
391 if (!((fqname && !strcmp (m_name, fqname)) ||
392 (qname && !strcmp (m_name, qname)) ||
393 (name && !strcmp (m_name, name))))
394 continue;
395
396 method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (first_idx + i + 1), klass, NULL, error);
397 if (!mono_error_ok (error)) //bail out if we hit a loader error
398 return NULL;
399 if (method) {
400 other_sig = mono_method_signature_checked (method, error);
401 if (!mono_error_ok (error)) //bail out if we hit a loader error
402 return NULL;
403 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
404 return method;
405 }
406 }
407 }
408
409 mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
410 /*
411 We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
412 See mono/tests/generic-type-load-exception.2.il
413 FIXME we should better report this error to the caller
414 */
415 if (!klass->methods || mono_class_has_failure (klass)) {
416 mono_error_set_type_load_class (error, klass, "Could not find method due to a type load error"); //FIXME get the error from the class
417
418 return NULL;
419 }
420 int mcount = mono_class_get_method_count (klass);
421 for (i = 0; i < mcount; ++i) {
422 MonoMethod *m = klass->methods [i];
423 MonoMethodSignature *msig;
424
425 /* We must cope with failing to load some of the types. */
426 if (!m)
427 continue;
428
429 if (!((fqname && !strcmp (m->name, fqname)) ||
430 (qname && !strcmp (m->name, qname)) ||
431 (name && !strcmp (m->name, name))))
432 continue;
433 msig = mono_method_signature_checked (m, error);
434 if (!mono_error_ok (error)) //bail out if we hit a loader error
435 return NULL;
436
437 if (!msig)
438 continue;
439
440 if (sig->call_convention == MONO_CALL_VARARG) {
441 if (mono_metadata_signature_vararg_match (sig, msig))
442 break;
443 } else {
444 if (mono_metadata_signature_equal (sig, msig))
445 break;
446 }
447 }
448
449 if (i < mcount)
450 return mono_class_get_method_by_index (from_class, i);
451 return NULL;
452 }
453
454 static MonoMethod *
find_method(MonoClass * in_class,MonoClass * ic,const char * name,MonoMethodSignature * sig,MonoClass * from_class,MonoError * error)455 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
456 {
457 int i;
458 char *qname, *fqname, *class_name;
459 gboolean is_interface;
460 MonoMethod *result = NULL;
461 MonoClass *initial_class = in_class;
462
463 error_init (error);
464 is_interface = MONO_CLASS_IS_INTERFACE (in_class);
465
466 if (ic) {
467 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
468
469 qname = g_strconcat (class_name, ".", name, NULL);
470 if (ic->name_space && ic->name_space [0])
471 fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
472 else
473 fqname = NULL;
474 } else
475 class_name = qname = fqname = NULL;
476
477 while (in_class) {
478 g_assert (from_class);
479 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
480 if (result || !mono_error_ok (error))
481 goto out;
482
483 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
484 break;
485
486 /*
487 * This happens when we fail to lazily load the interfaces of one of the types.
488 * On such case we can't just bail out since user code depends on us trying harder.
489 */
490 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
491 in_class = in_class->parent;
492 from_class = from_class->parent;
493 continue;
494 }
495
496 for (i = 0; i < in_class->interface_offsets_count; i++) {
497 MonoClass *in_ic = in_class->interfaces_packed [i];
498 MonoClass *from_ic = from_class->interfaces_packed [i];
499 char *ic_qname, *ic_fqname, *ic_class_name;
500
501 ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
502 ic_qname = g_strconcat (ic_class_name, ".", name, NULL);
503 if (in_ic->name_space && in_ic->name_space [0])
504 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
505 else
506 ic_fqname = NULL;
507
508 result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
509 g_free (ic_class_name);
510 g_free (ic_fqname);
511 g_free (ic_qname);
512 if (result || !mono_error_ok (error))
513 goto out;
514 }
515
516 in_class = in_class->parent;
517 from_class = from_class->parent;
518 }
519 g_assert (!in_class == !from_class);
520
521 if (is_interface)
522 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
523
524 //we did not find the method
525 if (!result && mono_error_ok (error)) {
526 char *desc = mono_signature_get_managed_fmt_string (sig);
527 mono_error_set_method_load (error, initial_class, g_strdup (name), desc, "");
528 }
529
530 out:
531 g_free (class_name);
532 g_free (fqname);
533 g_free (qname);
534 return result;
535 }
536
537 static MonoMethodSignature*
inflate_generic_signature_checked(MonoImage * image,MonoMethodSignature * sig,MonoGenericContext * context,MonoError * error)538 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
539 {
540 MonoMethodSignature *res;
541 gboolean is_open;
542 int i;
543
544 error_init (error);
545 if (!context)
546 return sig;
547
548 res = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
549 res->param_count = sig->param_count;
550 res->sentinelpos = -1;
551 res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
552 if (!mono_error_ok (error))
553 goto fail;
554 is_open = mono_class_is_open_constructed_type (res->ret);
555 for (i = 0; i < sig->param_count; ++i) {
556 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
557 if (!mono_error_ok (error))
558 goto fail;
559
560 if (!is_open)
561 is_open = mono_class_is_open_constructed_type (res->params [i]);
562 }
563 res->hasthis = sig->hasthis;
564 res->explicit_this = sig->explicit_this;
565 res->call_convention = sig->call_convention;
566 res->pinvoke = sig->pinvoke;
567 res->generic_param_count = sig->generic_param_count;
568 res->sentinelpos = sig->sentinelpos;
569 res->has_type_parameters = is_open;
570 res->is_inflated = 1;
571 return res;
572
573 fail:
574 if (res->ret)
575 mono_metadata_free_type (res->ret);
576 for (i = 0; i < sig->param_count; ++i) {
577 if (res->params [i])
578 mono_metadata_free_type (res->params [i]);
579 }
580 g_free (res);
581 return NULL;
582 }
583
584 /**
585 * mono_inflate_generic_signature:
586 *
587 * Inflate \p sig with \p context, and return a canonical copy. On error, set \p error, and return NULL.
588 */
589 MonoMethodSignature*
mono_inflate_generic_signature(MonoMethodSignature * sig,MonoGenericContext * context,MonoError * error)590 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
591 {
592 MonoMethodSignature *res, *cached;
593
594 res = inflate_generic_signature_checked (NULL, sig, context, error);
595 if (!mono_error_ok (error))
596 return NULL;
597 cached = mono_metadata_get_inflated_signature (res, context);
598 if (cached != res)
599 mono_metadata_free_inflated_signature (res);
600 return cached;
601 }
602
603 static MonoMethodHeader*
inflate_generic_header(MonoMethodHeader * header,MonoGenericContext * context,MonoError * error)604 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context, MonoError *error)
605 {
606 size_t locals_size = sizeof (gpointer) * header->num_locals;
607 size_t clauses_size = header->num_clauses * sizeof (MonoExceptionClause);
608 size_t header_size = MONO_SIZEOF_METHOD_HEADER + locals_size + clauses_size;
609 MonoMethodHeader *res = (MonoMethodHeader *)g_malloc0 (header_size);
610 res->num_locals = header->num_locals;
611 res->clauses = (MonoExceptionClause *) &res->locals [res->num_locals] ;
612 memcpy (res->clauses, header->clauses, clauses_size);
613
614 res->code = header->code;
615 res->code_size = header->code_size;
616 res->max_stack = header->max_stack;
617 res->num_clauses = header->num_clauses;
618 res->init_locals = header->init_locals;
619
620 res->is_transient = TRUE;
621
622 error_init (error);
623
624 for (int i = 0; i < header->num_locals; ++i) {
625 res->locals [i] = mono_class_inflate_generic_type_checked (header->locals [i], context, error);
626 goto_if_nok (error, fail);
627 }
628 if (res->num_clauses) {
629 for (int i = 0; i < header->num_clauses; ++i) {
630 MonoExceptionClause *clause = &res->clauses [i];
631 if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
632 continue;
633 clause->data.catch_class = mono_class_inflate_generic_class_checked (clause->data.catch_class, context, error);
634 goto_if_nok (error, fail);
635 }
636 }
637 return res;
638 fail:
639 g_free (res);
640 return NULL;
641 }
642
643 /**
644 * mono_method_get_signature_full:
645 * \p token is the method ref/def/spec token used in a \c call IL instruction.
646 * \deprecated use the \c _checked variant
647 * Notes: runtime code MUST not use this function
648 */
649 MonoMethodSignature*
mono_method_get_signature_full(MonoMethod * method,MonoImage * image,guint32 token,MonoGenericContext * context)650 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
651 {
652 MonoError error;
653 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
654 mono_error_cleanup (&error);
655 return res;
656 }
657
658 MonoMethodSignature*
mono_method_get_signature_checked(MonoMethod * method,MonoImage * image,guint32 token,MonoGenericContext * context,MonoError * error)659 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
660 {
661 int table = mono_metadata_token_table (token);
662 int idx = mono_metadata_token_index (token);
663 int sig_idx;
664 guint32 cols [MONO_MEMBERREF_SIZE];
665 MonoMethodSignature *sig;
666 const char *ptr;
667
668 error_init (error);
669
670 /* !table is for wrappers: we should really assign their own token to them */
671 if (!table || table == MONO_TABLE_METHOD)
672 return mono_method_signature_checked (method, error);
673
674 if (table == MONO_TABLE_METHODSPEC) {
675 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
676 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated) {
677 mono_error_set_bad_image (error, image, "Method is a pinvoke or open generic");
678 return NULL;
679 }
680
681 return mono_method_signature_checked (method, error);
682 }
683
684 if (mono_class_is_ginst (method->klass))
685 return mono_method_signature_checked (method, error);
686
687 if (image_is_dynamic (image)) {
688 sig = mono_reflection_lookup_signature (image, method, token, error);
689 if (!sig)
690 return NULL;
691 } else {
692 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
693 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
694
695 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
696 if (!sig) {
697 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
698 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
699 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
700
701 //FIXME include the verification error
702 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
703 return NULL;
704 }
705
706 ptr = mono_metadata_blob_heap (image, sig_idx);
707 mono_metadata_decode_blob_size (ptr, &ptr);
708
709 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
710 if (!sig)
711 return NULL;
712
713 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
714 }
715 /* FIXME: we probably should verify signature compat in the dynamic case too*/
716 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
717 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
718 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
719
720 mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
721 return NULL;
722 }
723 }
724
725 if (context) {
726 MonoMethodSignature *cached;
727
728 /* This signature is not owned by a MonoMethod, so need to cache */
729 sig = inflate_generic_signature_checked (image, sig, context, error);
730 if (!mono_error_ok (error))
731 return NULL;
732
733 cached = mono_metadata_get_inflated_signature (sig, context);
734 if (cached != sig)
735 mono_metadata_free_inflated_signature (sig);
736 else
737 mono_atomic_fetch_add_i32 (&inflated_signatures_size, mono_metadata_signature_size (cached));
738 sig = cached;
739 }
740
741 g_assert (mono_error_ok (error));
742 return sig;
743 }
744
745 /**
746 * mono_method_get_signature:
747 * \p token is the method_ref/def/spec token used in a call IL instruction.
748 * \deprecated use the \c _checked variant
749 * Notes: runtime code MUST not use this function
750 */
751 MonoMethodSignature*
mono_method_get_signature(MonoMethod * method,MonoImage * image,guint32 token)752 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
753 {
754 MonoError error;
755 MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
756 mono_error_cleanup (&error);
757 return res;
758 }
759
760 /* this is only for the typespec array methods */
761 MonoMethod*
mono_method_search_in_array_class(MonoClass * klass,const char * name,MonoMethodSignature * sig)762 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
763 {
764 int i;
765
766 mono_class_setup_methods (klass);
767 g_assert (!mono_class_has_failure (klass)); /*FIXME this should not fail, right?*/
768 int mcount = mono_class_get_method_count (klass);
769 for (i = 0; i < mcount; ++i) {
770 MonoMethod *method = klass->methods [i];
771 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
772 return method;
773 }
774 return NULL;
775 }
776
777 static MonoMethod *
method_from_memberref(MonoImage * image,guint32 idx,MonoGenericContext * typespec_context,gboolean * used_context,MonoError * error)778 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
779 gboolean *used_context, MonoError *error)
780 {
781 MonoClass *klass = NULL;
782 MonoMethod *method = NULL;
783 MonoTableInfo *tables = image->tables;
784 guint32 cols[6];
785 guint32 nindex, class_index, sig_idx;
786 const char *mname;
787 MonoMethodSignature *sig;
788 const char *ptr;
789
790 error_init (error);
791
792 mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
793 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
794 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
795 /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
796 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
797
798 mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
799
800 /*
801 * Whether we actually used the `typespec_context' or not.
802 * This is used to tell our caller whether or not it's safe to insert the returned
803 * method into a cache.
804 */
805 if (used_context)
806 *used_context = class_index == MONO_MEMBERREF_PARENT_TYPESPEC;
807
808 switch (class_index) {
809 case MONO_MEMBERREF_PARENT_TYPEREF:
810 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
811 if (!klass)
812 goto fail;
813 break;
814 case MONO_MEMBERREF_PARENT_TYPESPEC:
815 /*
816 * Parse the TYPESPEC in the parent's context.
817 */
818 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
819 if (!klass)
820 goto fail;
821 break;
822 case MONO_MEMBERREF_PARENT_TYPEDEF:
823 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
824 if (!klass)
825 goto fail;
826 break;
827 case MONO_MEMBERREF_PARENT_METHODDEF: {
828 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
829 if (!method)
830 goto fail;
831 return method;
832 }
833 default:
834 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class_index, nindex);
835 goto fail;
836 }
837
838 g_assert (klass);
839 mono_class_init (klass);
840
841 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
842
843 if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
844 mono_error_set_method_load (error, klass, g_strdup (mname), NULL, "Verifier rejected method signature");
845 goto fail;
846 }
847
848 ptr = mono_metadata_blob_heap (image, sig_idx);
849 mono_metadata_decode_blob_size (ptr, &ptr);
850
851 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
852 if (!sig) {
853 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
854 if (sig == NULL)
855 goto fail;
856
857 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
858 }
859
860 switch (class_index) {
861 case MONO_MEMBERREF_PARENT_TYPEREF:
862 case MONO_MEMBERREF_PARENT_TYPEDEF:
863 method = find_method (klass, NULL, mname, sig, klass, error);
864 break;
865
866 case MONO_MEMBERREF_PARENT_TYPESPEC: {
867 MonoType *type;
868
869 type = &klass->byval_arg;
870
871 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
872 MonoClass *in_class = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->container_class : klass;
873 method = find_method (in_class, NULL, mname, sig, klass, error);
874 break;
875 }
876
877 /* we're an array and we created these methods already in klass in mono_class_init () */
878 method = mono_method_search_in_array_class (klass, mname, sig);
879 break;
880 }
881 default:
882 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class_index, nindex);
883 goto fail;
884 }
885
886 if (!method && mono_error_ok (error)) {
887
888 char *desc = mono_signature_get_managed_fmt_string (sig);
889
890 mono_error_set_method_load (error, klass, g_strdup (mname), desc, "Failed to load due to unknown reasons");
891 }
892
893 return method;
894
895 fail:
896 g_assert (!mono_error_ok (error));
897 return NULL;
898 }
899
900 static MonoMethod *
method_from_methodspec(MonoImage * image,MonoGenericContext * context,guint32 idx,MonoError * error)901 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
902 {
903 MonoMethod *method;
904 MonoClass *klass;
905 MonoTableInfo *tables = image->tables;
906 MonoGenericContext new_context;
907 MonoGenericInst *inst;
908 const char *ptr;
909 guint32 cols [MONO_METHODSPEC_SIZE];
910 guint32 token, nindex, param_count;
911
912 error_init (error);
913
914 mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
915 token = cols [MONO_METHODSPEC_METHOD];
916 nindex = token >> MONO_METHODDEFORREF_BITS;
917
918 if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
919 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
920 return NULL;
921 }
922
923 ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
924
925 mono_metadata_decode_value (ptr, &ptr);
926 ptr++;
927 param_count = mono_metadata_decode_value (ptr, &ptr);
928
929 inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr, error);
930 if (!inst)
931 return NULL;
932
933 if (context && inst->is_open) {
934 inst = mono_metadata_inflate_generic_inst (inst, context, error);
935 if (!mono_error_ok (error))
936 return NULL;
937 }
938
939 if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
940 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
941 if (!method)
942 return NULL;
943 } else {
944 method = method_from_memberref (image, nindex, context, NULL, error);
945 }
946
947 if (!method)
948 return NULL;
949
950 klass = method->klass;
951
952 if (mono_class_is_ginst (klass)) {
953 g_assert (method->is_inflated);
954 method = ((MonoMethodInflated *) method)->declaring;
955 }
956
957 new_context.class_inst = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->context.class_inst : NULL;
958 new_context.method_inst = inst;
959
960 method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
961 return method;
962 }
963
964 struct _MonoDllMap {
965 char *dll;
966 char *target;
967 char *func;
968 char *target_func;
969 MonoDllMap *next;
970 };
971
972 static MonoDllMap *global_dll_map;
973
974 static int
mono_dllmap_lookup_list(MonoDllMap * dll_map,const char * dll,const char * func,const char ** rdll,const char ** rfunc)975 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
976 int found = 0;
977
978 *rdll = dll;
979
980 if (!dll_map)
981 return 0;
982
983 global_loader_data_lock ();
984
985 /*
986 * we use the first entry we find that matches, since entries from
987 * the config file are prepended to the list and we document that the
988 * later entries win.
989 */
990 for (; dll_map; dll_map = dll_map->next) {
991 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
992 if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
993 continue;
994 } else if (strcmp (dll_map->dll, dll)) {
995 continue;
996 }
997 if (!found && dll_map->target) {
998 *rdll = dll_map->target;
999 found = 1;
1000 /* we don't quit here, because we could find a full
1001 * entry that matches also function and that has priority.
1002 */
1003 }
1004 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1005 *rdll = dll_map->target;
1006 *rfunc = dll_map->target_func;
1007 break;
1008 }
1009 }
1010
1011 global_loader_data_unlock ();
1012 return found;
1013 }
1014
1015 static int
mono_dllmap_lookup(MonoImage * assembly,const char * dll,const char * func,const char ** rdll,const char ** rfunc)1016 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1017 {
1018 int res;
1019 if (assembly && assembly->dll_map) {
1020 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1021 if (res)
1022 return res;
1023 }
1024 return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1025 }
1026
1027 /**
1028 * mono_dllmap_insert:
1029 * \param assembly if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1030 * \param dll The name of the external library, as it would be found in the \c DllImport declaration. If prefixed with <code>i:</code> the matching of the library name is done without case sensitivity
1031 * \param func if not null, the mapping will only applied to the named function (the value of <code>EntryPoint</code>)
1032 * \param tdll The name of the library to map the specified \p dll if it matches.
1033 * \param tfunc The name of the function that replaces the invocation. If NULL, it is replaced with a copy of \p func.
1034 *
1035 * LOCKING: Acquires the loader lock.
1036 *
1037 * This function is used to programatically add \c DllImport remapping in either
1038 * a specific assembly, or as a global remapping. This is done by remapping
1039 * references in a \c DllImport attribute from the \p dll library name into the \p tdll
1040 * name. If the \p dll name contains the prefix <code>i:</code>, the comparison of the
1041 * library name is done without case sensitivity.
1042 *
1043 * If you pass \p func, this is the name of the \c EntryPoint in a \c DllImport if specified
1044 * or the name of the function as determined by \c DllImport. If you pass \p func, you
1045 * must also pass \p tfunc which is the name of the target function to invoke on a match.
1046 *
1047 * Example:
1048 *
1049 * <code>mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);</code>
1050 *
1051 * The above will remap \c DllImport statements for \c libdemo.dll and \c LIBDEMO.DLL to
1052 * the contents of \c relocated_demo_path for all assemblies in the Mono process.
1053 *
1054 * NOTE: This can be called before the runtime is initialized, for example from
1055 * \c mono_config_parse.
1056 */
1057 void
mono_dllmap_insert(MonoImage * assembly,const char * dll,const char * func,const char * tdll,const char * tfunc)1058 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1059 {
1060 MonoDllMap *entry;
1061
1062 mono_loader_init ();
1063
1064 if (!assembly) {
1065 entry = (MonoDllMap *)g_malloc0 (sizeof (MonoDllMap));
1066 entry->dll = dll? g_strdup (dll): NULL;
1067 entry->target = tdll? g_strdup (tdll): NULL;
1068 entry->func = func? g_strdup (func): NULL;
1069 entry->target_func = tfunc? g_strdup (tfunc): (func? g_strdup (func): NULL);
1070
1071 global_loader_data_lock ();
1072 entry->next = global_dll_map;
1073 global_dll_map = entry;
1074 global_loader_data_unlock ();
1075 } else {
1076 entry = (MonoDllMap *)mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1077 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1078 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1079 entry->func = func? mono_image_strdup (assembly, func): NULL;
1080 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): (func? mono_image_strdup (assembly, func): NULL);
1081
1082 mono_image_lock (assembly);
1083 entry->next = assembly->dll_map;
1084 assembly->dll_map = entry;
1085 mono_image_unlock (assembly);
1086 }
1087 }
1088
1089 static void
free_dllmap(MonoDllMap * map)1090 free_dllmap (MonoDllMap *map)
1091 {
1092 while (map) {
1093 MonoDllMap *next = map->next;
1094
1095 g_free (map->dll);
1096 g_free (map->target);
1097 g_free (map->func);
1098 g_free (map->target_func);
1099 g_free (map);
1100 map = next;
1101 }
1102 }
1103
1104 static void
dllmap_cleanup(void)1105 dllmap_cleanup (void)
1106 {
1107 free_dllmap (global_dll_map);
1108 global_dll_map = NULL;
1109 }
1110
1111 static GHashTable *global_module_map;
1112
1113 static MonoDl*
cached_module_load(const char * name,int flags,char ** err)1114 cached_module_load (const char *name, int flags, char **err)
1115 {
1116 MonoDl *res;
1117
1118 if (err)
1119 *err = NULL;
1120 global_loader_data_lock ();
1121 if (!global_module_map)
1122 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1123 res = (MonoDl *)g_hash_table_lookup (global_module_map, name);
1124 if (res) {
1125 global_loader_data_unlock ();
1126 return res;
1127 }
1128 res = mono_dl_open (name, flags, err);
1129 if (res)
1130 g_hash_table_insert (global_module_map, g_strdup (name), res);
1131 global_loader_data_unlock ();
1132 return res;
1133 }
1134
1135 void
mono_loader_register_module(const char * name,MonoDl * module)1136 mono_loader_register_module (const char *name, MonoDl *module)
1137 {
1138 if (!global_module_map)
1139 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1140 g_hash_table_insert (global_module_map, g_strdup (name), module);
1141 }
1142
1143 static void
remove_cached_module(gpointer key,gpointer value,gpointer user_data)1144 remove_cached_module(gpointer key, gpointer value, gpointer user_data)
1145 {
1146 mono_dl_close((MonoDl*)value);
1147 }
1148
1149 static void
cached_module_cleanup(void)1150 cached_module_cleanup(void)
1151 {
1152 if (global_module_map != NULL) {
1153 g_hash_table_foreach(global_module_map, remove_cached_module, NULL);
1154
1155 g_hash_table_destroy(global_module_map);
1156 global_module_map = NULL;
1157 }
1158 }
1159
1160 static MonoDl *internal_module;
1161
1162 static gboolean
is_absolute_path(const char * path)1163 is_absolute_path (const char *path)
1164 {
1165 #ifdef HOST_DARWIN
1166 if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1167 !strncmp (path, "@rpath/", 7))
1168 return TRUE;
1169 #endif
1170 return g_path_is_absolute (path);
1171 }
1172
1173 /**
1174 * mono_lookup_pinvoke_call:
1175 */
1176 gpointer
mono_lookup_pinvoke_call(MonoMethod * method,const char ** exc_class,const char ** exc_arg)1177 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1178 {
1179 MonoImage *image = method->klass->image;
1180 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1181 MonoTableInfo *tables = image->tables;
1182 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1183 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1184 guint32 im_cols [MONO_IMPLMAP_SIZE];
1185 guint32 scope_token;
1186 const char *import = NULL;
1187 const char *orig_scope;
1188 const char *new_scope;
1189 char *error_msg;
1190 char *full_name, *file_name, *found_name = NULL;
1191 int i,j;
1192 MonoDl *module = NULL;
1193 gboolean cached = FALSE;
1194 gpointer addr = NULL;
1195
1196 g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1197
1198 if (exc_class) {
1199 *exc_class = NULL;
1200 *exc_arg = NULL;
1201 }
1202
1203 if (piinfo->addr)
1204 return piinfo->addr;
1205
1206 if (image_is_dynamic (method->klass->image)) {
1207 MonoReflectionMethodAux *method_aux =
1208 (MonoReflectionMethodAux *)g_hash_table_lookup (
1209 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1210 if (!method_aux)
1211 return NULL;
1212
1213 import = method_aux->dllentry;
1214 orig_scope = method_aux->dll;
1215 }
1216 else {
1217 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1218 return NULL;
1219
1220 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1221
1222 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1223 return NULL;
1224
1225 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1226 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1227 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1228 orig_scope = mono_metadata_string_heap (image, scope_token);
1229 }
1230
1231 mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1232
1233 if (!module) {
1234 mono_image_lock (image);
1235 if (!image->pinvoke_scopes) {
1236 image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1237 image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1238 }
1239 module = (MonoDl *)g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1240 found_name = (char *)g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1241 mono_image_unlock (image);
1242 if (module)
1243 cached = TRUE;
1244 if (found_name)
1245 found_name = g_strdup (found_name);
1246 }
1247
1248 if (!module) {
1249 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1250 "DllImport attempting to load: '%s'.", new_scope);
1251
1252 /* we allow a special name to dlopen from the running process namespace */
1253 if (strcmp (new_scope, "__Internal") == 0){
1254 if (internal_module == NULL)
1255 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1256 module = internal_module;
1257 }
1258 }
1259
1260 /*
1261 * Try loading the module using a variety of names
1262 */
1263 for (i = 0; i < 5; ++i) {
1264 char *base_name = NULL, *dir_name = NULL;
1265 gboolean is_absolute = is_absolute_path (new_scope);
1266
1267 switch (i) {
1268 case 0:
1269 /* Try the original name */
1270 file_name = g_strdup (new_scope);
1271 break;
1272 case 1:
1273 /* Try trimming the .dll extension */
1274 if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1275 file_name = g_strdup (new_scope);
1276 file_name [strlen (new_scope) - 4] = '\0';
1277 }
1278 else
1279 continue;
1280 break;
1281 case 2:
1282 if (is_absolute) {
1283 dir_name = g_path_get_dirname (new_scope);
1284 base_name = g_path_get_basename (new_scope);
1285 if (strstr (base_name, "lib") != base_name) {
1286 char *tmp = g_strdup_printf ("lib%s", base_name);
1287 g_free (base_name);
1288 base_name = tmp;
1289 file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1290 break;
1291 }
1292 } else if (strstr (new_scope, "lib") != new_scope) {
1293 file_name = g_strdup_printf ("lib%s", new_scope);
1294 break;
1295 }
1296 continue;
1297 case 3:
1298 if (!is_absolute && mono_dl_get_system_dir ()) {
1299 dir_name = (char*)mono_dl_get_system_dir ();
1300 file_name = g_path_get_basename (new_scope);
1301 base_name = NULL;
1302 } else
1303 continue;
1304 break;
1305 default:
1306 #ifndef TARGET_WIN32
1307 if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1308 !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1309 !g_ascii_strcasecmp ("user32", new_scope) ||
1310 !g_ascii_strcasecmp ("kernel", new_scope)) {
1311 file_name = g_strdup ("libMonoSupportW.so");
1312 } else
1313 #endif
1314 continue;
1315 #ifndef TARGET_WIN32
1316 break;
1317 #endif
1318 }
1319
1320 if (is_absolute) {
1321 if (!dir_name)
1322 dir_name = g_path_get_dirname (file_name);
1323 if (!base_name)
1324 base_name = g_path_get_basename (file_name);
1325 }
1326
1327 if (!module && is_absolute) {
1328 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1329 if (!module) {
1330 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1331 "DllImport error loading library '%s': '%s'.",
1332 file_name, error_msg);
1333 g_free (error_msg);
1334 } else {
1335 found_name = g_strdup (file_name);
1336 }
1337 }
1338
1339 if (!module && !is_absolute) {
1340 void *iter;
1341 char *mdirname;
1342
1343 for (j = 0; j < 3; ++j) {
1344 iter = NULL;
1345 mdirname = NULL;
1346 switch (j) {
1347 case 0:
1348 mdirname = g_path_get_dirname (image->name);
1349 break;
1350 case 1: /* @executable_path@/../lib */
1351 {
1352 char buf [4096];
1353 int binl;
1354 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1355 if (binl != -1) {
1356 char *base, *newbase;
1357 char *resolvedname;
1358 buf [binl] = 0;
1359 resolvedname = mono_path_resolve_symlinks (buf);
1360
1361 base = g_path_get_dirname (resolvedname);
1362 newbase = g_path_get_dirname(base);
1363 mdirname = g_strdup_printf ("%s/lib", newbase);
1364
1365 g_free (resolvedname);
1366 g_free (base);
1367 g_free (newbase);
1368 }
1369 break;
1370 }
1371 #ifdef __MACH__
1372 case 2: /* @executable_path@/../Libraries */
1373 {
1374 char buf [4096];
1375 int binl;
1376 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1377 if (binl != -1) {
1378 char *base, *newbase;
1379 char *resolvedname;
1380 buf [binl] = 0;
1381 resolvedname = mono_path_resolve_symlinks (buf);
1382
1383 base = g_path_get_dirname (resolvedname);
1384 newbase = g_path_get_dirname(base);
1385 mdirname = g_strdup_printf ("%s/Libraries", newbase);
1386
1387 g_free (resolvedname);
1388 g_free (base);
1389 g_free (newbase);
1390 }
1391 break;
1392 }
1393 #endif
1394 }
1395
1396 if (!mdirname)
1397 continue;
1398
1399 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1400 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1401 if (!module) {
1402 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1403 "DllImport error loading library '%s': '%s'.",
1404 full_name, error_msg);
1405 g_free (error_msg);
1406 } else {
1407 found_name = g_strdup (full_name);
1408 }
1409 g_free (full_name);
1410 if (module)
1411 break;
1412
1413 }
1414 g_free (mdirname);
1415 if (module)
1416 break;
1417 }
1418
1419 }
1420
1421 if (!module) {
1422 void *iter = NULL;
1423 char *file_or_base = is_absolute ? base_name : file_name;
1424 while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1425 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1426 if (!module) {
1427 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1428 "DllImport error loading library '%s': '%s'.",
1429 full_name, error_msg);
1430 g_free (error_msg);
1431 } else {
1432 found_name = g_strdup (full_name);
1433 }
1434 g_free (full_name);
1435 if (module)
1436 break;
1437 }
1438 }
1439
1440 if (!module) {
1441 module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1442 if (!module) {
1443 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1444 "DllImport error loading library '%s': '%s'.",
1445 file_name, error_msg);
1446 } else {
1447 found_name = g_strdup (file_name);
1448 }
1449 }
1450
1451 g_free (file_name);
1452 if (is_absolute) {
1453 g_free (base_name);
1454 g_free (dir_name);
1455 }
1456
1457 if (module)
1458 break;
1459 }
1460
1461 if (!module) {
1462 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1463 "DllImport unable to load library '%s'.",
1464 error_msg);
1465 g_free (error_msg);
1466
1467 if (exc_class) {
1468 *exc_class = "DllNotFoundException";
1469 *exc_arg = new_scope;
1470 }
1471 return NULL;
1472 }
1473
1474 if (!cached) {
1475 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1476 "DllImport loaded library '%s'.", found_name);
1477 mono_image_lock (image);
1478 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1479 g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1480 g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1481 }
1482 mono_image_unlock (image);
1483 }
1484
1485 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1486 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1487 g_free (found_name);
1488
1489 #ifdef TARGET_WIN32
1490 if (import && import [0] == '#' && isdigit (import [1])) {
1491 char *end;
1492 long id;
1493
1494 id = strtol (import + 1, &end, 10);
1495 if (id > 0 && *end == '\0')
1496 import++;
1497 }
1498 #endif
1499 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1500 "Searching for '%s'.", import);
1501
1502 if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1503 error_msg = mono_dl_symbol (module, import, &addr);
1504 } else {
1505 char *mangled_name = NULL, *mangled_name2 = NULL;
1506 int mangle_charset;
1507 int mangle_stdcall;
1508 int mangle_param_count;
1509 #ifdef TARGET_WIN32
1510 int param_count;
1511 #endif
1512
1513 /*
1514 * Search using a variety of mangled names
1515 */
1516 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1517 for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1518 gboolean need_param_count = FALSE;
1519 #ifdef TARGET_WIN32
1520 if (mangle_stdcall > 0)
1521 need_param_count = TRUE;
1522 #endif
1523 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1524
1525 if (addr)
1526 continue;
1527
1528 mangled_name = (char*)import;
1529 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1530 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1531 /* Try the mangled name first */
1532 if (mangle_charset == 0)
1533 mangled_name = g_strconcat (import, "W", NULL);
1534 break;
1535 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1536 #ifdef TARGET_WIN32
1537 if (mangle_charset == 0)
1538 mangled_name = g_strconcat (import, "W", NULL);
1539 #else
1540 /* Try the mangled name last */
1541 if (mangle_charset == 1)
1542 mangled_name = g_strconcat (import, "A", NULL);
1543 #endif
1544 break;
1545 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1546 default:
1547 /* Try the mangled name last */
1548 if (mangle_charset == 1)
1549 mangled_name = g_strconcat (import, "A", NULL);
1550 break;
1551 }
1552
1553 #ifdef TARGET_WIN32
1554 if (mangle_param_count == 0)
1555 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1556 else
1557 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1558 param_count = mangle_param_count;
1559
1560 /* Try the stdcall mangled name */
1561 /*
1562 * gcc under windows creates mangled names without the underscore, but MS.NET
1563 * doesn't support it, so we doesn't support it either.
1564 */
1565 if (mangle_stdcall == 1)
1566 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1567 else
1568 mangled_name2 = mangled_name;
1569 #else
1570 mangled_name2 = mangled_name;
1571 #endif
1572
1573 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1574 "Probing '%s'.", mangled_name2);
1575
1576 error_msg = mono_dl_symbol (module, mangled_name2, &addr);
1577
1578 if (addr)
1579 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1580 "Found as '%s'.", mangled_name2);
1581 else
1582 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1583 "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1584
1585 g_free (error_msg);
1586 error_msg = NULL;
1587
1588 if (mangled_name != mangled_name2)
1589 g_free (mangled_name2);
1590 if (mangled_name != import)
1591 g_free (mangled_name);
1592 }
1593 }
1594 }
1595 }
1596
1597 if (!addr) {
1598 g_free (error_msg);
1599 if (exc_class) {
1600 *exc_class = "EntryPointNotFoundException";
1601 *exc_arg = import;
1602 }
1603 return NULL;
1604 }
1605 piinfo->addr = addr;
1606 return addr;
1607 }
1608
1609 /*
1610 * LOCKING: assumes the loader lock to be taken.
1611 */
1612 static MonoMethod *
mono_get_method_from_token(MonoImage * image,guint32 token,MonoClass * klass,MonoGenericContext * context,gboolean * used_context,MonoError * error)1613 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1614 MonoGenericContext *context, gboolean *used_context, MonoError *error)
1615 {
1616 MonoMethod *result;
1617 int table = mono_metadata_token_table (token);
1618 int idx = mono_metadata_token_index (token);
1619 MonoTableInfo *tables = image->tables;
1620 MonoGenericContainer *generic_container = NULL, *container = NULL;
1621 const char *sig = NULL;
1622 guint32 cols [MONO_TYPEDEF_SIZE];
1623
1624 error_init (error);
1625
1626 if (image_is_dynamic (image)) {
1627 MonoClass *handle_class;
1628
1629 result = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context, error);
1630 mono_error_assert_ok (error);
1631
1632 // This checks the memberref type as well
1633 if (result && handle_class != mono_defaults.methodhandle_class) {
1634 mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1635 return NULL;
1636 }
1637 return result;
1638 }
1639
1640 if (table != MONO_TABLE_METHOD) {
1641 if (table == MONO_TABLE_METHODSPEC) {
1642 if (used_context) *used_context = TRUE;
1643 return method_from_methodspec (image, context, idx, error);
1644 }
1645 if (table != MONO_TABLE_MEMBERREF) {
1646 mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1647 return NULL;
1648 }
1649 return method_from_memberref (image, idx, context, used_context, error);
1650 }
1651
1652 if (used_context) *used_context = FALSE;
1653
1654 if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1655 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1656 return NULL;
1657 }
1658
1659 if (!klass) {
1660 guint32 type = mono_metadata_typedef_from_method (image, token);
1661 if (!type) {
1662 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1663 return NULL;
1664 }
1665 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1666 if (klass == NULL)
1667 return NULL;
1668 }
1669
1670 mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1671
1672 if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1673 (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1674 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1675 } else {
1676 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1677 mono_atomic_fetch_add_i32 (&methods_size, sizeof (MonoMethod));
1678 }
1679
1680 mono_atomic_inc_i32 (&mono_stats.method_count);
1681
1682 result->slot = -1;
1683 result->klass = klass;
1684 result->flags = cols [2];
1685 result->iflags = cols [1];
1686 result->token = token;
1687 result->name = mono_metadata_string_heap (image, cols [3]);
1688
1689 if (!sig) /* already taken from the methodref */
1690 sig = mono_metadata_blob_heap (image, cols [4]);
1691 /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1692
1693 container = mono_class_try_get_generic_container (klass);
1694
1695 /*
1696 * load_generic_params does a binary search so only call it if the method
1697 * is generic.
1698 */
1699 if (*sig & 0x10) {
1700 generic_container = mono_metadata_load_generic_params (image, token, container);
1701 }
1702 if (generic_container) {
1703 result->is_generic = TRUE;
1704 generic_container->owner.method = result;
1705 generic_container->is_anonymous = FALSE; // Method is now known, container is no longer anonymous
1706 /*FIXME put this before the image alloc*/
1707 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1708 return NULL;
1709
1710 container = generic_container;
1711 }
1712
1713 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1714 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1715 result->string_ctor = 1;
1716 } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1717 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1718
1719 #ifdef TARGET_WIN32
1720 /* IJW is P/Invoke with a predefined function pointer. */
1721 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1722 piinfo->addr = mono_image_rva_map (image, cols [0]);
1723 g_assert (piinfo->addr);
1724 }
1725 #endif
1726 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1727 /* Native methods can have no map. */
1728 if (piinfo->implmap_idx)
1729 piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1730 }
1731
1732 if (generic_container)
1733 mono_method_set_generic_container (result, generic_container);
1734
1735 return result;
1736 }
1737
1738 /**
1739 * mono_get_method:
1740 */
1741 MonoMethod *
mono_get_method(MonoImage * image,guint32 token,MonoClass * klass)1742 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1743 {
1744 MonoError error;
1745 MonoMethod *result = mono_get_method_checked (image, token, klass, NULL, &error);
1746 mono_error_cleanup (&error);
1747 return result;
1748 }
1749
1750 /**
1751 * mono_get_method_full:
1752 */
1753 MonoMethod *
mono_get_method_full(MonoImage * image,guint32 token,MonoClass * klass,MonoGenericContext * context)1754 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1755 MonoGenericContext *context)
1756 {
1757 MonoError error;
1758 MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
1759 mono_error_cleanup (&error);
1760 return result;
1761 }
1762
1763 MonoMethod *
mono_get_method_checked(MonoImage * image,guint32 token,MonoClass * klass,MonoGenericContext * context,MonoError * error)1764 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
1765 {
1766 MonoMethod *result = NULL;
1767 gboolean used_context = FALSE;
1768
1769 /* We do everything inside the lock to prevent creation races */
1770
1771 error_init (error);
1772
1773 mono_image_lock (image);
1774
1775 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1776 if (!image->method_cache)
1777 image->method_cache = g_hash_table_new (NULL, NULL);
1778 result = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1779 } else if (!image_is_dynamic (image)) {
1780 if (!image->methodref_cache)
1781 image->methodref_cache = g_hash_table_new (NULL, NULL);
1782 result = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1783 }
1784 mono_image_unlock (image);
1785
1786 if (result)
1787 return result;
1788
1789
1790 result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
1791 if (!result)
1792 return NULL;
1793
1794 mono_image_lock (image);
1795 if (!used_context && !result->is_inflated) {
1796 MonoMethod *result2 = NULL;
1797
1798 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1799 result2 = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
1800 else if (!image_is_dynamic (image))
1801 result2 = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1802
1803 if (result2) {
1804 mono_image_unlock (image);
1805 return result2;
1806 }
1807
1808 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1809 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
1810 else if (!image_is_dynamic (image))
1811 g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1812 }
1813
1814 mono_image_unlock (image);
1815
1816 return result;
1817 }
1818
1819 static MonoMethod*
get_method_constrained(MonoImage * image,MonoMethod * method,MonoClass * constrained_class,MonoGenericContext * context,MonoError * error)1820 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
1821 {
1822 MonoClass *base_class = method->klass;
1823
1824 error_init (error);
1825
1826 if (!mono_class_is_assignable_from (base_class, constrained_class)) {
1827 char *base_class_name = mono_type_get_full_name (base_class);
1828 char *constrained_class_name = mono_type_get_full_name (constrained_class);
1829 mono_error_set_invalid_operation (error, "constrained call: %s is not assignable from %s", base_class_name, constrained_class_name);
1830 g_free (base_class_name);
1831 g_free (constrained_class_name);
1832 return NULL;
1833 }
1834
1835 /* If the constraining class is actually an interface, we don't learn
1836 * anything new by constraining.
1837 */
1838 if (MONO_CLASS_IS_INTERFACE (constrained_class))
1839 return method;
1840
1841 mono_class_setup_vtable (base_class);
1842 if (mono_class_has_failure (base_class)) {
1843 mono_error_set_for_class_failure (error, base_class);
1844 return NULL;
1845 }
1846
1847 MonoGenericContext inflated_method_ctx = { .class_inst = NULL, .method_inst = NULL };
1848 gboolean inflated_generic_method = FALSE;
1849 if (method->is_inflated) {
1850 MonoGenericContext *method_ctx = mono_method_get_context (method);
1851 /* If method is an instantiation of a generic method definition, ie
1852 * class H<T> { void M<U> (...) { ... } }
1853 * and method is H<C>.M<D>
1854 * we will get at the end a refined HSubclass<...>.M<U> and we will need to re-instantiate it with D.
1855 * to get HSubclass<...>.M<D>
1856 *
1857 */
1858 if (method_ctx->method_inst != NULL) {
1859 inflated_generic_method = TRUE;
1860 inflated_method_ctx.method_inst = method_ctx->method_inst;
1861 }
1862 }
1863 int vtable_slot = 0;
1864 if (!MONO_CLASS_IS_INTERFACE (base_class)) {
1865 /*if the base class isn't an interface and the method isn't
1866 * virtual, there's nothing to do, we're already on the method
1867 * we want to call. */
1868 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) == 0)
1869 return method;
1870 /* if this isn't an interface method, get the vtable slot and
1871 * find the corresponding method in the constrained class,
1872 * which is a subclass of the base class. */
1873 vtable_slot = mono_method_get_vtable_index (method);
1874
1875 mono_class_setup_vtable (constrained_class);
1876 if (mono_class_has_failure (constrained_class)) {
1877 mono_error_set_for_class_failure (error, constrained_class);
1878 return NULL;
1879 }
1880 } else {
1881 mono_class_setup_vtable (constrained_class);
1882 if (mono_class_has_failure (constrained_class)) {
1883 mono_error_set_for_class_failure (error, constrained_class);
1884 return NULL;
1885 }
1886
1887 /* Get the slot of the method in the interface. Then get the
1888 * interface base in constrained_class */
1889 int itf_slot = mono_method_get_vtable_index (method);
1890 g_assert (itf_slot >= 0);
1891 gboolean variant = FALSE;
1892 int itf_base = mono_class_interface_offset_with_variance (constrained_class, base_class, &variant);
1893 vtable_slot = itf_slot + itf_base;
1894 }
1895 g_assert (vtable_slot >= 0);
1896
1897 MonoMethod *res = mono_class_get_vtable_entry (constrained_class, vtable_slot);
1898 if (res == NULL && mono_class_is_abstract (constrained_class) ) {
1899 /* Constraining class is abstract, there may not be a refined method. */
1900 return method;
1901 }
1902 g_assert (res != NULL);
1903 if (inflated_generic_method) {
1904 g_assert (res->is_generic);
1905 res = mono_class_inflate_generic_method_checked (res, &inflated_method_ctx, error);
1906 return_val_if_nok (error, NULL);
1907 }
1908 return res;
1909 }
1910
1911 MonoMethod *
mono_get_method_constrained_with_method(MonoImage * image,MonoMethod * method,MonoClass * constrained_class,MonoGenericContext * context,MonoError * error)1912 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
1913 MonoGenericContext *context, MonoError *error)
1914 {
1915 g_assert (method);
1916
1917 return get_method_constrained (image, method, constrained_class, context, error);
1918 }
1919
1920 /**
1921 * mono_get_method_constrained:
1922 * This is used when JITing the <code>constrained.</code> opcode.
1923 * \returns The contrained method, which has been inflated
1924 * as the function return value; and the original CIL-stream method as
1925 * declared in \p cil_method. The latter is used for verification.
1926 */
1927 MonoMethod *
mono_get_method_constrained(MonoImage * image,guint32 token,MonoClass * constrained_class,MonoGenericContext * context,MonoMethod ** cil_method)1928 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1929 MonoGenericContext *context, MonoMethod **cil_method)
1930 {
1931 MonoError error;
1932 MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
1933 mono_error_cleanup (&error);
1934 return result;
1935 }
1936
1937 MonoMethod *
mono_get_method_constrained_checked(MonoImage * image,guint32 token,MonoClass * constrained_class,MonoGenericContext * context,MonoMethod ** cil_method,MonoError * error)1938 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
1939 {
1940 error_init (error);
1941
1942 *cil_method = mono_get_method_checked (image, token, NULL, context, error);
1943 if (!*cil_method)
1944 return NULL;
1945
1946 return get_method_constrained (image, *cil_method, constrained_class, context, error);
1947 }
1948
1949 /**
1950 * mono_free_method:
1951 */
1952 void
mono_free_method(MonoMethod * method)1953 mono_free_method (MonoMethod *method)
1954 {
1955 MONO_PROFILER_RAISE (method_free, (method));
1956
1957 /* FIXME: This hack will go away when the profiler will support freeing methods */
1958 if (G_UNLIKELY (mono_profiler_installed ()))
1959 return;
1960
1961 if (method->signature) {
1962 /*
1963 * FIXME: This causes crashes because the types inside signatures and
1964 * locals are shared.
1965 */
1966 /* mono_metadata_free_method_signature (method->signature); */
1967 /* g_free (method->signature); */
1968 }
1969
1970 if (method_is_dynamic (method)) {
1971 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1972 int i;
1973
1974 mono_marshal_free_dynamic_wrappers (method);
1975
1976 mono_image_property_remove (method->klass->image, method);
1977
1978 g_free ((char*)method->name);
1979 if (mw->header) {
1980 g_free ((char*)mw->header->code);
1981 for (i = 0; i < mw->header->num_locals; ++i)
1982 g_free (mw->header->locals [i]);
1983 g_free (mw->header->clauses);
1984 g_free (mw->header);
1985 }
1986 g_free (mw->method_data);
1987 g_free (method->signature);
1988 g_free (method);
1989 }
1990 }
1991
1992 /**
1993 * mono_method_get_param_names:
1994 */
1995 void
mono_method_get_param_names(MonoMethod * method,const char ** names)1996 mono_method_get_param_names (MonoMethod *method, const char **names)
1997 {
1998 int i, lastp;
1999 MonoClass *klass;
2000 MonoTableInfo *methodt;
2001 MonoTableInfo *paramt;
2002 MonoMethodSignature *signature;
2003 guint32 idx;
2004
2005 if (method->is_inflated)
2006 method = ((MonoMethodInflated *) method)->declaring;
2007
2008 signature = mono_method_signature (method);
2009 /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2010 number of arguments and allocate a properly sized array. */
2011 if (signature == NULL)
2012 return;
2013
2014 if (!signature->param_count)
2015 return;
2016
2017 for (i = 0; i < signature->param_count; ++i)
2018 names [i] = "";
2019
2020 klass = method->klass;
2021 if (klass->rank)
2022 return;
2023
2024 mono_class_init (klass);
2025
2026 if (image_is_dynamic (klass->image)) {
2027 MonoReflectionMethodAux *method_aux =
2028 (MonoReflectionMethodAux *)g_hash_table_lookup (
2029 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2030 if (method_aux && method_aux->param_names) {
2031 for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2032 if (method_aux->param_names [i + 1])
2033 names [i] = method_aux->param_names [i + 1];
2034 }
2035 return;
2036 }
2037
2038 if (method->wrapper_type) {
2039 char **pnames = NULL;
2040
2041 mono_image_lock (klass->image);
2042 if (klass->image->wrapper_param_names)
2043 pnames = (char **)g_hash_table_lookup (klass->image->wrapper_param_names, method);
2044 mono_image_unlock (klass->image);
2045
2046 if (pnames) {
2047 for (i = 0; i < signature->param_count; ++i)
2048 names [i] = pnames [i];
2049 }
2050 return;
2051 }
2052
2053 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2054 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2055 idx = mono_method_get_index (method);
2056 if (idx > 0) {
2057 guint32 cols [MONO_PARAM_SIZE];
2058 guint param_index;
2059
2060 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2061
2062 if (idx < methodt->rows)
2063 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2064 else
2065 lastp = paramt->rows + 1;
2066 for (i = param_index; i < lastp; ++i) {
2067 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2068 if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2069 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2070 }
2071 }
2072 }
2073
2074 /**
2075 * mono_method_get_param_token:
2076 */
2077 guint32
mono_method_get_param_token(MonoMethod * method,int index)2078 mono_method_get_param_token (MonoMethod *method, int index)
2079 {
2080 MonoClass *klass = method->klass;
2081 MonoTableInfo *methodt;
2082 guint32 idx;
2083
2084 mono_class_init (klass);
2085
2086 if (image_is_dynamic (klass->image))
2087 g_assert_not_reached ();
2088
2089 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2090 idx = mono_method_get_index (method);
2091 if (idx > 0) {
2092 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2093
2094 if (index == -1)
2095 /* Return value */
2096 return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2097 else
2098 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2099 }
2100
2101 return 0;
2102 }
2103
2104 /**
2105 * mono_method_get_marshal_info:
2106 */
2107 void
mono_method_get_marshal_info(MonoMethod * method,MonoMarshalSpec ** mspecs)2108 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2109 {
2110 int i, lastp;
2111 MonoClass *klass = method->klass;
2112 MonoTableInfo *methodt;
2113 MonoTableInfo *paramt;
2114 MonoMethodSignature *signature;
2115 guint32 idx;
2116
2117 signature = mono_method_signature (method);
2118 g_assert (signature); /*FIXME there is no way to signal error from this function*/
2119
2120 for (i = 0; i < signature->param_count + 1; ++i)
2121 mspecs [i] = NULL;
2122
2123 if (image_is_dynamic (method->klass->image)) {
2124 MonoReflectionMethodAux *method_aux =
2125 (MonoReflectionMethodAux *)g_hash_table_lookup (
2126 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2127 if (method_aux && method_aux->param_marshall) {
2128 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2129 for (i = 0; i < signature->param_count + 1; ++i)
2130 if (dyn_specs [i]) {
2131 mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2132 memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2133 mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2134 mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2135 }
2136 }
2137 return;
2138 }
2139
2140 mono_class_init (klass);
2141
2142 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2143 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2144 idx = mono_method_get_index (method);
2145 if (idx > 0) {
2146 guint32 cols [MONO_PARAM_SIZE];
2147 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2148
2149 if (idx < methodt->rows)
2150 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2151 else
2152 lastp = paramt->rows + 1;
2153
2154 for (i = param_index; i < lastp; ++i) {
2155 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2156
2157 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2158 const char *tp;
2159 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2160 g_assert (tp);
2161 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2162 }
2163 }
2164
2165 return;
2166 }
2167 }
2168
2169 /**
2170 * mono_method_has_marshal_info:
2171 */
2172 gboolean
mono_method_has_marshal_info(MonoMethod * method)2173 mono_method_has_marshal_info (MonoMethod *method)
2174 {
2175 int i, lastp;
2176 MonoClass *klass = method->klass;
2177 MonoTableInfo *methodt;
2178 MonoTableInfo *paramt;
2179 guint32 idx;
2180
2181 if (image_is_dynamic (method->klass->image)) {
2182 MonoReflectionMethodAux *method_aux =
2183 (MonoReflectionMethodAux *)g_hash_table_lookup (
2184 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2185 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2186 if (dyn_specs) {
2187 for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2188 if (dyn_specs [i])
2189 return TRUE;
2190 }
2191 return FALSE;
2192 }
2193
2194 mono_class_init (klass);
2195
2196 methodt = &klass->image->tables [MONO_TABLE_METHOD];
2197 paramt = &klass->image->tables [MONO_TABLE_PARAM];
2198 idx = mono_method_get_index (method);
2199 if (idx > 0) {
2200 guint32 cols [MONO_PARAM_SIZE];
2201 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2202
2203 if (idx + 1 < methodt->rows)
2204 lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2205 else
2206 lastp = paramt->rows + 1;
2207
2208 for (i = param_index; i < lastp; ++i) {
2209 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2210
2211 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2212 return TRUE;
2213 }
2214 return FALSE;
2215 }
2216 return FALSE;
2217 }
2218
2219 gpointer
mono_method_get_wrapper_data(MonoMethod * method,guint32 id)2220 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2221 {
2222 void **data;
2223 g_assert (method != NULL);
2224 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2225
2226 data = (void **)((MonoMethodWrapper *)method)->method_data;
2227 g_assert (data != NULL);
2228 g_assert (id <= GPOINTER_TO_UINT (*data));
2229 return data [id];
2230 }
2231
2232 typedef struct {
2233 MonoStackWalk func;
2234 gpointer user_data;
2235 } StackWalkUserData;
2236
2237 static gboolean
stack_walk_adapter(MonoStackFrameInfo * frame,MonoContext * ctx,gpointer data)2238 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2239 {
2240 StackWalkUserData *d = (StackWalkUserData *)data;
2241
2242 switch (frame->type) {
2243 case FRAME_TYPE_DEBUGGER_INVOKE:
2244 case FRAME_TYPE_MANAGED_TO_NATIVE:
2245 case FRAME_TYPE_TRAMPOLINE:
2246 return FALSE;
2247 case FRAME_TYPE_MANAGED:
2248 g_assert (frame->ji);
2249 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2250 break;
2251 default:
2252 g_assert_not_reached ();
2253 return FALSE;
2254 }
2255 }
2256
2257 void
mono_stack_walk(MonoStackWalk func,gpointer user_data)2258 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2259 {
2260 StackWalkUserData ud = { func, user_data };
2261 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2262 }
2263
2264 /**
2265 * mono_stack_walk_no_il:
2266 */
2267 void
mono_stack_walk_no_il(MonoStackWalk func,gpointer user_data)2268 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2269 {
2270 StackWalkUserData ud = { func, user_data };
2271 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2272 }
2273
2274 typedef struct {
2275 MonoStackWalkAsyncSafe func;
2276 gpointer user_data;
2277 } AsyncStackWalkUserData;
2278
2279
2280 static gboolean
async_stack_walk_adapter(MonoStackFrameInfo * frame,MonoContext * ctx,gpointer data)2281 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2282 {
2283 AsyncStackWalkUserData *d = (AsyncStackWalkUserData *)data;
2284
2285 switch (frame->type) {
2286 case FRAME_TYPE_DEBUGGER_INVOKE:
2287 case FRAME_TYPE_MANAGED_TO_NATIVE:
2288 case FRAME_TYPE_TRAMPOLINE:
2289 return FALSE;
2290 case FRAME_TYPE_MANAGED:
2291 if (!frame->ji)
2292 return FALSE;
2293 if (frame->ji->async) {
2294 return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2295 } else {
2296 return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2297 }
2298 break;
2299 default:
2300 g_assert_not_reached ();
2301 return FALSE;
2302 }
2303 }
2304
2305
2306 /**
2307 * mono_stack_walk_async_safe:
2308 * Async safe version callable from signal handlers.
2309 */
2310 void
mono_stack_walk_async_safe(MonoStackWalkAsyncSafe func,void * initial_sig_context,void * user_data)2311 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2312 {
2313 MonoContext ctx;
2314 AsyncStackWalkUserData ud = { func, user_data };
2315
2316 mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2317 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, &ctx, MONO_UNWIND_SIGNAL_SAFE, &ud);
2318 }
2319
2320 static gboolean
last_managed(MonoMethod * m,gint no,gint ilo,gboolean managed,gpointer data)2321 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2322 {
2323 MonoMethod **dest = (MonoMethod **)data;
2324 *dest = m;
2325 /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2326
2327 return managed;
2328 }
2329
2330 /**
2331 * mono_method_get_last_managed:
2332 */
2333 MonoMethod*
mono_method_get_last_managed(void)2334 mono_method_get_last_managed (void)
2335 {
2336 MonoMethod *m = NULL;
2337 mono_stack_walk_no_il (last_managed, &m);
2338 return m;
2339 }
2340
2341 static gboolean loader_lock_track_ownership = FALSE;
2342
2343 /**
2344 * mono_loader_lock:
2345 *
2346 * See \c docs/thread-safety.txt for the locking strategy.
2347 */
2348 void
mono_loader_lock(void)2349 mono_loader_lock (void)
2350 {
2351 mono_locks_coop_acquire (&loader_mutex, LoaderLock);
2352 if (G_UNLIKELY (loader_lock_track_ownership)) {
2353 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));
2354 }
2355 }
2356
2357 /**
2358 * mono_loader_unlock:
2359 */
2360 void
mono_loader_unlock(void)2361 mono_loader_unlock (void)
2362 {
2363 mono_locks_coop_release (&loader_mutex, LoaderLock);
2364 if (G_UNLIKELY (loader_lock_track_ownership)) {
2365 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));
2366 }
2367 }
2368
2369 /*
2370 * mono_loader_lock_track_ownership:
2371 *
2372 * Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2373 * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2374 * thread owns the loader lock.
2375 */
2376 void
mono_loader_lock_track_ownership(gboolean track)2377 mono_loader_lock_track_ownership (gboolean track)
2378 {
2379 loader_lock_track_ownership = track;
2380 }
2381
2382 /*
2383 * mono_loader_lock_is_owned_by_self:
2384 *
2385 * Return whenever the current thread owns the loader lock.
2386 * This is useful to avoid blocking operations while holding the loader lock.
2387 */
2388 gboolean
mono_loader_lock_is_owned_by_self(void)2389 mono_loader_lock_is_owned_by_self (void)
2390 {
2391 g_assert (loader_lock_track_ownership);
2392
2393 return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2394 }
2395
2396 /*
2397 * mono_loader_lock_if_inited:
2398 *
2399 * Acquire the loader lock if it has been initialized, no-op otherwise. This can
2400 * be used in runtime initialization code which can be executed before mono_loader_init ().
2401 */
2402 void
mono_loader_lock_if_inited(void)2403 mono_loader_lock_if_inited (void)
2404 {
2405 if (loader_lock_inited)
2406 mono_loader_lock ();
2407 }
2408
2409 void
mono_loader_unlock_if_inited(void)2410 mono_loader_unlock_if_inited (void)
2411 {
2412 if (loader_lock_inited)
2413 mono_loader_unlock ();
2414 }
2415
2416 /**
2417 * mono_method_signature_checked:
2418 *
2419 * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2420 */
2421 MonoMethodSignature*
mono_method_signature_checked(MonoMethod * m,MonoError * error)2422 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2423 {
2424 int idx;
2425 MonoImage* img;
2426 const char *sig;
2427 gboolean can_cache_signature;
2428 MonoGenericContainer *container;
2429 MonoMethodSignature *signature = NULL, *sig2;
2430 guint32 sig_offset;
2431
2432 /* We need memory barriers below because of the double-checked locking pattern */
2433
2434 error_init (error);
2435
2436 if (m->signature)
2437 return m->signature;
2438
2439 img = m->klass->image;
2440
2441 if (m->is_inflated) {
2442 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2443 /* the lock is recursive */
2444 signature = mono_method_signature (imethod->declaring);
2445 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2446 if (!mono_error_ok (error))
2447 return NULL;
2448
2449 mono_atomic_fetch_add_i32 (&inflated_signatures_size, mono_metadata_signature_size (signature));
2450
2451 mono_image_lock (img);
2452
2453 mono_memory_barrier ();
2454 if (!m->signature)
2455 m->signature = signature;
2456
2457 mono_image_unlock (img);
2458
2459 return m->signature;
2460 }
2461
2462 g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2463 idx = mono_metadata_token_index (m->token);
2464
2465 sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2466
2467 g_assert (!mono_class_is_ginst (m->klass));
2468 container = mono_method_get_generic_container (m);
2469 if (!container)
2470 container = mono_class_try_get_generic_container (m->klass);
2471
2472 /* Generic signatures depend on the container so they cannot be cached */
2473 /* icall/pinvoke signatures cannot be cached cause we modify them below */
2474 can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2475
2476 /* If the method has parameter attributes, that can modify the signature */
2477 if (mono_metadata_method_has_param_attrs (img, idx))
2478 can_cache_signature = FALSE;
2479
2480 if (can_cache_signature) {
2481 mono_image_lock (img);
2482 signature = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2483 mono_image_unlock (img);
2484 }
2485
2486 if (!signature) {
2487 const char *sig_body;
2488 /*TODO we should cache the failure result somewhere*/
2489 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2490 return NULL;
2491
2492 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2493
2494 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2495 if (!signature)
2496 return NULL;
2497
2498 if (can_cache_signature) {
2499 mono_image_lock (img);
2500 sig2 = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2501 if (!sig2)
2502 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2503 mono_image_unlock (img);
2504 }
2505
2506 mono_atomic_fetch_add_i32 (&signatures_size, mono_metadata_signature_size (signature));
2507 }
2508
2509 /* Verify metadata consistency */
2510 if (signature->generic_param_count) {
2511 if (!container || !container->is_method) {
2512 mono_error_set_method_load (error, m->klass, g_strdup (m->name), mono_signature_get_managed_fmt_string (signature), "Signature claims method has generic parameters, but generic_params table says it doesn't for method 0x%08x from image %s", idx, img->name);
2513 return NULL;
2514 }
2515 if (container->type_argc != signature->generic_param_count) {
2516 mono_error_set_method_load (error, m->klass, g_strdup (m->name), mono_signature_get_managed_fmt_string (signature), "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);
2517 return NULL;
2518 }
2519 } else if (container && container->is_method && container->type_argc) {
2520 mono_error_set_method_load (error, m->klass, g_strdup (m->name), mono_signature_get_managed_fmt_string (signature), "generic_params table claims method has generic parameters, but signature says it doesn't for method 0x%08x from image %s", idx, img->name);
2521 return NULL;
2522 }
2523 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
2524 signature->pinvoke = 1;
2525 #ifdef TARGET_WIN32
2526 /*
2527 * On Windows the default pinvoke calling convention is STDCALL but
2528 * we need CDECL since this is actually an icall.
2529 */
2530 signature->call_convention = MONO_CALL_C;
2531 #endif
2532 } else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2533 MonoCallConvention conv = (MonoCallConvention)0;
2534 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2535 signature->pinvoke = 1;
2536
2537 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2538 case 0: /* no call conv, so using default */
2539 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2540 conv = MONO_CALL_DEFAULT;
2541 break;
2542 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2543 conv = MONO_CALL_C;
2544 break;
2545 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2546 conv = MONO_CALL_STDCALL;
2547 break;
2548 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2549 conv = MONO_CALL_THISCALL;
2550 break;
2551 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2552 conv = MONO_CALL_FASTCALL;
2553 break;
2554 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2555 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2556 default: {
2557 mono_error_set_method_load (error, m->klass, g_strdup (m->name), mono_signature_get_managed_fmt_string (signature), "unsupported calling convention : 0x%04x for method 0x%08x from image %s", piinfo->piflags, idx, img->name);
2558 }
2559 return NULL;
2560 }
2561 signature->call_convention = conv;
2562 }
2563
2564 mono_image_lock (img);
2565
2566 mono_memory_barrier ();
2567 if (!m->signature)
2568 m->signature = signature;
2569
2570 mono_image_unlock (img);
2571
2572 return m->signature;
2573 }
2574
2575 /**
2576 * mono_method_signature:
2577 * \returns the signature of the method \p m. On failure, returns NULL.
2578 */
2579 MonoMethodSignature*
mono_method_signature(MonoMethod * m)2580 mono_method_signature (MonoMethod *m)
2581 {
2582 MonoError error;
2583 MonoMethodSignature *sig;
2584
2585 sig = mono_method_signature_checked (m, &error);
2586 if (!sig) {
2587 char *type_name = mono_type_get_full_name (m->klass);
2588 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2589 g_free (type_name);
2590 mono_error_cleanup (&error);
2591 }
2592
2593 return sig;
2594 }
2595
2596 /**
2597 * mono_method_get_name:
2598 */
2599 const char*
mono_method_get_name(MonoMethod * method)2600 mono_method_get_name (MonoMethod *method)
2601 {
2602 return method->name;
2603 }
2604
2605 /**
2606 * mono_method_get_class:
2607 */
2608 MonoClass*
mono_method_get_class(MonoMethod * method)2609 mono_method_get_class (MonoMethod *method)
2610 {
2611 return method->klass;
2612 }
2613
2614 /**
2615 * mono_method_get_token:
2616 */
2617 guint32
mono_method_get_token(MonoMethod * method)2618 mono_method_get_token (MonoMethod *method)
2619 {
2620 return method->token;
2621 }
2622
2623 MonoMethodHeader*
mono_method_get_header_checked(MonoMethod * method,MonoError * error)2624 mono_method_get_header_checked (MonoMethod *method, MonoError *error)
2625 {
2626 int idx;
2627 guint32 rva;
2628 MonoImage* img;
2629 gpointer loc;
2630 MonoGenericContainer *container;
2631
2632 error_init (error);
2633 img = method->klass->image;
2634
2635 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)) {
2636 mono_error_set_bad_image (error, img, "Method has no body");
2637 return NULL;
2638 }
2639
2640 if (method->is_inflated) {
2641 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2642 MonoMethodHeader *header, *iheader;
2643
2644 header = mono_method_get_header_checked (imethod->declaring, error);
2645 if (!header)
2646 return NULL;
2647
2648 iheader = inflate_generic_header (header, mono_method_get_context (method), error);
2649 mono_metadata_free_mh (header);
2650 if (!iheader) {
2651 return NULL;
2652 }
2653
2654 return iheader;
2655 }
2656
2657 if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2658 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2659 g_assert (mw->header);
2660 return mw->header;
2661 }
2662
2663 /*
2664 * We don't need locks here: the new header is allocated from malloc memory
2665 * and is not stored anywhere in the runtime, the user needs to free it.
2666 */
2667 g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2668 idx = mono_metadata_token_index (method->token);
2669 rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2670
2671 if (!mono_verifier_verify_method_header (img, rva, NULL)) {
2672 mono_error_set_bad_image (error, img, "Invalid method header, failed verification");
2673 return NULL;
2674 }
2675
2676 loc = mono_image_rva_map (img, rva);
2677 if (!loc) {
2678 mono_error_set_bad_image (error, img, "Method has zero rva");
2679 return NULL;
2680 }
2681
2682 /*
2683 * When parsing the types of local variables, we must pass any container available
2684 * to ensure that both VAR and MVAR will get the right owner.
2685 */
2686 container = mono_method_get_generic_container (method);
2687 if (!container)
2688 container = mono_class_try_get_generic_container (method->klass);
2689 return mono_metadata_parse_mh_full (img, container, (const char *)loc, error);
2690 }
2691
2692 /**
2693 * mono_method_get_header:
2694 */
2695 MonoMethodHeader*
mono_method_get_header(MonoMethod * method)2696 mono_method_get_header (MonoMethod *method)
2697 {
2698 MonoError error;
2699 MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
2700 mono_error_cleanup (&error);
2701 return header;
2702 }
2703
2704
2705 /**
2706 * mono_method_get_flags:
2707 */
2708 guint32
mono_method_get_flags(MonoMethod * method,guint32 * iflags)2709 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2710 {
2711 if (iflags)
2712 *iflags = method->iflags;
2713 return method->flags;
2714 }
2715
2716 /**
2717 * mono_method_get_index:
2718 * Find the method index in the metadata \c MethodDef table.
2719 */
2720 guint32
mono_method_get_index(MonoMethod * method)2721 mono_method_get_index (MonoMethod *method)
2722 {
2723 MonoClass *klass = method->klass;
2724 int i;
2725
2726 if (klass->rank)
2727 /* constructed array methods are not in the MethodDef table */
2728 return 0;
2729
2730 if (method->token)
2731 return mono_metadata_token_index (method->token);
2732
2733 mono_class_setup_methods (klass);
2734 if (mono_class_has_failure (klass))
2735 return 0;
2736 int first_idx = mono_class_get_first_method_idx (klass);
2737 int mcount = mono_class_get_method_count (klass);
2738 for (i = 0; i < mcount; ++i) {
2739 if (method == klass->methods [i]) {
2740 if (klass->image->uncompressed_metadata)
2741 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, first_idx + i + 1);
2742 else
2743 return first_idx + i + 1;
2744 }
2745 }
2746 return 0;
2747 }
2748