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