2001-08-23 Dietmar Maurer <dietmar@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 MonoDefaults mono_defaults;
33
34 static char *dll_map[] = {
35         "libc", "libc.so.6",
36         "libm", "libm.so.6",
37         "cygwin1.dll", "libc.so.6", 
38         NULL, NULL
39 };
40
41 static const char *
42 mono_map_dll (const char *name)
43 {
44         int i = 0;
45
46         while (dll_map [i]) {
47                 if (!strcmp (dll_map [i], name))
48                         return  dll_map [i + 1];
49                 i += 2;
50         }
51
52         return name;
53 }
54
55 void
56 mono_init ()
57 {
58         static gboolean initialized = FALSE;
59         MonoAssembly *ass;
60         enum MonoImageOpenStatus status = MONO_IMAGE_OK;
61
62         if (initialized)
63                 return;
64
65         /* find the corlib */
66         ass = mono_assembly_open (CORLIB_NAME, NULL, &status);
67         g_assert (status == MONO_IMAGE_OK);
68         g_assert (ass != NULL);
69         mono_defaults.corlib = ass->image;
70
71         mono_defaults.array_class = mono_class_from_name (
72                 mono_defaults.corlib, "System", "Array");
73         g_assert (mono_defaults.array_class != 0);
74
75         mono_defaults.char_class = mono_class_from_name (
76                 mono_defaults.corlib, "System", "Char");
77         g_assert (mono_defaults.char_class != 0);
78
79         mono_defaults.string_class = mono_class_from_name (
80                 mono_defaults.corlib, "System", "String");
81         g_assert (mono_defaults.string_class != 0);
82
83 }
84
85 static GHashTable *icall_hash = NULL;
86
87 void
88 mono_add_internal_call (const char *name, gpointer method)
89 {
90         if (!icall_hash)
91                 icall_hash = g_hash_table_new (g_str_hash , g_str_equal);
92         
93         g_hash_table_insert (icall_hash, g_strdup (name), method);
94 }
95
96 gpointer
97 mono_lookup_internal_call (const char *name)
98 {
99         gpointer res;
100
101         if (!icall_hash) {
102                 g_warning ("icall_hash not initialized");
103                 g_assert_not_reached ();
104         }
105
106         if (!(res = g_hash_table_lookup (icall_hash, name))) {
107                 g_warning ("cant resolve internal call to \"%s\"", name);
108                 g_assert_not_reached ();
109         }
110
111         return res;
112 }
113
114 static MonoMethod *
115 method_from_memberref (MonoImage *image, guint32 index)
116 {
117         MonoImage *mimage;
118         MonoClass *klass;
119         MonoTableInfo *tables = image->tables;
120         guint32 cols[6];
121         guint32 nindex, class, i;
122         const char *mname, *name, *nspace;
123         MonoMethodSignature *sig;
124         const char *ptr;
125
126         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], index-1, cols, 3);
127         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
128         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
129         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
130                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
131
132         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
133         
134         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
135         mono_metadata_decode_blob_size (ptr, &ptr);
136         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
137
138         switch (class) {
139         case MEMBERREF_PARENT_TYPEREF: {
140                 guint32 scopeindex, scopetable;
141
142                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPEREF], nindex-1, cols, MONO_TYPEREF_SIZE);
143                 scopeindex = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
144                 scopetable = cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK;
145                 /*g_print ("typeref: 0x%x 0x%x %s.%s\n", scopetable, scopeindex,
146                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAMESPACE]),
147                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAME]));*/
148                 switch (scopetable) {
149                 case RESOLTION_SCOPE_ASSEMBLYREF:
150                         /*
151                          * To find the method we have the following info:
152                          * *) name and namespace of the class from the TYPEREF table
153                          * *) name and signature of the method from the MEMBERREF table
154                          */
155                         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
156                         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
157
158                         /* this will triggered by references to mscorlib */
159                         g_assert (image->references [scopeindex-1] != NULL);
160
161                         mimage = image->references [scopeindex-1]->image;
162
163                         klass = mono_class_from_name (mimage, nspace, name);
164                         mono_class_metadata_init (klass);
165
166                         /* mostly dumb search for now */
167                         for (i = 0; i < klass->method.count; ++i) {
168                                 MonoMethod *m = klass->methods [i];
169                                 if (!strcmp (mname, m->name)) {
170                                         if (mono_metadata_signature_equal (image, sig, mimage, m->signature)) {
171                                                 mono_metadata_free_method_signature (sig);
172                                                 return m;
173                                         }
174                                 }
175                         }
176                         g_warning ("can't find method %s.%s::%s", nspace, name, mname);
177                         g_assert_not_reached ();
178                         break;
179                 default:
180                         g_assert_not_reached ();
181                 }
182                 break;
183         }
184         case MEMBERREF_PARENT_TYPESPEC: {
185                 guint32 bcols [MONO_TYPESPEC_SIZE];
186                 guint32 len;
187                 MonoType *type;
188                 MonoMethod *result;
189
190                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
191                                           bcols, MONO_TYPESPEC_SIZE);
192                 ptr = mono_metadata_blob_heap (image, bcols [MONO_TYPESPEC_SIGNATURE]);
193                 len = mono_metadata_decode_value (ptr, &ptr);   
194                 type = mono_metadata_parse_type (image, ptr, &ptr);
195
196                 if (type->type != MONO_TYPE_ARRAY)
197                         g_assert_not_reached ();                
198
199                 result = (MonoMethod *)g_new0 (MonoMethod, 1);
200                 result->klass = mono_defaults.array_class;
201                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
202                 result->signature = sig;
203                 
204                 if (!strcmp (mname, ".ctor")) { 
205                         g_assert (sig->hasthis);
206                         if (type->data.array->rank == sig->param_count) {
207                                 result->addr = mono_lookup_internal_call ("__array_ctor");
208                                 return result;
209                         } else if ((type->data.array->rank * 2) == sig->param_count) {
210                                 result->addr = mono_lookup_internal_call ("__array_bound_ctor");
211                                 return result;                  
212                         } else 
213                                 g_assert_not_reached ();
214                 }
215
216                 if (!strcmp (mname, "Set")) {
217                         g_assert (sig->hasthis);
218                         g_assert (type->data.array->rank + 1 == sig->param_count);
219
220                         result->addr = mono_lookup_internal_call ("__array_Set");
221                         return result;
222                 }
223
224                 if (!strcmp (mname, "Get")) {
225                         g_assert (sig->hasthis);
226                         g_assert (type->data.array->rank == sig->param_count);
227
228                         result->addr = mono_lookup_internal_call ("__array_Get");
229                         return result;
230                 }
231
232                 g_assert_not_reached ();
233                 break;
234         }
235         default:
236                 g_assert_not_reached ();
237         }
238
239         return NULL;
240 }
241
242 static ffi_type *
243 ves_map_ffi_type (MonoType *type)
244 {
245         ffi_type *rettype;
246
247         switch (type->type) {
248         case MONO_TYPE_I1:
249                 rettype = &ffi_type_sint8;
250                 break;
251         case MONO_TYPE_BOOLEAN:
252         case MONO_TYPE_U1:
253                 rettype = &ffi_type_uint8;
254                 break;
255         case MONO_TYPE_I2:
256                 rettype = &ffi_type_sint16;
257                 break;
258         case MONO_TYPE_U2:
259         case MONO_TYPE_CHAR:
260                 rettype = &ffi_type_uint16;
261                 break;
262         case MONO_TYPE_I4:
263                 rettype = &ffi_type_sint32;
264                 break;
265         case MONO_TYPE_U4:
266                 rettype = &ffi_type_sint32;
267                 break;
268         case MONO_TYPE_R4:
269                 rettype = &ffi_type_float;
270                 break;
271         case MONO_TYPE_R8:
272                 rettype = &ffi_type_double;
273                 break;
274         case MONO_TYPE_STRING:
275                 rettype = &ffi_type_pointer;
276                 break;
277         case MONO_TYPE_VOID:
278                 rettype = &ffi_type_void;
279                 break;
280         default:
281                 g_warning ("not implemented");
282                 g_assert_not_reached ();
283         }
284
285         return rettype;
286 }
287
288 static void
289 fill_pinvoke_info (MonoImage *image, MonoMethodPInvoke *piinfo, int index)
290 {
291         MonoMethod *mh = &piinfo->method;
292         MonoTableInfo *tables = image->tables;
293         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
294         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
295         guint32 im_cols [4];
296         guint32 mr_cols [1];
297         const char *import = NULL;
298         const char *scope = NULL;
299         char *full_name;
300         GModule *gmodule;
301         ffi_type **args, *rettype;
302         int i, acount;
303
304         for (i = 0; i < im->rows; i++) {
305                         
306                 mono_metadata_decode_row (im, i, im_cols, 4);
307
308                 if ((im_cols[1] >> 1) == index + 1) {
309
310                         import = mono_metadata_string_heap (image, im_cols [2]);
311
312                         mono_metadata_decode_row (mr, im_cols [3] - 1, mr_cols,
313                                                   1);
314                         
315                         scope = mono_metadata_string_heap (image, mr_cols [0]);
316                 }
317         }
318
319         g_assert (import && scope);
320
321         scope = mono_map_dll (scope);
322         full_name = g_module_build_path (NULL, scope);
323         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
324         g_free (full_name);
325
326         g_assert (gmodule);
327
328         piinfo->cif = g_new (ffi_cif , 1);
329         piinfo->piflags = im_cols [0];
330
331         g_module_symbol (gmodule, import, &mh->addr); 
332
333         g_assert (mh->addr);
334
335         acount = mh->signature->param_count;
336
337         args = g_new (ffi_type *, acount);
338
339         for (i = 0; i < acount; i++)
340                 args[i] = ves_map_ffi_type (mh->signature->params [i]->type);
341
342         rettype = ves_map_ffi_type (mh->signature->ret->type);
343         
344         if (!ffi_prep_cif (piinfo->cif, FFI_DEFAULT_ABI, acount, rettype, 
345                            args) == FFI_OK) {
346                 g_warning ("prepare pinvoke failed");
347                 g_assert_not_reached ();
348         }
349 }
350
351 MonoMethod *
352 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
353 {
354         MonoMethod *result;
355         int table = mono_metadata_token_table (token);
356         int index = mono_metadata_token_index (token);
357         MonoTableInfo *tables = image->tables;
358         const char *loc, *sig = NULL;
359         char *name;
360         int size;
361         guint32 cols [MONO_TYPEDEF_SIZE];
362
363         if (table == MONO_TABLE_METHOD && (result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token))))
364                         return result;
365
366         if (table != MONO_TABLE_METHOD) {
367                 g_assert (table == MONO_TABLE_MEMBERREF);
368                 return method_from_memberref (image, index);
369         }
370
371         mono_metadata_decode_row (&tables [table], index - 1, cols, 6);
372
373         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
374                 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
375                 MonoAssembly *corlib;
376                 guint32 tdef;
377                 guint32 tdcols [MONO_TYPEDEF_SIZE];
378
379                 tdef = mono_metadata_typedef_from_method (image, index - 1) - 1;
380
381                 mono_metadata_decode_row (t, tdef, tdcols, MONO_TYPEDEF_SIZE);
382
383                 name = g_strconcat (mono_metadata_string_heap (image, tdcols [MONO_TYPEDEF_NAMESPACE]), ".",
384                                     mono_metadata_string_heap (image, tdcols [MONO_TYPEDEF_NAME]), "::", 
385                                     mono_metadata_string_heap (image, cols [MONO_METHOD_NAME]), NULL);
386
387                 corlib = mono_assembly_open (CORLIB_NAME, NULL, NULL);
388
389                 /* all internal calls must be inside corlib */
390                 g_assert (corlib->image == image);
391
392                 result = (MonoMethod *)g_new0 (MonoMethod, 1);
393
394                 result->addr = mono_lookup_internal_call (name);
395
396                 g_free (name);
397
398                 g_assert (result->addr != NULL);
399
400         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
401
402                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
403         } else {
404
405                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
406         }
407
408         result->klass = klass;
409         result->flags = cols [2];
410         result->iflags = cols [1];
411         result->name = mono_metadata_string_heap (image, cols [3]);
412
413         if (!sig) /* already taken from the methodref */
414                 sig = mono_metadata_blob_heap (image, cols [4]);
415         size = mono_metadata_decode_blob_size (sig, &sig);
416         result->signature = mono_metadata_parse_method_signature (image, 0, sig, NULL);
417
418         if (result->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
419                 fill_pinvoke_info (image, (MonoMethodPInvoke *)result, 
420                                    index - 1);
421         } else if (!(result->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
422                 /* if this is a methodref from another module/assembly, this fails */
423                 loc = mono_cli_rva_map ((MonoCLIImageInfo *)image->image_info, cols [0]);
424
425                 if (!result->klass) {
426                         guint32 type = mono_metadata_typedef_from_method (image, token);
427                         result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
428                 }
429
430                 g_assert (loc);
431
432                 ((MonoMethodNormal *)result)->header = mono_metadata_parse_mh (image, loc);
433         }
434
435         g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
436
437         return result;
438 }
439
440 void
441 mono_free_method  (MonoMethod *method)
442 {
443         mono_metadata_free_method_signature (method->signature);
444         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
445                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
446                 g_free (piinfo->cif->arg_types);
447                 g_free (piinfo->cif);
448         } else if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
449                 mono_metadata_free_mh (((MonoMethodNormal *)method)->header);
450         }
451
452         g_free (method);
453 }
454