2005-10-04 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);
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);
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);
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);
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 = context ? context->container : NULL;
638         if (container && (container->is_method || container->is_signature))
639                 container = container->parent;
640
641         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
642                 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
643         else
644                 method = method_from_memberref (image, nindex, container, context);
645
646         method = mono_get_inflated_method (method);
647
648         container = ((MonoMethodNormal *) method)->generic_container;
649         g_assert (container);
650
651         gmethod = g_new0 (MonoGenericMethod, 1);
652         gmethod->generic_class = method->klass->generic_class;
653         gmethod->container = container;
654
655         new_context = g_new0 (MonoGenericContext, 1);
656         new_context->container = container;
657         new_context->gmethod = gmethod;
658         if (container->parent)
659                 new_context->gclass = container->parent->context.gclass;
660
661         gmethod->inst = mono_metadata_parse_generic_inst (image, context, param_count, ptr, &ptr);
662
663         if (context)
664                 gmethod->inst = mono_metadata_inflate_generic_inst (gmethod->inst, context);
665
666         if (!container->method_hash)
667                 container->method_hash = g_hash_table_new (
668                         (GHashFunc)mono_metadata_generic_method_hash, (GEqualFunc)mono_metadata_generic_method_equal);
669
670         inflated = g_hash_table_lookup (container->method_hash, gmethod);
671         if (inflated) {
672                 g_free (gmethod);
673                 g_free (new_context);
674                 return inflated;
675         }
676
677         context = new_context;
678
679         mono_stats.generics_metadata_size += sizeof (MonoGenericMethod) +
680                 sizeof (MonoGenericContext) + param_count * sizeof (MonoType);
681
682         inflated = mono_class_inflate_generic_method (method, new_context);
683         g_hash_table_insert (container->method_hash, gmethod, inflated);
684
685         new_context->gclass = inflated->klass->generic_class;
686         return inflated;
687 }
688
689 typedef struct MonoDllMap MonoDllMap;
690
691 struct MonoDllMap {
692         char *name;
693         char *target;
694         char *dll;
695         MonoDllMap *next;
696 };
697
698 static GHashTable *global_dll_map;
699
700 static int 
701 mono_dllmap_lookup_hash (GHashTable *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
702         MonoDllMap *map, *tmp;
703
704         *rdll = dll;
705
706         if (!dll_map)
707                 return 0;
708
709         mono_loader_lock ();
710
711         map = g_hash_table_lookup (dll_map, dll);
712         if (!map) {
713                 mono_loader_unlock ();
714                 return 0;
715         }
716         *rdll = map->target? map->target: dll;
717                 
718         for (tmp = map->next; tmp; tmp = tmp->next) {
719                 if (strcmp (func, tmp->name) == 0) {
720                         *rfunc = tmp->name;
721                         if (tmp->dll)
722                                 *rdll = tmp->dll;
723                         mono_loader_unlock ();
724                         return 1;
725                 }
726         }
727         *rfunc = func;
728         mono_loader_unlock ();
729         return 1;
730 }
731
732 static int 
733 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
734 {
735         int res;
736         if (assembly && assembly->dll_map) {
737                 res = mono_dllmap_lookup_hash (assembly->dll_map, dll, func, rdll, rfunc);
738                 if (res)
739                         return res;
740         }
741         return mono_dllmap_lookup_hash (global_dll_map, dll, func, rdll, rfunc);
742 }
743
744 void
745 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc) {
746         MonoDllMap *map, *entry;
747         GHashTable *dll_map = NULL;
748
749         mono_loader_lock ();
750
751         if (!assembly) {
752                 if (!global_dll_map)
753                         global_dll_map = g_hash_table_new (g_str_hash, g_str_equal);
754                 dll_map = global_dll_map;
755         } else {
756                 if (!assembly->dll_map)
757                         assembly->dll_map = g_hash_table_new (g_str_hash, g_str_equal);
758                 dll_map = assembly->dll_map;
759         }
760
761         map = g_hash_table_lookup (dll_map, dll);
762         if (!map) {
763                 map = g_new0 (MonoDllMap, 1);
764                 map->dll = g_strdup (dll);
765                 if (tdll)
766                         map->target = g_strdup (tdll);
767                 g_hash_table_insert (dll_map, map->dll, map);
768         }
769         if (func) {
770                 entry = g_new0 (MonoDllMap, 1);
771                 entry->name = g_strdup (func);
772                 if (tfunc)
773                         entry->target = g_strdup (tfunc);
774                 if (tdll && map->target && strcmp (map->target, tdll))
775                         entry->dll = g_strdup (tdll);
776                 entry->next = map->next;
777                 map->next = entry;
778         }
779
780         mono_loader_unlock ();
781 }
782
783 gpointer
784 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
785 {
786         MonoImage *image = method->klass->image;
787         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
788         MonoTableInfo *tables = image->tables;
789         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
790         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
791         guint32 im_cols [MONO_IMPLMAP_SIZE];
792         guint32 scope_token;
793         const char *import = NULL;
794         const char *orig_scope;
795         const char *new_scope;
796         char *full_name, *file_name;
797         int i;
798         GModule *gmodule = NULL;
799
800         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
801
802         if (piinfo->addr)
803                 return piinfo->addr;
804
805         if (method->klass->image->dynamic) {
806                 MonoReflectionMethodAux *method_aux = 
807                         g_hash_table_lookup (
808                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
809                 if (!method_aux)
810                         return NULL;
811
812                 import = method_aux->dllentry;
813                 orig_scope = method_aux->dll;
814         }
815         else {
816                 if (!piinfo->implmap_idx)
817                         return NULL;
818
819                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
820
821                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
822                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
823                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
824                 orig_scope = mono_metadata_string_heap (image, scope_token);
825         }
826
827         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
828
829         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
830                         "DllImport attempting to load: '%s'.", new_scope);
831
832         if (exc_class) {
833                 *exc_class = NULL;
834                 *exc_arg = NULL;
835         }
836
837         /* we allow a special name to dlopen from the running process namespace */
838         if (strcmp (new_scope, "__Internal") == 0)
839                 gmodule = g_module_open (NULL, G_MODULE_BIND_LAZY);
840                 
841         /*
842          * Try loading the module using a variety of names
843          */
844         for (i = 0; i < 4; ++i) {
845                 switch (i) {
846                 case 0:
847                         /* Try the original name */
848                         file_name = g_strdup (new_scope);
849                         break;
850                 case 1:
851                         /* Try trimming the .dll extension */
852                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
853                                 file_name = g_strdup (new_scope);
854                                 file_name [strlen (new_scope) - 4] = '\0';
855                         }
856                         else
857                                 continue;
858                         break;
859                 case 2:
860                         if (strstr (new_scope, "lib") != new_scope) {
861                                 file_name = g_strdup_printf ("lib%s", new_scope);
862                         }
863                         else
864                                 continue;
865                         break;
866                 default:
867 #ifndef PLATFORM_WIN32
868                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
869                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
870                             !g_ascii_strcasecmp ("user32", new_scope) ||
871                             !g_ascii_strcasecmp ("kernel", new_scope)) {
872                                 file_name = g_strdup ("libMonoSupportW.so");
873                         } else
874 #endif
875                                     continue;
876 #ifndef PLATFORM_WIN32
877                         break;
878 #endif
879                 }
880
881                 if (!gmodule) {
882                         full_name = g_module_build_path (NULL, file_name);
883                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
884                                         "DllImport loading location: '%s'.", full_name);
885                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
886                         if (!gmodule) {
887                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
888                                                 "DllImport error loading library: '%s'.",
889                                                 g_module_error ());
890                         }
891                         g_free (full_name);
892                 }
893
894                 if (!gmodule) {
895                         full_name = g_module_build_path (".", file_name);
896                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
897                                         "DllImport loading library: '%s'.", full_name);
898                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
899                         if (!gmodule) {
900                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
901                                                 "DllImport error loading library '%s'.",
902                                                 g_module_error ());
903                         }
904                         g_free (full_name);
905                 }
906
907                 if (!gmodule) {
908                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
909                                         "DllImport loading: '%s'.", file_name);
910                         gmodule=g_module_open (file_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                 }
917
918                 g_free (file_name);
919
920                 if (gmodule)
921                         break;
922         }
923
924         if (!gmodule) {
925                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
926                                 "DllImport unable to load library '%s'.",
927                                 g_module_error ());
928
929                 if (exc_class) {
930                         *exc_class = "DllNotFoundException";
931                         *exc_arg = new_scope;
932                 }
933                 return NULL;
934         }
935
936         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
937                                 "Searching for '%s'.", import);
938
939         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
940                 g_module_symbol (gmodule, import, &piinfo->addr); 
941         } else {
942                 char *mangled_name = NULL, *mangled_name2 = NULL;
943                 int mangle_charset;
944                 int mangle_stdcall;
945                 int mangle_param_count;
946 #ifdef PLATFORM_WIN32
947                 int param_count;
948 #endif
949
950                 /*
951                  * Search using a variety of mangled names
952                  */
953                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
954                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
955                                 gboolean need_param_count = FALSE;
956 #ifdef PLATFORM_WIN32
957                                 if (mangle_stdcall > 0)
958                                         need_param_count = TRUE;
959 #endif
960                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
961
962                                         if (piinfo->addr)
963                                                 continue;
964
965                                         mangled_name = (char*)import;
966                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
967                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
968                                                 /* Try the mangled name first */
969                                                 if (mangle_charset == 0)
970                                                         mangled_name = g_strconcat (import, "W", NULL);
971                                                 break;
972                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
973 #ifdef PLATFORM_WIN32
974                                                 if (mangle_charset == 0)
975                                                         mangled_name = g_strconcat (import, "W", NULL);
976 #endif
977                                                 break;
978                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
979                                         default:
980                                                 /* Try the mangled name last */
981                                                 if (mangle_charset == 1)
982                                                         mangled_name = g_strconcat (import, "A", NULL);
983                                                 break;
984                                         }
985
986 #ifdef PLATFORM_WIN32
987                                         if (mangle_param_count == 0)
988                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
989                                         else
990                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
991                                                 param_count = mangle_param_count;
992
993                                         /* Try the stdcall mangled name */
994                                         /* 
995                                          * gcc under windows creates mangled names without the underscore, but MS.NET
996                                          * doesn't support it, so we doesn't support it either.
997                                          */
998                                         if (mangle_stdcall == 1)
999                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1000                                         else
1001                                                 mangled_name2 = mangled_name;
1002 #else
1003                                         mangled_name2 = mangled_name;
1004 #endif
1005
1006                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1007                                                                 "Probing '%s'.", mangled_name2);
1008
1009                                         g_module_symbol (gmodule, mangled_name2, &piinfo->addr);
1010
1011                                         if (piinfo->addr)
1012                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1013                                                                         "Found as '%s'.", mangled_name2);
1014
1015                                         if (mangled_name != mangled_name2)
1016                                                 g_free (mangled_name2);
1017                                         if (mangled_name != import)
1018                                                 g_free (mangled_name);
1019                                 }
1020                         }
1021                 }
1022         }
1023
1024         if (!piinfo->addr) {
1025                 if (exc_class) {
1026                         *exc_class = "EntryPointNotFoundException";
1027                         *exc_arg = import;
1028                 }
1029                 return NULL;
1030         }
1031         return piinfo->addr;
1032 }
1033
1034 static MonoMethod *
1035 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1036                             MonoGenericContext *context)
1037 {
1038         MonoMethod *result;
1039         int table = mono_metadata_token_table (token);
1040         int idx = mono_metadata_token_index (token);
1041         MonoTableInfo *tables = image->tables;
1042         MonoGenericContainer *generic_container = NULL, *container = NULL;
1043         const char *sig = NULL;
1044         int size, i;
1045         guint32 cols [MONO_TYPEDEF_SIZE];
1046
1047         if (image->dynamic)
1048                 return mono_lookup_dynamic_token (image, token);
1049
1050         if (table != MONO_TABLE_METHOD) {
1051                 if (table == MONO_TABLE_METHODSPEC)
1052                         return method_from_methodspec (image, context, idx);
1053                 if (table != MONO_TABLE_MEMBERREF)
1054                         g_print("got wrong token: 0x%08x\n", token);
1055                 g_assert (table == MONO_TABLE_MEMBERREF);
1056                 result = method_from_memberref (image, idx, context, context);
1057
1058                 return result;
1059         }
1060
1061         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
1062
1063         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1064             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1065                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
1066         else 
1067                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
1068         
1069         result->slot = -1;
1070         result->klass = klass;
1071         result->flags = cols [2];
1072         result->iflags = cols [1];
1073         result->token = token;
1074         result->name = mono_metadata_string_heap (image, cols [3]);
1075
1076         if (klass)
1077                 container = klass->generic_container;
1078
1079         if (!(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
1080             (!(cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) || cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1081                 generic_container = mono_metadata_load_generic_params (image, token, container);
1082                 if (generic_container) {
1083                         mono_metadata_load_generic_param_constraints (image, token, generic_container);
1084                         container = generic_container;
1085                 }
1086         }
1087
1088         if (!sig) /* already taken from the methodref */
1089                 sig = mono_metadata_blob_heap (image, cols [4]);
1090         size = mono_metadata_decode_blob_size (sig, &sig);
1091         
1092         /* there are generic params, or a container. FIXME: be lazy here for generics*/
1093         if (* sig & 0x10 || container) {
1094                 result->signature = mono_metadata_parse_method_signature_full (
1095                         image, container, idx, sig, NULL);
1096
1097                 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1098                         result->signature->pinvoke = 1;
1099         }
1100
1101         if (!result->klass) {
1102                 guint32 type = mono_metadata_typedef_from_method (image, token);
1103                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1104         }
1105
1106         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1107                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1108                         result->string_ctor = 1;
1109         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1110                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1111                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1112                 
1113                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1114                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1115         } else {
1116                 if (result->signature && result->signature->generic_param_count) {
1117                         MonoMethodSignature *sig = result->signature;
1118
1119                         for (i = 0; i < sig->generic_param_count; i++) {
1120                                 generic_container->type_params [i].method = result;
1121
1122                                 mono_class_from_generic_parameter (
1123                                         &generic_container->type_params [i], image, TRUE);
1124                         }
1125
1126                         if (sig->ret->type == MONO_TYPE_MVAR) {
1127                                 int num = sig->ret->data.generic_param->num;
1128                                 sig->ret->data.generic_param = &generic_container->type_params [num];
1129                         }
1130
1131                         for (i = 0; i < sig->param_count; i++) {
1132                                 MonoType *t = sig->params [i];
1133                                 if (t->type == MONO_TYPE_MVAR) {
1134                                         int num = t->data.generic_param->num;
1135                                         sig->params [i]->data.generic_param = &generic_container->type_params [num];
1136                                 }
1137                         }
1138                 }
1139                 
1140                 /* FIXME: lazyness for generics too, but how? */
1141                 if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
1142                     !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
1143                         gpointer loc = mono_image_rva_map (image, cols [0]);
1144                         g_assert (loc);
1145                         ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (
1146                                 image, (MonoGenericContext *) container, loc);
1147                 }
1148                 
1149                 ((MonoMethodNormal *) result)->generic_container = generic_container;
1150         }
1151
1152         return result;
1153 }
1154
1155 MonoMethod *
1156 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1157 {
1158         return mono_get_method_full (image, token, klass, NULL);
1159 }
1160
1161 MonoMethod *
1162 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1163                       MonoGenericContext *context)
1164 {
1165         MonoMethod *result;
1166
1167         /* We do everything inside the lock to prevent creation races */
1168
1169         mono_loader_lock ();
1170
1171         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
1172                 mono_loader_unlock ();
1173                 return result;
1174         }
1175
1176         result = mono_get_method_from_token (image, token, klass, context);
1177
1178         //printf ("GET: %s\n", mono_method_full_name (result, TRUE));
1179
1180         if (!(result && result->is_inflated))
1181                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1182
1183         mono_loader_unlock ();
1184
1185         return result;
1186 }
1187
1188 MonoMethod *
1189 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1190                              MonoGenericContext *context)
1191 {
1192         MonoMethod *method, *result;
1193         MonoClass *ic = NULL;
1194         MonoGenericClass *gclass = NULL;
1195
1196         mono_loader_lock ();
1197
1198         method = mono_get_method_from_token (image, token, NULL, context);
1199         if (!method) {
1200                 mono_loader_unlock ();
1201                 return NULL;
1202         }
1203
1204         mono_class_init (constrained_class);
1205         method = mono_get_inflated_method (method);
1206
1207         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
1208                 ic = method->klass;
1209
1210         if (constrained_class->generic_class)
1211                 gclass = constrained_class->generic_class;
1212
1213         result = find_method (
1214                 constrained_class, ic, method->name, mono_method_signature (method),
1215                 context ? context->container : NULL);
1216         if (!result)
1217                 g_warning ("Missing method %s in assembly %s token %x", method->name,
1218                            image->name, token);
1219
1220         if (gclass)
1221                 result = mono_class_inflate_generic_method (result, gclass->context);
1222
1223         mono_loader_unlock ();
1224         return result;
1225 }
1226
1227 void
1228 mono_free_method  (MonoMethod *method)
1229 {
1230         if (method->signature) {
1231                 /* 
1232                  * FIXME: This causes crashes because the types inside signatures and
1233                  * locals are shared.
1234                  */
1235                 /* mono_metadata_free_method_signature (method->signature); */
1236                 g_free (method->signature);
1237         }
1238
1239         if (method->dynamic) {
1240                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1241
1242                 g_free ((char*)method->name);
1243                 if (mw->method.header)
1244                         g_free ((char*)mw->method.header->code);
1245                 g_free (mw->method_data);
1246         }
1247
1248         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
1249                 /* FIXME: Ditto */
1250                 /* mono_metadata_free_mh (((MonoMethodNormal *)method)->header); */
1251                 g_free (((MonoMethodNormal*)method)->header);
1252         }
1253
1254         g_free (method);
1255 }
1256
1257 void
1258 mono_method_get_param_names (MonoMethod *method, const char **names)
1259 {
1260         int i, lastp;
1261         MonoClass *klass = method->klass;
1262         MonoTableInfo *methodt;
1263         MonoTableInfo *paramt;
1264         guint32 idx;
1265
1266         if (!mono_method_signature (method)->param_count)
1267                 return;
1268         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1269                 names [i] = "";
1270
1271         if (klass->generic_class) /* copy the names later */
1272                 return;
1273
1274         mono_class_init (klass);
1275
1276         if (klass->image->dynamic) {
1277                 MonoReflectionMethodAux *method_aux = 
1278                         g_hash_table_lookup (
1279                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1280                 if (method_aux && method_aux->param_names) {
1281                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1282                                 if (method_aux->param_names [i + 1])
1283                                         names [i] = method_aux->param_names [i + 1];
1284                 }
1285                 return;
1286         }
1287
1288         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1289         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1290         idx = mono_method_get_index (method);
1291         if (idx > 0) {
1292                 guint32 cols [MONO_PARAM_SIZE];
1293                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1294
1295                 if (idx < methodt->rows)
1296                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1297                 else
1298                         lastp = paramt->rows + 1;
1299                 for (i = param_index; i < lastp; ++i) {
1300                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1301                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1302                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1303                 }
1304                 return;
1305         }
1306 }
1307
1308 guint32
1309 mono_method_get_param_token (MonoMethod *method, int index)
1310 {
1311         MonoClass *klass = method->klass;
1312         MonoTableInfo *methodt;
1313         guint32 idx;
1314
1315         if (klass->generic_class)
1316                 g_assert_not_reached ();
1317
1318         mono_class_init (klass);
1319
1320         if (klass->image->dynamic) {
1321                 g_assert_not_reached ();
1322         }
1323
1324         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1325         idx = mono_method_get_index (method);
1326         if (idx > 0) {
1327                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1328
1329                 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1330         }
1331
1332         return 0;
1333 }
1334
1335 void
1336 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1337 {
1338         int i, lastp;
1339         MonoClass *klass = method->klass;
1340         MonoTableInfo *methodt;
1341         MonoTableInfo *paramt;
1342         guint32 idx;
1343
1344         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1345                 mspecs [i] = NULL;
1346
1347         if (method->klass->image->dynamic) {
1348                 MonoReflectionMethodAux *method_aux = 
1349                         g_hash_table_lookup (
1350                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1351                 if (method_aux && method_aux->param_marshall) {
1352                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1353                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1354                                 if (dyn_specs [i]) {
1355                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1356                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1357                                 }
1358                 }
1359                 return;
1360         }
1361
1362         mono_class_init (klass);
1363
1364         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1365         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1366         idx = mono_method_get_index (method);
1367         if (idx > 0) {
1368                 guint32 cols [MONO_PARAM_SIZE];
1369                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1370
1371                 if (idx < methodt->rows)
1372                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1373                 else
1374                         lastp = paramt->rows + 1;
1375
1376                 for (i = param_index; i < lastp; ++i) {
1377                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1378
1379                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1380                                 const char *tp;
1381                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1382                                 g_assert (tp);
1383                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1384                         }
1385                 }
1386
1387                 return;
1388         }
1389 }
1390
1391 gboolean
1392 mono_method_has_marshal_info (MonoMethod *method)
1393 {
1394         int i, lastp;
1395         MonoClass *klass = method->klass;
1396         MonoTableInfo *methodt;
1397         MonoTableInfo *paramt;
1398         guint32 idx;
1399
1400         if (method->klass->image->dynamic) {
1401                 MonoReflectionMethodAux *method_aux = 
1402                         g_hash_table_lookup (
1403                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1404                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1405                 if (dyn_specs) {
1406                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1407                                 if (dyn_specs [i])
1408                                         return TRUE;
1409                 }
1410                 return FALSE;
1411         }
1412
1413         mono_class_init (klass);
1414
1415         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1416         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1417         idx = mono_method_get_index (method);
1418         if (idx > 0) {
1419                 guint32 cols [MONO_PARAM_SIZE];
1420                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1421                 
1422                 if (idx + 1 < methodt->rows)
1423                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1424                 else
1425                         lastp = paramt->rows + 1;
1426
1427                 for (i = param_index; i < lastp; ++i) {
1428                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1429
1430                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1431                                 return TRUE;
1432                 }
1433                 return FALSE;
1434         }
1435         return FALSE;
1436 }
1437
1438 gpointer
1439 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1440 {
1441         void **data;
1442         g_assert (method != NULL);
1443         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1444
1445         data = ((MonoMethodWrapper *)method)->method_data;
1446         g_assert (data != NULL);
1447         g_assert (id <= GPOINTER_TO_UINT (*data));
1448         return data [id];
1449 }
1450
1451 static void
1452 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1453         g_error ("stack walk not installed");
1454 }
1455
1456 static MonoStackWalkImpl stack_walk = default_stack_walk;
1457
1458 void
1459 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1460 {
1461         stack_walk (func, TRUE, user_data);
1462 }
1463
1464 void
1465 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1466 {
1467         stack_walk (func, FALSE, user_data);
1468 }
1469
1470 void
1471 mono_install_stack_walk (MonoStackWalkImpl func)
1472 {
1473         stack_walk = func;
1474 }
1475
1476 static gboolean
1477 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1478 {
1479         MonoMethod **dest = data;
1480         *dest = m;
1481         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1482
1483         return managed;
1484 }
1485
1486 MonoMethod*
1487 mono_method_get_last_managed (void)
1488 {
1489         MonoMethod *m = NULL;
1490         stack_walk (last_managed, FALSE, &m);
1491         return m;
1492 }
1493
1494 void
1495 mono_loader_lock (void)
1496 {
1497         EnterCriticalSection (&loader_mutex);
1498 }
1499
1500 void
1501 mono_loader_unlock (void)
1502 {
1503         LeaveCriticalSection (&loader_mutex);
1504 }
1505
1506 MonoMethodSignature* 
1507 mono_method_signature (MonoMethod *m)
1508 {
1509         m = mono_get_inflated_method (m);
1510         return mono_method_signature_full (m, NULL);
1511 }
1512
1513 MonoMethodSignature* 
1514 mono_method_signature_full (MonoMethod *m, MonoGenericContainer *container)
1515 {
1516         int idx;
1517         int size;
1518         MonoImage* img;
1519         const char *sig;
1520         
1521         if (m->signature)
1522                 return m->signature;
1523                 
1524         mono_loader_lock ();
1525         
1526         if (m->signature) {
1527                 mono_loader_unlock ();
1528                 return m->signature;
1529         }
1530         
1531         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
1532         idx = mono_metadata_token_index (m->token);
1533         img = m->klass->image;
1534         
1535         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
1536         size = mono_metadata_decode_blob_size (sig, &sig);
1537         
1538         m->signature = mono_metadata_parse_method_signature_full (img, container, idx, sig, NULL);
1539         
1540         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1541                 m->signature->pinvoke = 1;
1542         else if ((m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(m->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1543                 MonoCallConvention conv = 0;
1544                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
1545                 m->signature->pinvoke = 1;
1546                 
1547                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
1548                 case 0: /* no call conv, so using default */
1549                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
1550                         conv = MONO_CALL_DEFAULT;
1551                         break;
1552                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
1553                         conv = MONO_CALL_C;
1554                         break;
1555                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
1556                         conv = MONO_CALL_STDCALL;
1557                         break;
1558                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
1559                         conv = MONO_CALL_THISCALL;
1560                         break;
1561                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
1562                         conv = MONO_CALL_FASTCALL;
1563                         break;
1564                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
1565                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
1566                 default:
1567                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
1568                         g_assert_not_reached ();
1569                 }       
1570                 m->signature->call_convention = conv;
1571         }
1572         
1573         mono_loader_unlock ();
1574         return m->signature;
1575 }
1576
1577 const char*
1578 mono_method_get_name (MonoMethod *method)
1579 {
1580         return method->name;
1581 }
1582
1583 MonoClass*
1584 mono_method_get_class (MonoMethod *method)
1585 {
1586         return method->klass;
1587 }
1588
1589 guint32
1590 mono_method_get_token (MonoMethod *method)
1591 {
1592         return method->token;
1593 }
1594
1595 MonoMethodHeader* 
1596 mono_method_get_header (MonoMethod *method)
1597 {
1598         int idx;
1599         guint32 rva;
1600         MonoImage* img;
1601         gpointer loc;
1602         MonoMethodNormal* mn = (MonoMethodNormal*) method;
1603         
1604 #ifdef G_LIKELY
1605         if (G_LIKELY (mn->header))
1606 #else
1607         if (mn->header)
1608 #endif
1609                 return mn->header;
1610         
1611         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))
1612                 return NULL;
1613         
1614         mono_loader_lock ();
1615         
1616         if (mn->header) {
1617                 mono_loader_unlock ();
1618                 return mn->header;
1619         }
1620         
1621         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
1622         idx = mono_metadata_token_index (method->token);
1623         img = method->klass->image;
1624         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
1625         loc = mono_image_rva_map (img, rva);
1626         
1627         g_assert (loc);
1628         
1629         mn->header = mono_metadata_parse_mh_full (img, (MonoGenericContext *) mn->generic_container, loc);
1630         
1631         mono_loader_unlock ();
1632         return mn->header;
1633 }
1634
1635 guint32
1636 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
1637 {
1638         if (iflags)
1639                 *iflags = method->iflags;
1640         return method->flags;
1641 }
1642
1643 /*
1644  * Find the method index in the metadata methodDef table.
1645  */
1646 guint32
1647 mono_method_get_index (MonoMethod *method) {
1648         MonoClass *klass = method->klass;
1649         int i;
1650
1651         if (method->token)
1652                 return mono_metadata_token_index (method->token);
1653
1654         mono_class_setup_methods (klass);
1655         for (i = 0; i < klass->method.count; ++i) {
1656                 if (method == klass->methods [i])
1657                         return klass->method.first + 1 + i;
1658         }
1659         return 0;
1660 }
1661