Mon Apr 22 19:44:16 CEST 2002 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  *   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 #ifdef __CYGWIN__
40 #define mono_map_dll(name) (name)
41 #else
42 static const char *dll_map[] = {
43         "libc", "libc.so.6",
44         "libm", "libm.so.6",
45         "cygwin1.dll", "libc.so.6", 
46         NULL, NULL
47 };
48
49 static const char *
50 mono_map_dll (const char *name)
51 {
52         int i = 0;
53
54         while (dll_map [i]) {
55                 if (!strcmp (dll_map [i], name))
56                         return  dll_map [i + 1];
57                 i += 2;
58         }
59
60         return name;
61 }
62 #endif
63
64 static GHashTable *icall_hash = NULL;
65
66 void
67 mono_add_internal_call (const char *name, gconstpointer method)
68 {
69         if (!icall_hash) {
70                 dummy_icall = FALSE;
71                 icall_hash = g_hash_table_new (g_str_hash , g_str_equal);
72         }
73
74         g_hash_table_insert (icall_hash, g_strdup (name), method);
75 }
76
77 static void
78 ves_icall_dummy (void)
79 {
80         g_warning ("the mono runtime is not initialized");
81         g_assert_not_reached ();
82 }
83
84 gpointer
85 mono_lookup_internal_call (MonoMethod *method)
86 {
87         char *name;
88         char *tmpsig;
89         gpointer res;
90
91         if (dummy_icall)
92                 return ves_icall_dummy;
93
94         if (!method) {
95                 g_warning ("can't resolve internal call, method is null");
96         }
97
98         if (!icall_hash) {
99                 g_warning ("icall_hash not initialized");
100                 g_assert_not_reached ();
101         }
102
103         name = g_strconcat (method->klass->name_space, ".", method->klass->name, "::", method->name, NULL);
104         if (!(res = g_hash_table_lookup (icall_hash, name))) {
105                 // trying to resolve with full signature
106                 g_free (name);
107         
108                 tmpsig = mono_signature_get_desc(method->signature, TRUE);
109                 name = g_strconcat (method->klass->name_space, ".", method->klass->name, "::", method->name, "(", tmpsig, ")", NULL);
110                 if (!(res = g_hash_table_lookup (icall_hash, name))) {
111                         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", name);
112
113                         g_free (name);
114                         g_free(tmpsig);
115
116                         return NULL;
117                 }
118
119                 g_free(tmpsig);
120         }
121
122         g_free (name);
123
124         return res;
125 }
126
127 MonoClassField*
128 mono_field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass)
129 {
130         MonoImage *mimage;
131         MonoClass *klass;
132         MonoTableInfo *tables = image->tables;
133         guint32 cols[6];
134         guint32 nindex, class, i;
135         const char *fname, *name, *nspace;
136         const char *ptr;
137         guint32 idx = mono_metadata_token_index (token);
138
139         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
140         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
141         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
142
143         fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
144         
145         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
146         mono_metadata_decode_blob_size (ptr, &ptr);
147         /* we may want to check the signature here... */
148
149         switch (class) {
150         case MEMBERREF_PARENT_TYPEREF: {
151                 guint32 scopeindex, scopetable;
152
153                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPEREF], nindex-1, cols, MONO_TYPEREF_SIZE);
154                 scopeindex = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
155                 scopetable = cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK;
156                 /*g_print ("typeref: 0x%x 0x%x %s.%s\n", scopetable, scopeindex,
157                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAMESPACE]),
158                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAME]));*/
159                 switch (scopetable) {
160                 case RESOLTION_SCOPE_ASSEMBLYREF:
161                         /*
162                          * To find the field we have the following info:
163                          * *) name and namespace of the class from the TYPEREF table
164                          * *) name and signature of the field from the MEMBERREF table
165                          */
166                         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
167                         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
168
169                         /* this will triggered by references to mscorlib */
170                         if (image->references [scopeindex-1] == NULL)
171                                 g_error ("Reference to mscorlib? Probably need to implement %s.%s::%s in corlib", nspace, name, fname);
172
173                         mimage = image->references [scopeindex-1]->image;
174
175                         klass = mono_class_from_name (mimage, nspace, name);
176                         mono_class_init (klass);
177
178                         /* mostly dumb search for now */
179                         for (i = 0; i < klass->field.count; ++i) {
180                                 MonoClassField *f = &klass->fields [i];
181                                 if (!strcmp (fname, f->name)) {
182                                         if (retklass)
183                                                 *retklass = klass;
184                                         return f;
185                                 }
186                         }
187                         g_warning ("Missing field %s.%s::%s", nspace, name, fname);
188                         return NULL;
189                 default:
190                         return NULL;
191                 }
192                 break;
193         }
194         default:
195                 return NULL;
196         }
197 }
198
199 static MonoMethod *
200 method_from_memberref (MonoImage *image, guint32 idx)
201 {
202         MonoImage *mimage;
203         MonoClass *klass;
204         MonoTableInfo *tables = image->tables;
205         guint32 cols[6];
206         guint32 nindex, class, i;
207         const char *mname, *name, *nspace;
208         MonoMethodSignature *sig;
209         const char *ptr;
210
211         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
212         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
213         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
214         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
215                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
216
217         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
218         
219         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
220         mono_metadata_decode_blob_size (ptr, &ptr);
221         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
222
223         switch (class) {
224         case MEMBERREF_PARENT_TYPEREF: {
225                 guint32 scopeindex, scopetable;
226
227                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPEREF], nindex-1, cols, MONO_TYPEREF_SIZE);
228                 scopeindex = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
229                 scopetable = cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK;
230                 /*g_print ("typeref: 0x%x 0x%x %s.%s\n", scopetable, scopeindex,
231                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAMESPACE]),
232                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAME]));*/
233                 switch (scopetable) {
234                 case RESOLTION_SCOPE_ASSEMBLYREF:
235                         /*
236                          * To find the method we have the following info:
237                          * *) name and namespace of the class from the TYPEREF table
238                          * *) name and signature of the method from the MEMBERREF table
239                          */
240                         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
241                         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
242
243                         /* this will triggered by references to mscorlib */
244                         if (image->references [scopeindex-1] == NULL)
245                                 g_error ("Reference to mscorlib? Probably need to implement %s.%s::%s in corlib", nspace, name, mname);
246
247                         mimage = image->references [scopeindex-1]->image;
248
249                         klass = mono_class_from_name (mimage, nspace, name);
250                         if (!klass) {
251                                 g_warning ("Missing method %s.%s::%s", nspace, name, mname);
252                                 mono_metadata_free_method_signature (sig);
253                                 return NULL;
254                         }
255                         mono_class_init (klass);
256
257                         /* mostly dumb search for now */
258                         for (i = 0; i < klass->method.count; ++i) {
259                                 MonoMethod *m = klass->methods [i];
260                                 if (!strcmp (mname, m->name)) {
261                                         if (mono_metadata_signature_equal (sig, m->signature)) {
262                                                 mono_metadata_free_method_signature (sig);
263                                                 return m;
264                                         }
265                                 }
266                         }
267                         g_warning ("Missing method %s.%s::%s", nspace, name, mname);
268                         mono_metadata_free_method_signature (sig);
269                         return NULL;
270                 default:
271                         mono_metadata_free_method_signature (sig);
272                         return NULL;
273                 }
274                 break;
275         }
276         case MEMBERREF_PARENT_TYPESPEC: {
277                 guint32 bcols [MONO_TYPESPEC_SIZE];
278                 guint32 len;
279                 MonoType *type;
280                 MonoMethod *result;
281
282                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
283                                           bcols, MONO_TYPESPEC_SIZE);
284                 ptr = mono_metadata_blob_heap (image, bcols [MONO_TYPESPEC_SIGNATURE]);
285                 len = mono_metadata_decode_value (ptr, &ptr);   
286                 type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
287
288                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY)
289                         g_assert_not_reached ();                
290
291                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
292                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_SPEC | nindex);
293                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
294                 result->signature = sig;
295                 result->name = mname;
296
297                 if (!strcmp (mname, ".ctor")) {
298                         /* we special-case this in the runtime. */
299                         result->addr = NULL;
300                         return result;
301                 }
302                 
303                 if (!strcmp (mname, "Set")) {
304                         g_assert (sig->hasthis);
305                         g_assert (type->data.array->rank + 1 == sig->param_count);
306
307                         result->addr = mono_lookup_internal_call(result);
308                         return result;
309                 }
310
311                 if (!strcmp (mname, "Get")) {
312                         g_assert (sig->hasthis);
313                         g_assert (type->data.array->rank == sig->param_count);
314
315                         result->addr = mono_lookup_internal_call(result);
316                         return result;
317                 }
318
319                 if (!strcmp (mname, "Address")) {
320                         g_assert (sig->hasthis);
321                         g_assert (type->data.array->rank == sig->param_count);
322
323                         result->addr = mono_lookup_internal_call(result);
324                         return result;
325                 }
326
327                 g_assert_not_reached ();
328                 break;
329         }
330         default:
331                 g_assert_not_reached ();
332         }
333
334         return NULL;
335 }
336
337 static void
338 fill_pinvoke_info (MonoImage *image, MonoMethodPInvoke *piinfo, int idx)
339 {
340         MonoMethod *mh = &piinfo->method;
341         MonoTableInfo *tables = image->tables;
342         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
343         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
344         guint32 im_cols [4];
345         guint32 mr_cols [1];
346         const char *import = NULL;
347         const char *scope = NULL;
348         char *full_name;
349         GModule *gmodule;
350         int i;
351
352         for (i = 0; i < im->rows; i++) {
353                         
354                 mono_metadata_decode_row (im, i, im_cols, 4);
355
356                 if ((im_cols[1] >> 1) == idx + 1) {
357
358                         import = mono_metadata_string_heap (image, im_cols [2]);
359
360                         mono_metadata_decode_row (mr, im_cols [3] - 1, mr_cols,
361                                                   1);
362                         
363                         scope = mono_metadata_string_heap (image, mr_cols [0]);
364                 }
365         }
366
367         piinfo->piflags = im_cols [0];
368
369         g_assert (import && scope);
370
371         scope = mono_map_dll (scope);
372         full_name = g_module_build_path (NULL, scope);
373         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
374
375         mh->addr = NULL;
376         if (!gmodule) {
377                 if (!(gmodule=g_module_open (scope, G_MODULE_BIND_LAZY))) {
378                         g_warning ("Failed to load library %s (%s)", full_name, scope);
379                         g_free (full_name);
380                         return;
381                 }
382         }
383         g_free (full_name);
384
385         g_module_symbol (gmodule, import, &mh->addr); 
386
387         if (!mh->addr) {
388                 g_warning ("Failed to load function %s from %s", import, scope);
389                 return;
390         }
391
392         mh->flags |= METHOD_ATTRIBUTE_PINVOKE_IMPL;
393 }
394
395 MonoMethod *
396 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
397 {
398         MonoMethod *result;
399         int table = mono_metadata_token_table (token);
400         int idx = mono_metadata_token_index (token);
401         MonoTableInfo *tables = image->tables;
402         const char *loc, *sig = NULL;
403         int size;
404         guint32 cols [MONO_TYPEDEF_SIZE];
405
406         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token))))
407                         return result;
408
409         if (table != MONO_TABLE_METHOD) {
410                 if (table != MONO_TABLE_MEMBERREF)
411                         g_print("got wrong token: 0x%08x\n", token);
412                 g_assert (table == MONO_TABLE_MEMBERREF);
413                 result = method_from_memberref (image, idx);
414                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
415                 return result;
416         }
417
418         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
419
420         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
421             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
422                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
423         else 
424                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
425         
426         result->slot = -1;
427         result->klass = klass;
428         result->flags = cols [2];
429         result->iflags = cols [1];
430         result->name = mono_metadata_string_heap (image, cols [3]);
431
432         if (!sig) /* already taken from the methodref */
433                 sig = mono_metadata_blob_heap (image, cols [4]);
434         size = mono_metadata_decode_blob_size (sig, &sig);
435         result->signature = mono_metadata_parse_method_signature (image, 0, sig, NULL);
436
437         if (!result->klass) {
438                 guint32 type = mono_metadata_typedef_from_method (image, token);
439                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
440         }
441
442         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
443                 result->addr = mono_lookup_internal_call (result);
444                 result->flags |= METHOD_ATTRIBUTE_PINVOKE_IMPL;
445         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
446                 fill_pinvoke_info (image, (MonoMethodPInvoke *)result, idx - 1);
447         } else {
448                 /* if this is a methodref from another module/assembly, this fails */
449                 loc = mono_cli_rva_map ((MonoCLIImageInfo *)image->image_info, cols [0]);
450
451                 if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
452                                         !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
453                         g_assert (loc);
454                         ((MonoMethodNormal *)result)->header = mono_metadata_parse_mh (image, loc);
455                 }
456         }
457
458         g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
459
460         return result;
461 }
462
463 void
464 mono_free_method  (MonoMethod *method)
465 {
466         mono_metadata_free_method_signature (method->signature);
467         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
468                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
469                 g_free (piinfo->code);
470         } else if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
471                 mono_metadata_free_mh (((MonoMethodNormal *)method)->header);
472         }
473
474         g_free (method);
475 }
476
477 void
478 mono_method_get_param_names (MonoMethod *method, const char **names)
479 {
480         int i, lastp;
481         MonoClass *klass = method->klass;
482         MonoTableInfo *methodt = &klass->image->tables [MONO_TABLE_METHOD];
483         MonoTableInfo *paramt = &klass->image->tables [MONO_TABLE_PARAM];
484
485         if (!method->signature->param_count)
486                 return;
487         for (i = 0; i < method->signature->param_count; ++i)
488                 names [i] = "";
489
490         mono_class_init (klass);
491         if (!klass->methods)
492                 return;
493
494         for (i = 0; i < klass->method.count; ++i) {
495                 if (method == klass->methods [i]) {
496                         guint32 idx = klass->method.first + i;
497                         guint32 cols [MONO_PARAM_SIZE];
498                         guint param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
499
500                         if (idx + 1 < methodt->rows)
501                                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
502                         else
503                                 lastp = paramt->rows;
504                         for (i = param_index; i < lastp; ++i) {
505                                 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
506                                 if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
507                                         names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
508                         }
509                         return;
510                 }
511         }
512 }