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