2006-05-04 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / loader.c
1 /*
2  * loader.c: Image Loader 
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Miguel de Icaza (miguel@ximian.com)
7  *   Patrik Torstensson (patrik.torstensson@labs2.com)
8  *
9  * (C) 2001 Ximian, Inc.
10  *
11  * This file is used by the interpreter and the JIT engine to locate
12  * assemblies.  Used to load AssemblyRef and later to resolve various
13  * kinds of `Refs'.
14  *
15  * TODO:
16  *   This should keep track of the assembly versions that we are loading.
17  *
18  */
19 #include <config.h>
20 #include <glib.h>
21 #include <gmodule.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <mono/metadata/metadata.h>
26 #include <mono/metadata/image.h>
27 #include <mono/metadata/assembly.h>
28 #include <mono/metadata/tokentype.h>
29 #include <mono/metadata/cil-coff.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/metadata-internals.h>
32 #include <mono/metadata/loader.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/debug-helpers.h>
35 #include <mono/metadata/reflection.h>
36 #include <mono/utils/mono-logger.h>
37
38 MonoDefaults mono_defaults;
39
40 /*
41  * This lock protects the hash tables inside MonoImage used by the metadata 
42  * loading functions in class.c and loader.c.
43  */
44 static CRITICAL_SECTION loader_mutex;
45
46
47 /*
48  * This TLS variable contains the last type load error encountered by the loader.
49  */
50 guint32 loader_error_thread_id;
51
52 void
53 mono_loader_init ()
54 {
55         InitializeCriticalSection (&loader_mutex);
56
57         loader_error_thread_id = TlsAlloc ();
58 }
59
60 void
61 mono_loader_cleanup (void)
62 {
63         TlsFree (loader_error_thread_id);
64
65         DeleteCriticalSection (&loader_mutex);
66 }
67
68 /*
69  * Handling of type load errors should be done as follows:
70  *
71  *   If something could not be loaded, the loader should call one of the
72  * mono_loader_set_error_XXX functions ()
73  * with the appropriate arguments, then return NULL to report the failure. The error 
74  * should be propagated until it reaches code which can throw managed exceptions. At that
75  * point, an exception should be thrown based on the information returned by
76  * mono_loader_get_error (). Then the error should be cleared by calling 
77  * mono_loader_clear_error ().
78  */
79
80 static void
81 set_loader_error (MonoLoaderError *error)
82 {
83         TlsSetValue (loader_error_thread_id, error);
84 }
85
86 /*
87  * mono_loader_set_error_type_load:
88  *
89  *   Set the loader error for this thread. CLASS_NAME and ASSEMBLY_NAME should be
90  * dynamically allocated strings whose ownership is passed to this function.
91  */
92 void
93 mono_loader_set_error_type_load (char *class_name, char *assembly_name)
94 {
95         MonoLoaderError *error;
96
97         if (mono_loader_get_last_error ()) {
98                 g_free (class_name);
99                 g_free (assembly_name);
100                 return;
101         }
102
103         error = g_new0 (MonoLoaderError, 1);
104         error->kind = MONO_LOADER_ERROR_TYPE;
105         error->class_name = class_name;
106         error->assembly_name = assembly_name;
107
108         /* 
109          * This is not strictly needed, but some (most) of the loader code still
110          * can't deal with load errors, and this message is more helpful than an
111          * assert.
112          */
113         g_warning ("The class %s could not be loaded, used in %s", class_name, assembly_name);
114
115         set_loader_error (error);
116 }
117
118 /*
119  * mono_loader_set_error_method_load:
120  *
121  *   Set the loader error for this thread. MEMBER_NAME should point to a string
122  * inside metadata.
123  */
124 void
125 mono_loader_set_error_method_load (MonoClass *klass, const char *member_name)
126 {
127         MonoLoaderError *error;
128
129         /* FIXME: Store the signature as well */
130         if (mono_loader_get_last_error ())
131                 return;
132
133         error = g_new0 (MonoLoaderError, 1);
134         error->kind = MONO_LOADER_ERROR_METHOD;
135         error->klass = klass;
136         error->member_name = member_name;
137
138         set_loader_error (error);
139 }
140
141 /*
142  * mono_loader_set_error_field_load:
143  *
144  *   Set the loader error for this thread. MEMBER_NAME should point to a string
145  * inside metadata.
146  */
147 void
148 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
149 {
150         MonoLoaderError *error;
151
152         /* FIXME: Store the signature as well */
153         if (mono_loader_get_last_error ())
154                 return;
155
156         error = g_new0 (MonoLoaderError, 1);
157         error->kind = MONO_LOADER_ERROR_FIELD;
158         error->klass = klass;
159         error->member_name = member_name;
160
161         set_loader_error (error);
162 }
163
164 /*
165  * mono_loader_get_last_error:
166  *
167  *   Returns information about the last type load exception encountered by the loader, or
168  * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
169  */
170 MonoLoaderError*
171 mono_loader_get_last_error (void)
172 {
173         return (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
174 }
175
176 void
177 mono_loader_clear_error (void)
178 {
179         MonoLoaderError *ex = (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
180
181         g_assert (ex);  
182
183         g_free (ex->class_name);
184         g_free (ex->assembly_name);
185         g_free (ex);
186
187         TlsSetValue (loader_error_thread_id, NULL);
188 }
189
190 static MonoClassField*
191 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
192                       MonoGenericContext *context)
193 {
194         MonoClass *klass;
195         MonoClassField *field;
196         MonoTableInfo *tables = image->tables;
197         guint32 cols[6];
198         guint32 nindex, class;
199         const char *fname;
200         const char *ptr;
201         guint32 idx = mono_metadata_token_index (token);
202
203         if (image->dynamic) {
204                 MonoClassField *result = mono_lookup_dynamic_token (image, token);
205                 *retklass = result->parent;
206                 return result;
207         }
208
209         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
210         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
211         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
212
213         fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
214
215         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
216         mono_metadata_decode_blob_size (ptr, &ptr);
217         /* we may want to check the signature here... */
218
219         switch (class) {
220         case MONO_MEMBERREF_PARENT_TYPEREF:
221                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
222                 if (!klass) {
223                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
224                         g_warning ("Missing field %s in class %s (typeref index %d)", fname, name, nindex);
225                         g_free (name);
226                         return NULL;
227                 }
228                 mono_class_init (klass);
229                 if (retklass)
230                         *retklass = klass;
231                 field = mono_class_get_field_from_name (klass, fname);
232                 break;
233         case MONO_MEMBERREF_PARENT_TYPESPEC: {
234                 /*guint32 bcols [MONO_TYPESPEC_SIZE];
235                 guint32 len;
236                 MonoType *type;
237
238                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
239                                           bcols, MONO_TYPESPEC_SIZE);
240                 ptr = mono_metadata_blob_heap (image, bcols [MONO_TYPESPEC_SIGNATURE]);
241                 len = mono_metadata_decode_value (ptr, &ptr);   
242                 type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
243
244                 klass = mono_class_from_mono_type (type);
245                 mono_class_init (klass);
246                 g_print ("type in sig: %s\n", klass->name);*/
247                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
248                 mono_class_init (klass);
249                 if (retklass)
250                         *retklass = klass;
251                 field = mono_class_get_field_from_name (klass, fname);
252                 break;
253         }
254         default:
255                 g_warning ("field load from %x", class);
256                 return NULL;
257         }
258
259         if (!field)
260                 mono_loader_set_error_field_load (klass, fname);
261
262         return field;
263 }
264
265 MonoClassField*
266 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
267                        MonoGenericContext *context)
268 {
269         MonoClass *k;
270         guint32 type;
271         MonoClassField *field;
272
273         if (image->dynamic) {
274                 MonoClassField *result = mono_lookup_dynamic_token (image, token);
275                 *retklass = result->parent;
276                 return result;
277         }
278
279         mono_loader_lock ();
280         if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
281                 *retklass = field->parent;
282                 mono_loader_unlock ();
283                 return field;
284         }
285         mono_loader_unlock ();
286
287         if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
288                 field = field_from_memberref (image, token, retklass, context);
289         else {
290                 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
291                 if (!type)
292                         return NULL;
293                 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
294                 mono_class_init (k);
295                 if (!k)
296                         return NULL;
297                 if (retklass)
298                         *retklass = k;
299                 field = mono_class_get_field (k, token);
300         }
301
302         mono_loader_lock ();
303         if (field && !field->parent->generic_class)
304                 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
305         mono_loader_unlock ();
306         return field;
307 }
308
309 static gboolean
310 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
311 {
312         int i;
313
314         if (sig1->hasthis != sig2->hasthis ||
315             sig1->sentinelpos != sig2->sentinelpos)
316                 return FALSE;
317
318         for (i = 0; i < sig1->sentinelpos; i++) { 
319                 MonoType *p1 = sig1->params[i];
320                 MonoType *p2 = sig2->params[i];
321
322                 /*if (p1->attrs != p2->attrs)
323                         return FALSE;
324                 */
325                 if (!mono_metadata_type_equal (p1, p2))
326                         return FALSE;
327         }
328
329         if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
330                 return FALSE;
331         return TRUE;
332 }
333
334 static MonoMethod *
335 find_method_in_class (MonoClass *in_class, const char *name, const char *qname, const char *fqname,
336                       MonoMethodSignature *sig, MonoClass *from_class)
337 {
338         int i;
339
340         mono_class_setup_methods (in_class);
341         for (i = 0; i < in_class->method.count; ++i) {
342                 MonoMethod *m = in_class->methods [i];
343
344                 if (!((fqname && !strcmp (m->name, fqname)) ||
345                       (qname && !strcmp (m->name, qname)) || !strcmp (m->name, name)))
346                         continue;
347
348                 if (sig->call_convention == MONO_CALL_VARARG) {
349                         if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m)))
350                                 break;
351                 } else {
352                         if (mono_metadata_signature_equal (sig, mono_method_signature (m)))
353                                 break;
354                 }
355         }
356
357         if (i < in_class->method.count) {
358                 mono_class_setup_methods (from_class);
359                 g_assert (from_class->method.count == in_class->method.count);
360                 return from_class->methods [i];
361         }
362         return NULL;
363 }
364
365 static MonoMethod *
366 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
367 {
368         int i;
369         char *qname, *fqname, *class_name;
370         gboolean is_interface;
371         MonoMethod *result = NULL;
372
373         is_interface = MONO_CLASS_IS_INTERFACE (in_class);
374
375         if (ic) {
376                 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
377
378                 qname = g_strconcat (class_name, ".", name, NULL); 
379                 if (ic->name_space && ic->name_space [0])
380                         fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
381                 else
382                         fqname = NULL;
383         } else
384                 class_name = qname = fqname = NULL;
385
386         while (in_class) {
387                 g_assert (from_class);
388                 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
389                 if (result)
390                         goto out;
391
392                 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
393                         break;
394
395                 g_assert (from_class->interface_count == in_class->interface_count);
396                 for (i = 0; i < in_class->interface_count; i++) {
397                         MonoClass *ic = in_class->interfaces [i];
398                         MonoClass *from_ic = from_class->interfaces [i];
399
400                         result = find_method_in_class (ic, name, qname, fqname, sig, from_ic);
401                         if (result)
402                                 goto out;
403                 }
404
405                 in_class = in_class->parent;
406                 from_class = from_class->parent;
407         }
408         g_assert (!in_class == !from_class);
409
410         if (is_interface)
411                 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
412
413  out:
414         g_free (class_name);
415         g_free (fqname);
416         g_free (qname);
417         return result;
418 }
419
420 static MonoMethodSignature*
421 inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
422 {
423         MonoMethodSignature *res;
424         gboolean is_open;
425         int i;
426
427         if (!context)
428                 return sig;
429
430         res = mono_metadata_signature_alloc (image, sig->param_count);
431         res->ret = mono_class_inflate_generic_type (sig->ret, context);
432         is_open = mono_class_is_open_constructed_type (res->ret);
433         for (i = 0; i < sig->param_count; ++i) {
434                 res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
435                 if (!is_open)
436                         is_open = mono_class_is_open_constructed_type (res->params [i]);
437         }
438         res->hasthis = sig->hasthis;
439         res->explicit_this = sig->explicit_this;
440         res->call_convention = sig->call_convention;
441         res->pinvoke = sig->pinvoke;
442         res->generic_param_count = sig->generic_param_count;
443         res->sentinelpos = sig->sentinelpos;
444         res->has_type_parameters = is_open;
445         res->is_inflated = 1;
446         return res;
447 }
448
449 static MonoMethodHeader*
450 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
451 {
452         MonoMethodHeader *res;
453         int i;
454         res = g_malloc0 (sizeof (MonoMethodHeader) + sizeof (gpointer) * header->num_locals);
455         res->code = header->code;
456         res->code_size = header->code_size;
457         res->max_stack = header->max_stack;
458         res->num_clauses = header->num_clauses;
459         res->init_locals = header->init_locals;
460         res->num_locals = header->num_locals;
461         res->clauses = header->clauses;
462         for (i = 0; i < header->num_locals; ++i)
463                 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
464         return res;
465 }
466
467 /*
468  * token is the method_ref or method_def token used in a call IL instruction.
469  */
470 MonoMethodSignature*
471 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
472 {
473         int table = mono_metadata_token_table (token);
474         int idx = mono_metadata_token_index (token);
475         guint32 cols [MONO_MEMBERREF_SIZE];
476         MonoMethodSignature *sig, *prev_sig;
477         const char *ptr;
478
479         /* !table is for wrappers: we should really assign their own token to them */
480         if (!table || table == MONO_TABLE_METHOD)
481                 return mono_method_signature (method);
482
483         if (table == MONO_TABLE_METHODSPEC) {
484                 g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) &&
485                           !(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
486                           mono_method_signature (method));
487                 g_assert (method->is_inflated);
488
489                 return mono_method_signature (method);
490         }
491
492         if (method->klass->generic_class)
493                 return mono_method_signature (method);
494
495         if (image->dynamic)
496                 /* FIXME: This might be incorrect for vararg methods */
497                 return mono_method_signature (method);
498
499         mono_loader_lock ();
500         sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
501         mono_loader_unlock ();
502         if (!sig) {
503                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
504
505                 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
506                 mono_metadata_decode_blob_size (ptr, &ptr);
507                 sig = mono_metadata_parse_method_signature_full (
508                         image, context ? context->container : NULL, 0, ptr, NULL);
509
510                 mono_loader_lock ();
511                 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
512                 if (prev_sig) {
513                         /* Somebody got in before us */
514                         /* FIXME: Free sig */
515                         sig = prev_sig;
516                 }
517                 else
518                         g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (token), sig);
519                 mono_loader_unlock ();
520         }
521
522         sig = inflate_generic_signature (image, sig, context);
523
524         return sig;
525 }
526
527 MonoMethodSignature*
528 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
529 {
530         return mono_method_get_signature_full (method, image, token, NULL);
531 }
532
533 static MonoMethod *
534 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context)
535 {
536         MonoClass *klass = NULL;
537         MonoMethod *method = NULL;
538         MonoTableInfo *tables = image->tables;
539         guint32 cols[6];
540         guint32 nindex, class;
541         const char *mname;
542         MonoMethodSignature *sig;
543         const char *ptr;
544
545         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
546         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
547         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
548         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
549                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
550
551         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
552
553         switch (class) {
554         case MONO_MEMBERREF_PARENT_TYPEREF:
555                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
556                 if (!klass) {
557                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
558                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
559                         g_free (name);
560                         return NULL;
561                 }
562                 break;
563         case MONO_MEMBERREF_PARENT_TYPESPEC:
564                 /*
565                  * Parse the TYPESPEC in the parent's context.
566                  */
567                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
568                 if (!klass) {
569                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
570                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
571                         g_free (name);
572                         return NULL;
573                 }
574                 break;
575         case MONO_MEMBERREF_PARENT_TYPEDEF:
576                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
577                 if (!klass) {
578                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
579                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
580                         g_free (name);
581                         return NULL;
582                 }
583                 break;
584         case MONO_MEMBERREF_PARENT_METHODDEF:
585                 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
586         default:
587                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
588                 g_assert_not_reached ();
589         }
590         g_assert (klass);
591         mono_class_init (klass);
592
593         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
594         mono_metadata_decode_blob_size (ptr, &ptr);
595
596         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
597
598         switch (class) {
599         case MONO_MEMBERREF_PARENT_TYPEREF:
600         case MONO_MEMBERREF_PARENT_TYPEDEF:
601                 method = find_method (klass, NULL, mname, sig, klass);
602                 break;
603
604         case MONO_MEMBERREF_PARENT_TYPESPEC: {
605                 MonoType *type;
606                 MonoMethod *result;
607
608                 type = &klass->byval_arg;
609
610                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
611                         MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
612                         method = find_method (in_class, NULL, mname, sig, klass);
613                         break;
614                 }
615
616                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
617                 result->klass = klass;
618                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
619                 result->flags = METHOD_ATTRIBUTE_PUBLIC;
620                 result->signature = sig;
621                 result->name = mname;
622
623                 if (!strcmp (mname, ".ctor")) {
624                         /* we special-case this in the runtime. */
625                         return result;
626                 }
627
628                 if (!strcmp (mname, "Set")) {
629                         g_assert (sig->hasthis);
630                         g_assert (type->data.array->rank + 1 == sig->param_count);
631                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
632                         return result;
633                 }
634
635                 if (!strcmp (mname, "Get")) {
636                         g_assert (sig->hasthis);
637                         g_assert (type->data.array->rank == sig->param_count);
638                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
639                         return result;
640                 }
641
642                 if (!strcmp (mname, "Address")) {
643                         g_assert (sig->hasthis);
644                         g_assert (type->data.array->rank == sig->param_count);
645                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
646                         return result;
647                 }
648
649                 g_assert_not_reached ();
650                 break;
651         }
652         default:
653                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
654                 g_assert_not_reached ();
655         }
656
657         if (!method) {
658                 char *msig = mono_signature_get_desc (sig, FALSE);
659                 GString *s = g_string_new (mname);
660                 if (sig->generic_param_count)
661                         g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
662                 g_string_append_printf (s, "(%s)", msig);
663                 g_free (msig);
664                 msig = g_string_free (s, FALSE);
665
666                 g_warning (
667                         "Missing method %s::%s in assembly %s, referenced in assembly %s",
668                         mono_type_get_name (&klass->byval_arg), msig, klass->image->name, image->name);
669                 g_free (msig);
670                 mono_loader_set_error_method_load (klass, mname);
671         }
672         mono_metadata_free_method_signature (sig);
673
674         return method;
675 }
676
677 static MonoMethod *
678 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
679 {
680         MonoMethod *method, *inflated;
681         MonoTableInfo *tables = image->tables;
682         MonoGenericContext *new_context = NULL;
683         MonoGenericMethod *gmethod;
684         MonoGenericContainer *container = NULL;
685         const char *ptr;
686         guint32 cols [MONO_METHODSPEC_SIZE];
687         guint32 token, nindex, param_count;
688
689         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
690         token = cols [MONO_METHODSPEC_METHOD];
691         nindex = token >> MONO_METHODDEFORREF_BITS;
692
693         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
694
695         mono_metadata_decode_value (ptr, &ptr);
696         ptr++;
697         param_count = mono_metadata_decode_value (ptr, &ptr);
698         g_assert (param_count);
699
700         /*
701          * Be careful with the two contexts here:
702          *
703          * ----------------------------------------
704          * class Foo<S> {
705          *   static void Hello<T> (S s, T t) { }
706          *
707          *   static void Test<U> (U u) {
708          *     Foo<U>.Hello<string> (u, "World");
709          *   }
710          * }
711          * ----------------------------------------
712          *
713          * Let's assume we're currently JITing Foo<int>.Test<long>
714          * (ie. `S' is instantiated as `int' and `U' is instantiated as `long').
715          *
716          * The call to Hello() is encoded with a MethodSpec with a TypeSpec as parent
717          * (MONO_MEMBERREF_PARENT_TYPESPEC).
718          *
719          * The TypeSpec is encoded as `Foo<!!0>', so we need to parse it in the current
720          * context (S=int, U=long) to get the correct `Foo<long>'.
721          * 
722          * After that, we parse the memberref signature in the new context
723          * (S=int, T=uninstantiated) and get the open generic method `Foo<long>.Hello<T>'.
724          *
725          */
726         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
727                 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
728         else
729                 method = method_from_memberref (image, nindex, context);
730
731         method = mono_get_inflated_method (method);
732
733         container = method->generic_container;
734         g_assert (container);
735
736         gmethod = g_new0 (MonoGenericMethod, 1);
737         gmethod->generic_class = method->klass->generic_class;
738         gmethod->container = container;
739
740         new_context = g_new0 (MonoGenericContext, 1);
741         new_context->container = container;
742         new_context->gmethod = gmethod;
743         if (container->parent)
744                 new_context->gclass = container->parent->context.gclass;
745
746         /*
747          * When parsing the methodspec signature, we're in the old context again:
748          *
749          * ----------------------------------------
750          * class Foo {
751          *   static void Hello<T> (T t) { }
752          *
753          *   static void Test<U> (U u) {
754          *     Foo.Hello<U> (u);
755          *   }
756          * }
757          * ----------------------------------------
758          *
759          * Let's assume we're currently JITing "Foo.Test<float>".
760          *
761          * In this case, we already parsed the memberref as "Foo.Hello<T>" and the methodspec
762          * signature is "<!!0>".  This means that we must instantiate the method type parameter
763          * `T' from the new method with the method type parameter `U' from the current context;
764          * ie. instantiate the method as `Foo.Hello<float>.
765          */
766
767         gmethod->inst = mono_metadata_parse_generic_inst (image, context ? context->container : NULL, param_count, ptr, &ptr);
768
769         if (context && gmethod->inst->is_open)
770                 gmethod->inst = mono_metadata_inflate_generic_inst (gmethod->inst, context);
771
772         if (!container->method_hash)
773                 container->method_hash = g_hash_table_new (
774                         (GHashFunc)mono_metadata_generic_method_hash, (GEqualFunc)mono_metadata_generic_method_equal);
775
776         inflated = g_hash_table_lookup (container->method_hash, gmethod);
777         if (inflated) {
778                 g_free (gmethod);
779                 g_free (new_context);
780                 return inflated;
781         }
782
783         context = new_context;
784
785         mono_stats.generics_metadata_size += sizeof (MonoGenericMethod) +
786                 sizeof (MonoGenericContext) + param_count * sizeof (MonoType);
787
788         inflated = mono_class_inflate_generic_method_full (method, method->klass, new_context);
789         g_hash_table_insert (container->method_hash, gmethod, inflated);
790
791         return inflated;
792 }
793
794 typedef struct MonoDllMap MonoDllMap;
795
796 struct MonoDllMap {
797         char *name;
798         char *target;
799         char *dll;
800         MonoDllMap *next;
801 };
802
803 static GHashTable *global_dll_map;
804
805 static int 
806 mono_dllmap_lookup_hash (GHashTable *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
807         MonoDllMap *map, *tmp;
808
809         *rdll = dll;
810
811         if (!dll_map)
812                 return 0;
813
814         mono_loader_lock ();
815
816         map = g_hash_table_lookup (dll_map, dll);
817         if (!map) {
818                 mono_loader_unlock ();
819                 return 0;
820         }
821         *rdll = map->target? map->target: dll;
822
823         for (tmp = map->next; tmp; tmp = tmp->next) {
824                 if (strcmp (func, tmp->name) == 0) {
825                         *rfunc = tmp->name;
826                         if (tmp->dll)
827                                 *rdll = tmp->dll;
828                         mono_loader_unlock ();
829                         return 1;
830                 }
831         }
832         *rfunc = func;
833         mono_loader_unlock ();
834         return 1;
835 }
836
837 static int 
838 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
839 {
840         int res;
841         if (assembly && assembly->dll_map) {
842                 res = mono_dllmap_lookup_hash (assembly->dll_map, dll, func, rdll, rfunc);
843                 if (res)
844                         return res;
845         }
846         return mono_dllmap_lookup_hash (global_dll_map, dll, func, rdll, rfunc);
847 }
848
849 void
850 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc) {
851         MonoDllMap *map, *entry;
852         GHashTable *dll_map = NULL;
853
854         mono_loader_lock ();
855
856         if (!assembly) {
857                 if (!global_dll_map)
858                         global_dll_map = g_hash_table_new (g_str_hash, g_str_equal);
859                 dll_map = global_dll_map;
860         } else {
861                 if (!assembly->dll_map)
862                         assembly->dll_map = g_hash_table_new (g_str_hash, g_str_equal);
863                 dll_map = assembly->dll_map;
864         }
865
866         map = g_hash_table_lookup (dll_map, dll);
867         if (!map) {
868                 map = g_new0 (MonoDllMap, 1);
869                 map->dll = g_strdup (dll);
870                 if (tdll)
871                         map->target = g_strdup (tdll);
872                 g_hash_table_insert (dll_map, map->dll, map);
873         }
874         if (func) {
875                 entry = g_new0 (MonoDllMap, 1);
876                 entry->name = g_strdup (func);
877                 if (tfunc)
878                         entry->target = g_strdup (tfunc);
879                 if (tdll && map->target && strcmp (map->target, tdll))
880                         entry->dll = g_strdup (tdll);
881                 entry->next = map->next;
882                 map->next = entry;
883         }
884
885         mono_loader_unlock ();
886 }
887
888 gpointer
889 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
890 {
891         MonoImage *image = method->klass->image;
892         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
893         MonoTableInfo *tables = image->tables;
894         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
895         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
896         guint32 im_cols [MONO_IMPLMAP_SIZE];
897         guint32 scope_token;
898         const char *import = NULL;
899         const char *orig_scope;
900         const char *new_scope;
901         char *full_name, *file_name;
902         int i;
903         GModule *gmodule = NULL;
904
905         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
906
907         if (piinfo->addr)
908                 return piinfo->addr;
909
910         if (method->klass->image->dynamic) {
911                 MonoReflectionMethodAux *method_aux = 
912                         g_hash_table_lookup (
913                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
914                 if (!method_aux)
915                         return NULL;
916
917                 import = method_aux->dllentry;
918                 orig_scope = method_aux->dll;
919         }
920         else {
921                 if (!piinfo->implmap_idx)
922                         return NULL;
923
924                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
925
926                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
927                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
928                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
929                 orig_scope = mono_metadata_string_heap (image, scope_token);
930         }
931
932         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
933
934         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
935                         "DllImport attempting to load: '%s'.", new_scope);
936
937         if (exc_class) {
938                 *exc_class = NULL;
939                 *exc_arg = NULL;
940         }
941
942         /* we allow a special name to dlopen from the running process namespace */
943         if (strcmp (new_scope, "__Internal") == 0)
944                 gmodule = g_module_open (NULL, G_MODULE_BIND_LAZY);
945
946         /*
947          * Try loading the module using a variety of names
948          */
949         for (i = 0; i < 4; ++i) {
950                 switch (i) {
951                 case 0:
952                         /* Try the original name */
953                         file_name = g_strdup (new_scope);
954                         break;
955                 case 1:
956                         /* Try trimming the .dll extension */
957                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
958                                 file_name = g_strdup (new_scope);
959                                 file_name [strlen (new_scope) - 4] = '\0';
960                         }
961                         else
962                                 continue;
963                         break;
964                 case 2:
965                         if (strstr (new_scope, "lib") != new_scope) {
966                                 file_name = g_strdup_printf ("lib%s", new_scope);
967                         }
968                         else
969                                 continue;
970                         break;
971                 default:
972 #ifndef PLATFORM_WIN32
973                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
974                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
975                             !g_ascii_strcasecmp ("user32", new_scope) ||
976                             !g_ascii_strcasecmp ("kernel", new_scope)) {
977                                 file_name = g_strdup ("libMonoSupportW.so");
978                         } else
979 #endif
980                                     continue;
981 #ifndef PLATFORM_WIN32
982                         break;
983 #endif
984                 }
985
986                 if (!gmodule) {
987                         full_name = g_module_build_path (NULL, file_name);
988                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
989                                         "DllImport loading location: '%s'.", full_name);
990                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
991                         if (!gmodule) {
992                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
993                                                 "DllImport error loading library: '%s'.",
994                                                 g_module_error ());
995                         }
996                         g_free (full_name);
997                 }
998
999                 if (!gmodule) {
1000                         full_name = g_module_build_path (".", file_name);
1001                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1002                                         "DllImport loading library: '%s'.", full_name);
1003                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
1004                         if (!gmodule) {
1005                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1006                                                 "DllImport error loading library '%s'.",
1007                                                 g_module_error ());
1008                         }
1009                         g_free (full_name);
1010                 }
1011
1012                 if (!gmodule) {
1013                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1014                                         "DllImport loading: '%s'.", file_name);
1015                         gmodule=g_module_open (file_name, G_MODULE_BIND_LAZY);
1016                         if (!gmodule) {
1017                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1018                                                 "DllImport error loading library '%s'.",
1019                                                 g_module_error ());
1020                         }
1021                 }
1022
1023                 g_free (file_name);
1024
1025                 if (gmodule)
1026                         break;
1027         }
1028
1029         if (!gmodule) {
1030                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1031                                 "DllImport unable to load library '%s'.",
1032                                 g_module_error ());
1033
1034                 if (exc_class) {
1035                         *exc_class = "DllNotFoundException";
1036                         *exc_arg = new_scope;
1037                 }
1038                 return NULL;
1039         }
1040
1041         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1042                                 "Searching for '%s'.", import);
1043
1044         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1045                 g_module_symbol (gmodule, import, &piinfo->addr); 
1046         } else {
1047                 char *mangled_name = NULL, *mangled_name2 = NULL;
1048                 int mangle_charset;
1049                 int mangle_stdcall;
1050                 int mangle_param_count;
1051 #ifdef PLATFORM_WIN32
1052                 int param_count;
1053 #endif
1054
1055                 /*
1056                  * Search using a variety of mangled names
1057                  */
1058                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1059                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1060                                 gboolean need_param_count = FALSE;
1061 #ifdef PLATFORM_WIN32
1062                                 if (mangle_stdcall > 0)
1063                                         need_param_count = TRUE;
1064 #endif
1065                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1066
1067                                         if (piinfo->addr)
1068                                                 continue;
1069
1070                                         mangled_name = (char*)import;
1071                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1072                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1073                                                 /* Try the mangled name first */
1074                                                 if (mangle_charset == 0)
1075                                                         mangled_name = g_strconcat (import, "W", NULL);
1076                                                 break;
1077                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1078 #ifdef PLATFORM_WIN32
1079                                                 if (mangle_charset == 0)
1080                                                         mangled_name = g_strconcat (import, "W", NULL);
1081 #else
1082                                                 /* Try the mangled name last */
1083                                                 if (mangle_charset == 1)
1084                                                         mangled_name = g_strconcat (import, "A", NULL);
1085 #endif
1086                                                 break;
1087                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1088                                         default:
1089                                                 /* Try the mangled name last */
1090                                                 if (mangle_charset == 1)
1091                                                         mangled_name = g_strconcat (import, "A", NULL);
1092                                                 break;
1093                                         }
1094
1095 #ifdef PLATFORM_WIN32
1096                                         if (mangle_param_count == 0)
1097                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1098                                         else
1099                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1100                                                 param_count = mangle_param_count;
1101
1102                                         /* Try the stdcall mangled name */
1103                                         /* 
1104                                          * gcc under windows creates mangled names without the underscore, but MS.NET
1105                                          * doesn't support it, so we doesn't support it either.
1106                                          */
1107                                         if (mangle_stdcall == 1)
1108                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1109                                         else
1110                                                 mangled_name2 = mangled_name;
1111 #else
1112                                         mangled_name2 = mangled_name;
1113 #endif
1114
1115                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1116                                                                 "Probing '%s'.", mangled_name2);
1117
1118                                         g_module_symbol (gmodule, mangled_name2, &piinfo->addr);
1119
1120                                         if (piinfo->addr)
1121                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1122                                                                         "Found as '%s'.", mangled_name2);
1123
1124                                         if (mangled_name != mangled_name2)
1125                                                 g_free (mangled_name2);
1126                                         if (mangled_name != import)
1127                                                 g_free (mangled_name);
1128                                 }
1129                         }
1130                 }
1131         }
1132
1133         if (!piinfo->addr) {
1134                 if (exc_class) {
1135                         *exc_class = "EntryPointNotFoundException";
1136                         *exc_arg = import;
1137                 }
1138                 return NULL;
1139         }
1140         return piinfo->addr;
1141 }
1142
1143 MonoGenericMethod *
1144 mono_get_shared_generic_method (MonoGenericContainer *container)
1145 {
1146         MonoGenericMethod *gmethod = g_new0 (MonoGenericMethod, 1);
1147         gmethod->container = container;
1148         gmethod->generic_class = container->context.gclass;
1149         gmethod->inst = mono_get_shared_generic_inst (container);
1150
1151         return gmethod;
1152 }
1153
1154 static MonoMethod *
1155 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1156                             MonoGenericContext *context)
1157 {
1158         MonoMethod *result;
1159         int table = mono_metadata_token_table (token);
1160         int idx = mono_metadata_token_index (token);
1161         MonoTableInfo *tables = image->tables;
1162         MonoGenericContainer *generic_container = NULL, *container = NULL;
1163         const char *sig = NULL;
1164         int size, i;
1165         guint32 cols [MONO_TYPEDEF_SIZE];
1166
1167         if (image->dynamic)
1168                 return mono_lookup_dynamic_token (image, token);
1169
1170         if (table != MONO_TABLE_METHOD) {
1171                 if (table == MONO_TABLE_METHODSPEC)
1172                         return method_from_methodspec (image, context, idx);
1173                 if (table != MONO_TABLE_MEMBERREF)
1174                         g_print("got wrong token: 0x%08x\n", token);
1175                 g_assert (table == MONO_TABLE_MEMBERREF);
1176                 result = method_from_memberref (image, idx, context);
1177
1178                 return result;
1179         }
1180
1181         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
1182
1183         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1184             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1185                 result = (MonoMethod *)mono_mempool_alloc0 (image->mempool, sizeof (MonoMethodPInvoke));
1186         else
1187                 result = (MonoMethod *)mono_mempool_alloc0 (image->mempool, sizeof (MonoMethodNormal));
1188
1189         if (!klass) {
1190                 guint32 type = mono_metadata_typedef_from_method (image, token);
1191                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1192         }
1193
1194         result->slot = -1;
1195         result->klass = klass;
1196         result->flags = cols [2];
1197         result->iflags = cols [1];
1198         result->token = token;
1199         result->name = mono_metadata_string_heap (image, cols [3]);
1200
1201         container = klass->generic_container;
1202         generic_container = mono_metadata_load_generic_params (image, token, container);
1203         if (generic_container) {
1204                 MonoGenericContext *context = &generic_container->context;
1205                 if (container)
1206                         context->gclass = container->context.gclass;
1207                 context->gmethod = mono_get_shared_generic_method (generic_container);
1208                 mono_metadata_load_generic_param_constraints (image, token, generic_container);
1209
1210                 for (i = 0; i < generic_container->type_argc; i++) {
1211                         generic_container->type_params [i].method = result;
1212
1213                         mono_class_from_generic_parameter (
1214                                 &generic_container->type_params [i], image, TRUE);
1215                 }
1216
1217                 container = generic_container;
1218         }
1219
1220         if (!sig) /* already taken from the methodref */
1221                 sig = mono_metadata_blob_heap (image, cols [4]);
1222         size = mono_metadata_decode_blob_size (sig, &sig);
1223
1224         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1225                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1226                         result->string_ctor = 1;
1227         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1228                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1229                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1230
1231                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1232                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1233         }
1234
1235         /* FIXME: lazyness for generics too, but how? */
1236         if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
1237             !(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
1238             !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
1239                 gpointer loc = mono_image_rva_map (image, cols [0]);
1240                 g_assert (loc);
1241                 ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (image, container, loc);
1242         }
1243
1244         result->generic_container = generic_container;
1245
1246         return result;
1247 }
1248
1249 MonoMethod *
1250 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1251 {
1252         return mono_get_method_full (image, token, klass, NULL);
1253 }
1254
1255 MonoMethod *
1256 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1257                       MonoGenericContext *context)
1258 {
1259         MonoMethod *result;
1260
1261         /* We do everything inside the lock to prevent creation races */
1262
1263         mono_loader_lock ();
1264
1265         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
1266                 mono_loader_unlock ();
1267                 return result;
1268         }
1269
1270         result = mono_get_method_from_token (image, token, klass, context);
1271
1272         //printf ("GET: %s\n", mono_method_full_name (result, TRUE));
1273
1274         if (!(result && result->is_inflated))
1275                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1276
1277         mono_loader_unlock ();
1278
1279         return result;
1280 }
1281
1282 /**
1283  * mono_get_method_constrained:
1284  *
1285  * This is used when JITing the `constrained.' opcode.
1286  */
1287 MonoMethod *
1288 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1289                              MonoGenericContext *context)
1290 {
1291         MonoMethod *method, *result;
1292         MonoClass *ic = NULL;
1293         MonoGenericContext *class_context = NULL, *method_context = NULL;
1294         MonoMethodSignature *sig;
1295
1296         mono_loader_lock ();
1297
1298         method = mono_get_method_from_token (image, token, NULL, context);
1299         if (!method) {
1300                 mono_loader_unlock ();
1301                 return NULL;
1302         }
1303
1304         mono_class_init (constrained_class);
1305         method = mono_get_inflated_method (method);
1306         sig = mono_method_signature (method);
1307
1308         if (method->is_inflated && sig->generic_param_count) {
1309                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1310                 sig = mono_method_signature (imethod->declaring);
1311                 method_context = imethod->context;
1312         }
1313
1314         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
1315                 ic = method->klass;
1316
1317         if (constrained_class->generic_class)
1318                 class_context = constrained_class->generic_class->context;
1319
1320         result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1321         if (!result) {
1322                 g_warning ("Missing method %s.%s.%s in assembly %s token %x", method->klass->name_space,
1323                            method->klass->name, method->name, image->name, token);
1324                 mono_loader_unlock ();
1325                 return NULL;
1326         }
1327
1328         if (class_context)
1329                 result = mono_class_inflate_generic_method (result, class_context);
1330         if (method_context)
1331                 result = mono_class_inflate_generic_method (result, method_context);
1332
1333         mono_loader_unlock ();
1334         return result;
1335 }
1336
1337 void
1338 mono_free_method  (MonoMethod *method)
1339 {
1340         if (method->signature) {
1341                 /* 
1342                  * FIXME: This causes crashes because the types inside signatures and
1343                  * locals are shared.
1344                  */
1345                 /* mono_metadata_free_method_signature (method->signature); */
1346                 /* g_free (method->signature); */
1347         }
1348
1349         if (method->dynamic) {
1350                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1351
1352                 g_free ((char*)method->name);
1353                 if (mw->method.header)
1354                         g_free ((char*)mw->method.header->code);
1355                 g_free (mw->method_data);
1356         }
1357
1358         if (method->dynamic && !(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
1359                 /* FIXME: Ditto */
1360                 /* mono_metadata_free_mh (((MonoMethodNormal *)method)->header); */
1361                 g_free (((MonoMethodNormal*)method)->header);
1362         }
1363
1364         if (method->dynamic)
1365                 g_free (method);
1366 }
1367
1368 void
1369 mono_method_get_param_names (MonoMethod *method, const char **names)
1370 {
1371         int i, lastp;
1372         MonoClass *klass = method->klass;
1373         MonoTableInfo *methodt;
1374         MonoTableInfo *paramt;
1375         guint32 idx;
1376
1377         if (!mono_method_signature (method)->param_count)
1378                 return;
1379         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1380                 names [i] = "";
1381
1382         if (klass->generic_class) /* copy the names later */
1383                 return;
1384
1385         mono_class_init (klass);
1386
1387         if (klass->image->dynamic) {
1388                 MonoReflectionMethodAux *method_aux = 
1389                         g_hash_table_lookup (
1390                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1391                 if (method_aux && method_aux->param_names) {
1392                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1393                                 if (method_aux->param_names [i + 1])
1394                                         names [i] = method_aux->param_names [i + 1];
1395                 }
1396                 return;
1397         }
1398
1399         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1400         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1401         idx = mono_method_get_index (method);
1402         if (idx > 0) {
1403                 guint32 cols [MONO_PARAM_SIZE];
1404                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1405
1406                 if (idx < methodt->rows)
1407                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1408                 else
1409                         lastp = paramt->rows + 1;
1410                 for (i = param_index; i < lastp; ++i) {
1411                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1412                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1413                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1414                 }
1415                 return;
1416         }
1417 }
1418
1419 guint32
1420 mono_method_get_param_token (MonoMethod *method, int index)
1421 {
1422         MonoClass *klass = method->klass;
1423         MonoTableInfo *methodt;
1424         guint32 idx;
1425
1426         if (klass->generic_class)
1427                 g_assert_not_reached ();
1428
1429         mono_class_init (klass);
1430
1431         if (klass->image->dynamic) {
1432                 g_assert_not_reached ();
1433         }
1434
1435         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1436         idx = mono_method_get_index (method);
1437         if (idx > 0) {
1438                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1439
1440                 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1441         }
1442
1443         return 0;
1444 }
1445
1446 void
1447 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1448 {
1449         int i, lastp;
1450         MonoClass *klass = method->klass;
1451         MonoTableInfo *methodt;
1452         MonoTableInfo *paramt;
1453         guint32 idx;
1454
1455         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1456                 mspecs [i] = NULL;
1457
1458         if (method->klass->image->dynamic) {
1459                 MonoReflectionMethodAux *method_aux = 
1460                         g_hash_table_lookup (
1461                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1462                 if (method_aux && method_aux->param_marshall) {
1463                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1464                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1465                                 if (dyn_specs [i]) {
1466                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1467                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1468                                 }
1469                 }
1470                 return;
1471         }
1472
1473         mono_class_init (klass);
1474
1475         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1476         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1477         idx = mono_method_get_index (method);
1478         if (idx > 0) {
1479                 guint32 cols [MONO_PARAM_SIZE];
1480                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1481
1482                 if (idx < methodt->rows)
1483                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1484                 else
1485                         lastp = paramt->rows + 1;
1486
1487                 for (i = param_index; i < lastp; ++i) {
1488                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1489
1490                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1491                                 const char *tp;
1492                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1493                                 g_assert (tp);
1494                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1495                         }
1496                 }
1497
1498                 return;
1499         }
1500 }
1501
1502 gboolean
1503 mono_method_has_marshal_info (MonoMethod *method)
1504 {
1505         int i, lastp;
1506         MonoClass *klass = method->klass;
1507         MonoTableInfo *methodt;
1508         MonoTableInfo *paramt;
1509         guint32 idx;
1510
1511         if (method->klass->image->dynamic) {
1512                 MonoReflectionMethodAux *method_aux = 
1513                         g_hash_table_lookup (
1514                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1515                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1516                 if (dyn_specs) {
1517                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1518                                 if (dyn_specs [i])
1519                                         return TRUE;
1520                 }
1521                 return FALSE;
1522         }
1523
1524         mono_class_init (klass);
1525
1526         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1527         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1528         idx = mono_method_get_index (method);
1529         if (idx > 0) {
1530                 guint32 cols [MONO_PARAM_SIZE];
1531                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1532
1533                 if (idx + 1 < methodt->rows)
1534                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1535                 else
1536                         lastp = paramt->rows + 1;
1537
1538                 for (i = param_index; i < lastp; ++i) {
1539                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1540
1541                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1542                                 return TRUE;
1543                 }
1544                 return FALSE;
1545         }
1546         return FALSE;
1547 }
1548
1549 gpointer
1550 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1551 {
1552         void **data;
1553         g_assert (method != NULL);
1554         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1555
1556         data = ((MonoMethodWrapper *)method)->method_data;
1557         g_assert (data != NULL);
1558         g_assert (id <= GPOINTER_TO_UINT (*data));
1559         return data [id];
1560 }
1561
1562 static void
1563 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1564         g_error ("stack walk not installed");
1565 }
1566
1567 static MonoStackWalkImpl stack_walk = default_stack_walk;
1568
1569 void
1570 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1571 {
1572         stack_walk (func, TRUE, user_data);
1573 }
1574
1575 void
1576 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1577 {
1578         stack_walk (func, FALSE, user_data);
1579 }
1580
1581 void
1582 mono_install_stack_walk (MonoStackWalkImpl func)
1583 {
1584         stack_walk = func;
1585 }
1586
1587 static gboolean
1588 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1589 {
1590         MonoMethod **dest = data;
1591         *dest = m;
1592         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1593
1594         return managed;
1595 }
1596
1597 MonoMethod*
1598 mono_method_get_last_managed (void)
1599 {
1600         MonoMethod *m = NULL;
1601         stack_walk (last_managed, FALSE, &m);
1602         return m;
1603 }
1604
1605 void
1606 mono_loader_lock (void)
1607 {
1608         EnterCriticalSection (&loader_mutex);
1609 }
1610
1611 void
1612 mono_loader_unlock (void)
1613 {
1614         LeaveCriticalSection (&loader_mutex);
1615 }
1616
1617 MonoMethodSignature*
1618 mono_method_signature (MonoMethod *m)
1619 {
1620         int idx;
1621         int size;
1622         MonoImage* img;
1623         const char *sig;
1624         gboolean can_cache_signature;
1625         MonoGenericContainer *container;
1626         int *pattrs;
1627
1628         if (m->signature)
1629                 return m->signature;
1630
1631         mono_loader_lock ();
1632
1633         if (m->signature) {
1634                 mono_loader_unlock ();
1635                 return m->signature;
1636         }
1637
1638         if (m->is_inflated) {
1639                 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
1640                 MonoMethodSignature *signature;
1641                 /* the lock is recursive */
1642                 signature = mono_method_signature (imethod->declaring);
1643                 m->signature = inflate_generic_signature (imethod->declaring->klass->image, signature, imethod->context);
1644                 mono_loader_unlock ();
1645                 return m->signature;
1646         }
1647
1648         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
1649         idx = mono_metadata_token_index (m->token);
1650         img = m->klass->image;
1651
1652         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
1653
1654         g_assert (!m->klass->generic_class);
1655         container = m->generic_container;
1656         if (!container)
1657                 container = m->klass->generic_container;
1658
1659         /* Generic signatures depend on the container so they cannot be cached */
1660         /* icall/pinvoke signatures cannot be cached cause we modify them below */
1661         can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
1662
1663         /* If the method has parameter attributes, that can modify the signature */
1664         pattrs = mono_metadata_get_param_attrs (img, idx);
1665         if (pattrs) {
1666                 can_cache_signature = FALSE;
1667                 g_free (pattrs);
1668         }
1669
1670         if (can_cache_signature)
1671                 m->signature = g_hash_table_lookup (img->method_signatures, sig);
1672
1673         if (!m->signature) {
1674                 const char *sig_body;
1675
1676                 size = mono_metadata_decode_blob_size (sig, &sig_body);
1677
1678                 m->signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
1679
1680                 if (can_cache_signature)
1681                         g_hash_table_insert (img->method_signatures, (gpointer)sig, m->signature);
1682         }
1683
1684         /* Verify metadata consistency */
1685         if (m->signature->generic_param_count) {
1686                 if (!container || !container->is_method)
1687                         g_error ("Signature claims method has generic parameters, but generic_params table says it doesn't");
1688                 if (container->type_argc != m->signature->generic_param_count)
1689                         g_error ("Inconsistent generic parameter count.  Signature says %d, generic_params table says %d",
1690                                  m->signature->generic_param_count, container->type_argc);
1691         } else if (container && container->is_method && container->type_argc)
1692                 g_error ("generic_params table claims method has generic parameters, but signature says it doesn't");
1693
1694         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1695                 m->signature->pinvoke = 1;
1696         else if ((m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(m->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1697                 MonoCallConvention conv = 0;
1698                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
1699                 m->signature->pinvoke = 1;
1700
1701                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
1702                 case 0: /* no call conv, so using default */
1703                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
1704                         conv = MONO_CALL_DEFAULT;
1705                         break;
1706                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
1707                         conv = MONO_CALL_C;
1708                         break;
1709                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
1710                         conv = MONO_CALL_STDCALL;
1711                         break;
1712                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
1713                         conv = MONO_CALL_THISCALL;
1714                         break;
1715                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
1716                         conv = MONO_CALL_FASTCALL;
1717                         break;
1718                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
1719                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
1720                 default:
1721                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
1722                         g_assert_not_reached ();
1723                 }
1724                 m->signature->call_convention = conv;
1725         }
1726
1727         mono_loader_unlock ();
1728         return m->signature;
1729 }
1730
1731 const char*
1732 mono_method_get_name (MonoMethod *method)
1733 {
1734         return method->name;
1735 }
1736
1737 MonoClass*
1738 mono_method_get_class (MonoMethod *method)
1739 {
1740         return method->klass;
1741 }
1742
1743 guint32
1744 mono_method_get_token (MonoMethod *method)
1745 {
1746         return method->token;
1747 }
1748
1749 MonoMethodHeader*
1750 mono_method_get_header (MonoMethod *method)
1751 {
1752         int idx;
1753         guint32 rva;
1754         MonoImage* img;
1755         gpointer loc;
1756         MonoMethodNormal* mn = (MonoMethodNormal*) method;
1757
1758         if (method->klass->dummy || (method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
1759                 return NULL;
1760
1761 #ifdef G_LIKELY
1762         if (G_LIKELY (mn->header))
1763 #else
1764         if (mn->header)
1765 #endif
1766                 return mn->header;
1767
1768         mono_loader_lock ();
1769
1770         if (mn->header) {
1771                 mono_loader_unlock ();
1772                 return mn->header;
1773         }
1774
1775         if (method->is_inflated) {
1776                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1777                 MonoMethodHeader *header;
1778                 /* the lock is recursive */
1779                 header = mono_method_get_header (imethod->declaring);
1780                 mn->header = inflate_generic_header (header, imethod->context);
1781                 mono_loader_unlock ();
1782                 return mn->header;
1783         }
1784
1785         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
1786         idx = mono_metadata_token_index (method->token);
1787         img = method->klass->image;
1788         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
1789         loc = mono_image_rva_map (img, rva);
1790
1791         g_assert (loc);
1792
1793         mn->header = mono_metadata_parse_mh_full (img, method->generic_container, loc);
1794
1795         mono_loader_unlock ();
1796         return mn->header;
1797 }
1798
1799 guint32
1800 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
1801 {
1802         if (iflags)
1803                 *iflags = method->iflags;
1804         return method->flags;
1805 }
1806
1807 /*
1808  * Find the method index in the metadata methodDef table.
1809  */
1810 guint32
1811 mono_method_get_index (MonoMethod *method) {
1812         MonoClass *klass = method->klass;
1813         int i;
1814
1815         if (method->token)
1816                 return mono_metadata_token_index (method->token);
1817
1818         mono_class_setup_methods (klass);
1819         for (i = 0; i < klass->method.count; ++i) {
1820                 if (method == klass->methods [i])
1821                         return klass->method.first + 1 + i;
1822         }
1823         return 0;
1824 }
1825