Use a #define to enable/disable the finalizer thread.
[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/loader.h>
32 #include <mono/metadata/class.h>
33 #include <mono/metadata/debug-helpers.h>
34
35 static gboolean dummy_icall = TRUE;
36
37 MonoDefaults mono_defaults;
38
39 static GHashTable *icall_hash = NULL;
40
41 void
42 mono_add_internal_call (const char *name, gconstpointer method)
43 {
44         if (!icall_hash) {
45                 dummy_icall = FALSE;
46                 icall_hash = g_hash_table_new (g_str_hash , g_str_equal);
47         }
48
49         g_hash_table_insert (icall_hash, g_strdup (name), method);
50 }
51
52 static void
53 ves_icall_dummy (void)
54 {
55         g_warning ("the mono runtime is not initialized");
56         g_assert_not_reached ();
57 }
58
59 gpointer
60 mono_lookup_internal_call (MonoMethod *method)
61 {
62         char *name;
63         char *tmpsig;
64         gpointer res;
65
66         if (dummy_icall)
67                 return ves_icall_dummy;
68
69         if (!method) {
70                 g_warning ("can't resolve internal call, method is null");
71         }
72
73         if (!icall_hash) {
74                 g_warning ("icall_hash not initialized");
75                 g_assert_not_reached ();
76         }
77
78         if (*method->klass->name_space)
79                 name = g_strconcat (method->klass->name_space, ".", method->klass->name, "::", method->name, NULL);
80         else
81                 name = g_strconcat (method->klass->name, "::", method->name, NULL);
82         if (!(res = g_hash_table_lookup (icall_hash, name))) {
83                 /* trying to resolve with full signature */
84                 g_free (name);
85         
86                 tmpsig = mono_signature_get_desc(method->signature, TRUE);
87                 if (*method->klass->name_space)
88                         name = g_strconcat (method->klass->name_space, ".", method->klass->name, "::", method->name, "(", tmpsig, ")", NULL);
89                 else
90                         name = g_strconcat (method->klass->name, "::", method->name, "(", tmpsig, ")", NULL);
91                 if (!(res = g_hash_table_lookup (icall_hash, name))) {
92                         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", name);
93                         g_print ("\nYour mono runtime and corlib are out of sync.\n");
94                         g_print ("When you update one from cvs you need to update, compile and install\nthe other too.\n");
95                         g_print ("Do not report this as a bug unless you're sure you have updated correctly:\nyou probably have a broken mono install.\n");
96                         g_print ("If you see other errors or faults after this message they are probably related\n");
97                         g_print ("and you need to fix your mono install first.\n");
98
99                         g_free (name);
100                         g_free (tmpsig);
101
102                         return NULL;
103                 }
104
105                 g_free(tmpsig);
106         }
107
108         g_free (name);
109
110         return res;
111 }
112
113 MonoClassField*
114 mono_field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass)
115 {
116         MonoClass *klass;
117         MonoTableInfo *tables = image->tables;
118         guint32 cols[6];
119         guint32 nindex, class;
120         const char *fname;
121         const char *ptr;
122         guint32 idx = mono_metadata_token_index (token);
123
124         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
125         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
126         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
127
128         fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
129         
130         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
131         mono_metadata_decode_blob_size (ptr, &ptr);
132         /* we may want to check the signature here... */
133
134         switch (class) {
135         case MEMBERREF_PARENT_TYPEREF:
136                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
137                 if (!klass) {
138                         g_warning ("Missing field %s in typeref index %d", fname, nindex);
139                         return NULL;
140                 }
141                 mono_class_init (klass);
142                 if (retklass)
143                         *retklass = klass;
144                 return mono_class_get_field_from_name (klass, fname);
145         default:
146                 return NULL;
147         }
148 }
149
150 MonoClassField*
151 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass)
152 {
153         MonoClass *k;
154         guint32 type;
155         
156         if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
157                 return mono_field_from_memberref (image, token, retklass);
158
159         type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
160         if (!type)
161                 return NULL;
162         k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
163         mono_class_init (k);
164         if (!k)
165                 return NULL;
166         if (retklass)
167                 *retklass = k;
168         return mono_class_get_field (k, token);
169 }
170
171 static MonoMethod *
172 find_method (MonoClass *klass, const char* name, MonoMethodSignature *sig)
173 {
174         int i;
175         while (klass) {
176                 /* mostly dumb search for now */
177                 for (i = 0; i < klass->method.count; ++i) {
178                         MonoMethod *m = klass->methods [i];
179                         if (!strcmp (name, m->name)) {
180                                 if (mono_metadata_signature_equal (sig, m->signature))
181                                         return m;
182                         }
183                 }
184                 klass = klass->parent;
185         }
186         return NULL;
187
188 }
189
190 static MonoMethod *
191 method_from_memberref (MonoImage *image, guint32 idx)
192 {
193         MonoClass *klass;
194         MonoMethod *method;
195         MonoTableInfo *tables = image->tables;
196         guint32 cols[6];
197         guint32 nindex, class;
198         const char *mname;
199         MonoMethodSignature *sig;
200         const char *ptr;
201
202         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
203         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
204         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
205         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
206                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
207
208         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
209         
210         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
211         mono_metadata_decode_blob_size (ptr, &ptr);
212         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
213
214         switch (class) {
215         case MEMBERREF_PARENT_TYPEREF:
216                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
217                 if (!klass) {
218                         g_warning ("Missing method %s in assembly %s typeref index %d", mname, image->name, nindex);
219                         mono_metadata_free_method_signature (sig);
220                         return NULL;
221                 }
222                 mono_class_init (klass);
223                 method = find_method (klass, mname, sig);
224                 if (!method)
225                         g_warning ("Missing method %s in assembly %s typeref index %d", mname, image->name, nindex);
226                 mono_metadata_free_method_signature (sig);
227                 return method;
228         case MEMBERREF_PARENT_TYPESPEC: {
229                 guint32 bcols [MONO_TYPESPEC_SIZE];
230                 guint32 len;
231                 MonoType *type;
232                 MonoMethod *result;
233
234                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
235                                           bcols, MONO_TYPESPEC_SIZE);
236                 ptr = mono_metadata_blob_heap (image, bcols [MONO_TYPESPEC_SIGNATURE]);
237                 len = mono_metadata_decode_value (ptr, &ptr);   
238                 type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
239
240                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY)
241                         g_assert_not_reached ();                
242
243                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
244                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_SPEC | nindex);
245                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
246                 result->signature = sig;
247                 result->name = mname;
248
249                 if (!strcmp (mname, ".ctor")) {
250                         /* we special-case this in the runtime. */
251                         result->addr = NULL;
252                         return result;
253                 }
254                 
255                 if (!strcmp (mname, "Set")) {
256                         g_assert (sig->hasthis);
257                         g_assert (type->data.array->rank + 1 == sig->param_count);
258                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
259                         result->addr = NULL;
260                         return result;
261                 }
262
263                 if (!strcmp (mname, "Get")) {
264                         g_assert (sig->hasthis);
265                         g_assert (type->data.array->rank == sig->param_count);
266                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
267                         result->addr = NULL;
268                         return result;
269                 }
270
271                 if (!strcmp (mname, "Address")) {
272                         g_assert (sig->hasthis);
273                         g_assert (type->data.array->rank == sig->param_count);
274                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
275                         result->addr = NULL;
276                         return result;
277                 }
278
279                 g_assert_not_reached ();
280                 break;
281         }
282         default:
283                 g_assert_not_reached ();
284         }
285
286         return NULL;
287 }
288
289 typedef struct MonoDllMap MonoDllMap;
290
291 struct MonoDllMap {
292         char *name;
293         char *target;
294         char *dll;
295         MonoDllMap *next;
296 };
297
298 static GHashTable *dll_map;
299
300 int 
301 mono_dllmap_lookup (const char *dll, const char* func, const char **rdll, const char **rfunc) {
302         MonoDllMap *map, *tmp;
303
304         if (!dll_map)
305                 return 0;
306         map = g_hash_table_lookup (dll_map, dll);
307         if (!map)
308                 return 0;
309         *rdll = map->target? map->target: dll;
310                 
311         for (tmp = map->next; tmp; tmp = tmp->next) {
312                 if (strcmp (func, tmp->name) == 0) {
313                         *rfunc = tmp->name;
314                         if (tmp->dll)
315                                 *rdll = tmp->dll;
316                         return 1;
317                 }
318         }
319         *rfunc = func;
320         return 1;
321 }
322
323 void
324 mono_dllmap_insert (const char *dll, const char *func, const char *tdll, const char *tfunc) {
325         MonoDllMap *map, *entry;
326
327         if (!dll_map)
328                 dll_map = g_hash_table_new (g_str_hash, g_str_equal);
329
330         map = g_hash_table_lookup (dll_map, dll);
331         if (!map) {
332                 map = g_new0 (MonoDllMap, 1);
333                 map->dll = g_strdup (dll);
334                 if (tdll)
335                         map->target = g_strdup (tdll);
336                 g_hash_table_insert (dll_map, map->dll, map);
337         }
338         if (func) {
339                 entry = g_new0 (MonoDllMap, 1);
340                 entry->name = g_strdup (func);
341                 if (tfunc)
342                         entry->target = g_strdup (tfunc);
343                 if (tdll && map->target && strcmp (map->target, tdll))
344                         entry->dll = g_strdup (tdll);
345                 entry->next = map->next;
346                 map->next = entry;
347         }
348 }
349
350 gpointer
351 mono_lookup_pinvoke_call (MonoMethod *method)
352 {
353         MonoImage *image = method->klass->image;
354         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
355         MonoTableInfo *tables = image->tables;
356         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
357         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
358         guint32 im_cols [MONO_IMPLMAP_SIZE];
359         guint32 scope_token;
360         const char *import = NULL;
361         const char *scope = NULL;
362         char *full_name;
363         GModule *gmodule;
364
365         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
366
367         if (method->addr)
368                 return method->addr;
369         if (!piinfo->implmap_idx)
370                 return NULL;
371         
372         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
373
374         piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
375         import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
376         scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
377         scope = mono_metadata_string_heap (image, scope_token);
378
379         mono_dllmap_lookup (scope, import, &scope, &import);
380
381         full_name = g_module_build_path (NULL, scope);
382         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
383
384         if (!gmodule) {
385                 gchar *error = g_strdup (g_module_error ());
386                 if (!(gmodule=g_module_open (scope, G_MODULE_BIND_LAZY))) {
387                         g_warning ("Failed to load library %s (%s): %s", full_name, scope, error);
388                         g_free (error);
389                         g_free (full_name);
390                         return NULL;
391                 }
392                 g_free (error);
393         }
394         g_free (full_name);
395
396         g_module_symbol (gmodule, import, &method->addr); 
397
398         if (!method->addr) {
399                 g_warning ("Failed to load function %s from %s", import, scope);
400                 return NULL;
401         }
402         return method->addr;
403 }
404
405 MonoMethod *
406 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
407 {
408         MonoMethod *result;
409         int table = mono_metadata_token_table (token);
410         int idx = mono_metadata_token_index (token);
411         MonoTableInfo *tables = image->tables;
412         const char *loc, *sig = NULL;
413         int size;
414         guint32 cols [MONO_TYPEDEF_SIZE];
415
416         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token))))
417                         return result;
418
419         if (table != MONO_TABLE_METHOD) {
420                 if (table != MONO_TABLE_MEMBERREF)
421                         g_print("got wrong token: 0x%08x\n", token);
422                 g_assert (table == MONO_TABLE_MEMBERREF);
423                 result = method_from_memberref (image, idx);
424                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
425                 return result;
426         }
427
428         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
429
430         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
431             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
432                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
433         else 
434                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
435         
436         result->slot = -1;
437         result->klass = klass;
438         result->flags = cols [2];
439         result->iflags = cols [1];
440         result->token = token;
441         result->name = mono_metadata_string_heap (image, cols [3]);
442
443         if (!sig) /* already taken from the methodref */
444                 sig = mono_metadata_blob_heap (image, cols [4]);
445         size = mono_metadata_decode_blob_size (sig, &sig);
446         result->signature = mono_metadata_parse_method_signature (image, idx, sig, NULL);
447
448         if (!result->klass) {
449                 guint32 type = mono_metadata_typedef_from_method (image, token);
450                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
451         }
452
453         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
454                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
455                         result->string_ctor = 1;
456
457                 result->addr = mono_lookup_internal_call (result);
458                 result->signature->pinvoke = 1;
459         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
460                 result->signature->pinvoke = 1;
461                 ((MonoMethodPInvoke *)result)->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
462         } else {
463                 /* if this is a methodref from another module/assembly, this fails */
464                 loc = mono_cli_rva_map ((MonoCLIImageInfo *)image->image_info, cols [0]);
465
466                 if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
467                                         !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
468                         g_assert (loc);
469                         ((MonoMethodNormal *)result)->header = mono_metadata_parse_mh (image, loc);
470                 }
471         }
472
473         g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
474
475         return result;
476 }
477
478 void
479 mono_free_method  (MonoMethod *method)
480 {
481         mono_metadata_free_method_signature (method->signature);
482         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
483                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
484                 g_free (piinfo->code);
485         } else if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
486                 mono_metadata_free_mh (((MonoMethodNormal *)method)->header);
487         }
488
489         g_free (method);
490 }
491
492 void
493 mono_method_get_param_names (MonoMethod *method, const char **names)
494 {
495         int i, lastp;
496         MonoClass *klass = method->klass;
497         MonoTableInfo *methodt;
498         MonoTableInfo *paramt;
499
500         if (!method->signature->param_count)
501                 return;
502         for (i = 0; i < method->signature->param_count; ++i)
503                 names [i] = "";
504
505         mono_class_init (klass);
506
507         if (klass->wastypebuilder) /* copy the names later */
508                 return;
509
510         methodt = &klass->image->tables [MONO_TABLE_METHOD];
511         paramt = &klass->image->tables [MONO_TABLE_PARAM];
512         for (i = 0; i < klass->method.count; ++i) {
513                 if (method == klass->methods [i]) {
514                         guint32 idx = klass->method.first + i;
515                         guint32 cols [MONO_PARAM_SIZE];
516                         guint param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
517
518                         if (idx + 1 < methodt->rows)
519                                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
520                         else
521                                 lastp = paramt->rows;
522                         for (i = param_index; i < lastp; ++i) {
523                                 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
524                                 if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
525                                         names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
526                         }
527                         return;
528                 }
529         }
530 }
531
532 gpointer
533 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
534 {
535         GList *l;
536         g_assert (method != NULL);
537         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
538
539         if (!(l = g_list_nth (((MonoMethodWrapper *)method)->data, id - 1)))
540                 g_assert_not_reached ();
541
542         return l->data;
543 }
544
545 static void
546 default_stack_walk (MonoStackWalk func, gpointer user_data) {
547         g_error ("stack walk not installed");
548 }
549
550 static MonoStackWalkImpl stack_walk = default_stack_walk;
551
552 void
553 mono_stack_walk (MonoStackWalk func, gpointer user_data)
554 {
555         stack_walk (func, user_data);
556 }
557
558 void
559 mono_install_stack_walk (MonoStackWalkImpl func)
560 {
561         stack_walk = func;
562 }
563
564 static gboolean
565 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
566 {
567         MonoMethod **dest = data;
568         *dest = m;
569         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
570
571         return managed;
572 }
573
574 MonoMethod*
575 mono_method_get_last_managed (void)
576 {
577         MonoMethod *m = NULL;
578         stack_walk (last_managed, &m);
579         return m;
580 }
581
582
583