Thu Oct 4 19:10:30 CEST 2001 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / metadata / loader.c
1 /*
2  * loader.c: Image Loader 
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Miguel de Icaza (miguel@ximian.com)
7  *
8  * (C) 2001 Ximian, Inc.
9  *
10  * This file is used by the interpreter and the JIT engine to locate
11  * assemblies.  Used to load AssemblyRef and later to resolve various
12  * kinds of `Refs'.
13  *
14  * TODO:
15  *   This should keep track of the assembly versions that we are loading.
16  *
17  */
18 #include <config.h>
19 #include <glib.h>
20 #include <gmodule.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <mono/metadata/metadata.h>
24 #include <mono/metadata/image.h>
25 #include <mono/metadata/assembly.h>
26 #include <mono/metadata/tokentype.h>
27 #include <mono/metadata/cil-coff.h>
28 #include <mono/metadata/tabledefs.h>
29 #include <mono/metadata/loader.h>
30 #include <mono/metadata/class.h>
31
32 static gboolean dummy_icall = TRUE;
33
34 MonoDefaults mono_defaults;
35
36 #ifdef __CYGWIN__
37 #define mono_map_dll(name) (name)
38 #else
39 static char *dll_map[] = {
40         "libc", "libc.so.6",
41         "libm", "libm.so.6",
42         "cygwin1.dll", "libc.so.6", 
43         NULL, NULL
44 };
45
46 static const char *
47 mono_map_dll (const char *name)
48 {
49         int i = 0;
50
51         while (dll_map [i]) {
52                 if (!strcmp (dll_map [i], name))
53                         return  dll_map [i + 1];
54                 i += 2;
55         }
56
57         return name;
58 }
59 #endif
60
61 void
62 mono_init (void)
63 {
64         static gboolean initialized = FALSE;
65         MonoAssembly *ass;
66         enum MonoImageOpenStatus status = MONO_IMAGE_OK;
67
68         if (initialized)
69                 return;
70
71         /* find the corlib */
72         ass = mono_assembly_open (CORLIB_NAME, NULL, &status);
73         g_assert (status == MONO_IMAGE_OK);
74         g_assert (ass != NULL);
75         mono_defaults.corlib = ass->image;
76
77         mono_defaults.object_class = mono_class_from_name (
78                 mono_defaults.corlib, "System", "Object");
79         g_assert (mono_defaults.object_class != 0);
80
81         mono_defaults.void_class = mono_class_from_name (
82                 mono_defaults.corlib, "System", "Void");
83         g_assert (mono_defaults.void_class != 0);
84
85         mono_defaults.boolean_class = mono_class_from_name (
86                 mono_defaults.corlib, "System", "Boolean");
87         g_assert (mono_defaults.boolean_class != 0);
88
89         mono_defaults.byte_class = mono_class_from_name (
90                 mono_defaults.corlib, "System", "Byte");
91         g_assert (mono_defaults.byte_class != 0);
92
93         mono_defaults.sbyte_class = mono_class_from_name (
94                 mono_defaults.corlib, "System", "SByte");
95         g_assert (mono_defaults.sbyte_class != 0);
96
97         mono_defaults.int16_class = mono_class_from_name (
98                 mono_defaults.corlib, "System", "Int16");
99         g_assert (mono_defaults.int16_class != 0);
100
101         mono_defaults.uint16_class = mono_class_from_name (
102                 mono_defaults.corlib, "System", "UInt16");
103         g_assert (mono_defaults.uint16_class != 0);
104
105         mono_defaults.int32_class = mono_class_from_name (
106                 mono_defaults.corlib, "System", "Int32");
107         g_assert (mono_defaults.int32_class != 0);
108
109         mono_defaults.uint32_class = mono_class_from_name (
110                 mono_defaults.corlib, "System", "UInt32");
111         g_assert (mono_defaults.uint32_class != 0);
112
113         mono_defaults.uint_class = mono_class_from_name (
114                 mono_defaults.corlib, "System", "UIntPtr");
115         g_assert (mono_defaults.uint_class != 0);
116
117         mono_defaults.int_class = mono_class_from_name (
118                 mono_defaults.corlib, "System", "IntPtr");
119         g_assert (mono_defaults.int_class != 0);
120
121         mono_defaults.int64_class = mono_class_from_name (
122                 mono_defaults.corlib, "System", "Int64");
123         g_assert (mono_defaults.int64_class != 0);
124
125         mono_defaults.uint64_class = mono_class_from_name (
126                 mono_defaults.corlib, "System", "UInt64");
127         g_assert (mono_defaults.uint64_class != 0);
128
129         mono_defaults.single_class = mono_class_from_name (
130                 mono_defaults.corlib, "System", "Single");
131         g_assert (mono_defaults.single_class != 0);
132
133         mono_defaults.double_class = mono_class_from_name (
134                 mono_defaults.corlib, "System", "Double");
135         g_assert (mono_defaults.double_class != 0);
136
137         mono_defaults.char_class = mono_class_from_name (
138                 mono_defaults.corlib, "System", "Char");
139         g_assert (mono_defaults.char_class != 0);
140
141         mono_defaults.string_class = mono_class_from_name (
142                 mono_defaults.corlib, "System", "String");
143         g_assert (mono_defaults.string_class != 0);
144
145         mono_defaults.enum_class = mono_class_from_name (
146                 mono_defaults.corlib, "System", "Enum");
147         g_assert (mono_defaults.enum_class != 0);
148
149         mono_defaults.array_class = mono_class_from_name (
150                 mono_defaults.corlib, "System", "Array");
151         g_assert (mono_defaults.array_class != 0);
152
153         mono_defaults.delegate_class = mono_class_from_name (
154                 mono_defaults.corlib, "System", "Delegate");
155         g_assert (mono_defaults.delegate_class != 0);
156
157         mono_defaults.typehandle_class = mono_class_from_name (
158                 mono_defaults.corlib, "System", "RuntimeTypeHandle");
159         g_assert (mono_defaults.typehandle_class != 0);
160
161         mono_defaults.methodhandle_class = mono_class_from_name (
162                 mono_defaults.corlib, "System", "RuntimeMethodHandle");
163         g_assert (mono_defaults.methodhandle_class != 0);
164
165         mono_defaults.fieldhandle_class = mono_class_from_name (
166                 mono_defaults.corlib, "System", "RuntimeFieldHandle");
167         g_assert (mono_defaults.fieldhandle_class != 0);
168
169         mono_defaults.type_class = mono_class_from_name (
170                 mono_defaults.corlib, "System", "Type");
171         g_assert (mono_defaults.type_class != 0);
172
173 }
174
175 static GHashTable *icall_hash = NULL;
176
177 void
178 mono_add_internal_call (const char *name, gpointer method)
179 {
180         if (!icall_hash) {
181                 dummy_icall = FALSE;
182                 icall_hash = g_hash_table_new (g_str_hash , g_str_equal);
183         }
184
185         g_hash_table_insert (icall_hash, g_strdup (name), method);
186 }
187
188 static void
189 ves_icall_dummy ()
190 {
191         g_warning ("the mono runtime is not initialized");
192         g_assert_not_reached ();
193 }
194
195 gpointer
196 mono_lookup_internal_call (const char *name)
197 {
198         gpointer res;
199
200         if (dummy_icall)
201                 return ves_icall_dummy;
202
203         if (!icall_hash) {
204                 g_warning ("icall_hash not initialized");
205                 g_assert_not_reached ();
206         }
207
208         if (!(res = g_hash_table_lookup (icall_hash, name))) {
209                 g_warning ("cant resolve internal call to \"%s\"", name);
210                 return NULL;
211         }
212
213         return res;
214 }
215
216 static MonoMethod *
217 method_from_memberref (MonoImage *image, guint32 index)
218 {
219         MonoImage *mimage;
220         MonoClass *klass;
221         MonoTableInfo *tables = image->tables;
222         guint32 cols[6];
223         guint32 nindex, class, i;
224         const char *mname, *name, *nspace;
225         MonoMethodSignature *sig;
226         const char *ptr;
227
228         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], index-1, cols, 3);
229         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
230         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
231         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
232                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
233
234         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
235         
236         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
237         mono_metadata_decode_blob_size (ptr, &ptr);
238         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
239
240         switch (class) {
241         case MEMBERREF_PARENT_TYPEREF: {
242                 guint32 scopeindex, scopetable;
243
244                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPEREF], nindex-1, cols, MONO_TYPEREF_SIZE);
245                 scopeindex = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
246                 scopetable = cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK;
247                 /*g_print ("typeref: 0x%x 0x%x %s.%s\n", scopetable, scopeindex,
248                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAMESPACE]),
249                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAME]));*/
250                 switch (scopetable) {
251                 case RESOLTION_SCOPE_ASSEMBLYREF:
252                         /*
253                          * To find the method we have the following info:
254                          * *) name and namespace of the class from the TYPEREF table
255                          * *) name and signature of the method from the MEMBERREF table
256                          */
257                         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
258                         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
259
260                         /* this will triggered by references to mscorlib */
261                         if (image->references [scopeindex-1] == NULL)
262                                 g_error ("Reference to mscorlib? Probably need to implement %s.%s::%s in corlib", nspace, name, mname);
263
264                         mimage = image->references [scopeindex-1]->image;
265
266                         klass = mono_class_from_name (mimage, nspace, name);
267                         mono_class_metadata_init (klass);
268
269                         /* 
270                          * FIXME: this is a workaround for the different signatures
271                          * in delegates constructors you get in user code (native int)
272                          * and in mscorlib (native unsigned int)
273                          */
274                         if (klass->parent && klass->parent->parent == mono_defaults.delegate_class) {
275                                 for (i = 0; i < klass->method.count; ++i) {
276                                         MonoMethod *m = klass->methods [i];
277                                         if (!strcmp (mname, m->name)) {
278                                                 if (!strcmp (mname, ".ctor")) {
279                                                         /* we assume signature is correct */
280                                                         mono_metadata_free_method_signature (sig);
281                                                         return m;
282                                                 }
283                                                 if (mono_metadata_signature_equal (sig, m->signature)) {
284                                                         mono_metadata_free_method_signature (sig);
285                                                         return m;
286                                                 }
287                                         }
288                                 }
289                         }
290                         /* mostly dumb search for now */
291                         for (i = 0; i < klass->method.count; ++i) {
292                                 MonoMethod *m = klass->methods [i];
293                                 if (!strcmp (mname, m->name)) {
294                                         if (mono_metadata_signature_equal (sig, m->signature)) {
295                                                 mono_metadata_free_method_signature (sig);
296                                                 return m;
297                                         }
298                                 }
299                         }
300                         g_warning ("Missing method %s.%s::%s", nspace, name, mname);
301                         mono_metadata_free_method_signature (sig);
302                         return NULL;
303                 default:
304                         mono_metadata_free_method_signature (sig);
305                         return NULL;
306                 }
307                 break;
308         }
309         case MEMBERREF_PARENT_TYPESPEC: {
310                 guint32 bcols [MONO_TYPESPEC_SIZE];
311                 guint32 len;
312                 MonoType *type;
313                 MonoMethod *result;
314
315                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
316                                           bcols, MONO_TYPESPEC_SIZE);
317                 ptr = mono_metadata_blob_heap (image, bcols [MONO_TYPESPEC_SIGNATURE]);
318                 len = mono_metadata_decode_value (ptr, &ptr);   
319                 type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
320
321                 if (type->type != MONO_TYPE_ARRAY)
322                         g_assert_not_reached ();                
323
324                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
325                 result->klass = mono_defaults.array_class;
326                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
327                 result->signature = sig;
328                 result->name = mname;
329
330                 if (!strcmp (mname, ".ctor")) { 
331                         g_assert (sig->hasthis);
332                         if (type->data.array->rank == sig->param_count) {
333                                 result->addr = mono_lookup_internal_call ("__array_ctor");
334                         } else if ((type->data.array->rank * 2) == sig->param_count) {
335                                 result->addr = mono_lookup_internal_call ("__array_bound_ctor");
336                         } else 
337                                 g_assert_not_reached ();
338
339                         result->flags = METHOD_ATTRIBUTE_PINVOKE_IMPL;
340                         return result;                                          
341                 }
342
343                 if (!strcmp (mname, "Set")) {
344                         g_assert (sig->hasthis);
345                         g_assert (type->data.array->rank + 1 == sig->param_count);
346
347                         result->addr = mono_lookup_internal_call ("__array_Set");
348                         return result;
349                 }
350
351                 if (!strcmp (mname, "Get")) {
352                         g_assert (sig->hasthis);
353                         g_assert (type->data.array->rank == sig->param_count);
354
355                         result->addr = mono_lookup_internal_call ("__array_Get");
356                         return result;
357                 }
358
359                 g_assert_not_reached ();
360                 break;
361         }
362         default:
363                 g_assert_not_reached ();
364         }
365
366         return NULL;
367 }
368
369 static void
370 fill_pinvoke_info (MonoImage *image, MonoMethodPInvoke *piinfo, int index)
371 {
372         MonoMethod *mh = &piinfo->method;
373         MonoTableInfo *tables = image->tables;
374         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
375         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
376         guint32 im_cols [4];
377         guint32 mr_cols [1];
378         const char *import = NULL;
379         const char *scope = NULL;
380         char *full_name;
381         GModule *gmodule;
382         int i;
383
384         for (i = 0; i < im->rows; i++) {
385                         
386                 mono_metadata_decode_row (im, i, im_cols, 4);
387
388                 if ((im_cols[1] >> 1) == index + 1) {
389
390                         import = mono_metadata_string_heap (image, im_cols [2]);
391
392                         mono_metadata_decode_row (mr, im_cols [3] - 1, mr_cols,
393                                                   1);
394                         
395                         scope = mono_metadata_string_heap (image, mr_cols [0]);
396                 }
397         }
398
399         piinfo->piflags = im_cols [0];
400
401         g_assert (import && scope);
402
403         scope = mono_map_dll (scope);
404         full_name = g_module_build_path (NULL, scope);
405         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
406
407         mh->addr = NULL;
408         if (!gmodule) {
409                 if (!(gmodule=g_module_open (scope, G_MODULE_BIND_LAZY))) {
410                         g_warning ("Failed to load library %s (%s)", full_name, scope);
411                         g_free (full_name);
412                         return;
413                 }
414         }
415         g_free (full_name);
416
417         g_module_symbol (gmodule, import, &mh->addr); 
418
419         if (!mh->addr) {
420                 g_warning ("Failed to load function %s from %s", import, scope);
421                 return;
422         }
423
424         mh->flags |= METHOD_ATTRIBUTE_PINVOKE_IMPL;
425 }
426
427 MonoMethod *
428 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
429 {
430         MonoMethod *result;
431         int table = mono_metadata_token_table (token);
432         int index = mono_metadata_token_index (token);
433         MonoTableInfo *tables = image->tables;
434         const char *loc, *sig = NULL;
435         char *name;
436         int size;
437         guint32 cols [MONO_TYPEDEF_SIZE];
438
439         if (table == MONO_TABLE_METHOD && (result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token))))
440                         return result;
441
442         if (table != MONO_TABLE_METHOD) {
443                 g_assert (table == MONO_TABLE_MEMBERREF);
444                 return method_from_memberref (image, index);
445         }
446
447         mono_metadata_decode_row (&tables [table], index - 1, cols, 6);
448
449         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
450             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
451                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
452         else 
453                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
454         
455         result->klass = klass;
456         result->flags = cols [2];
457         result->iflags = cols [1];
458         result->name = mono_metadata_string_heap (image, cols [3]);
459
460         if (!sig) /* already taken from the methodref */
461                 sig = mono_metadata_blob_heap (image, cols [4]);
462         size = mono_metadata_decode_blob_size (sig, &sig);
463         result->signature = mono_metadata_parse_method_signature (image, 0, sig, NULL);
464
465         if (!result->klass) {
466                 guint32 type = mono_metadata_typedef_from_method (image, token);
467                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
468         }
469
470         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
471                 name = g_strconcat (result->klass->name_space, ".", result->klass->name, "::", 
472                                     mono_metadata_string_heap (image, cols [MONO_METHOD_NAME]), NULL);
473                 result->addr = mono_lookup_internal_call (name);
474                 g_free (name);
475                 result->flags |= METHOD_ATTRIBUTE_PINVOKE_IMPL;
476         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
477                 fill_pinvoke_info (image, (MonoMethodPInvoke *)result, index - 1);
478         } else {
479                 /* if this is a methodref from another module/assembly, this fails */
480                 loc = mono_cli_rva_map ((MonoCLIImageInfo *)image->image_info, cols [0]);
481
482                 if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
483                                         !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
484                         g_assert (loc);
485                         ((MonoMethodNormal *)result)->header = mono_metadata_parse_mh (image, loc);
486                 }
487         }
488
489         g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
490
491         return result;
492 }
493
494 void
495 mono_free_method  (MonoMethod *method)
496 {
497         mono_metadata_free_method_signature (method->signature);
498         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
499                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
500                 g_free (piinfo->code);
501         } else if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
502                 mono_metadata_free_mh (((MonoMethodNormal *)method)->header);
503         }
504
505         g_free (method);
506 }
507