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