2004-01-19 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / metadata / image.c
1 /*
2  * image.c: Routines for manipulating an image stored in an
3  * extended PE/COFF file.
4  * 
5  * Authors:
6  *   Miguel de Icaza (miguel@ximian.com)
7  *   Paolo Molaro (lupus@ximian.com)
8  *
9  * (C) 2001-2003 Ximian, Inc.  http://www.ximian.com
10  *
11  */
12 #include <config.h>
13 #include <stdio.h>
14 #include <glib.h>
15 #include <errno.h>
16 #include <time.h>
17 #include <string.h>
18 #include "image.h"
19 #include "cil-coff.h"
20 #include "rawbuffer.h"
21 #include "mono-endian.h"
22 #include "private.h"
23 #include "tabledefs.h"
24 #include "tokentype.h"
25 #include <mono/io-layer/io-layer.h>
26
27 #define INVALID_ADDRESS 0xffffffff
28
29 /*
30  * Keeps track of the various assemblies loaded
31  */
32 static GHashTable *loaded_images_hash;
33 static GHashTable *loaded_images_guid_hash;
34
35 static CRITICAL_SECTION images_mutex;
36
37 guint32
38 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
39 {
40         const int top = iinfo->cli_section_count;
41         MonoSectionTable *tables = iinfo->cli_section_tables;
42         int i;
43         
44         for (i = 0; i < top; i++){
45                 if ((addr >= tables->st_virtual_address) &&
46                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
47                         return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
48                 }
49                 tables++;
50         }
51         return INVALID_ADDRESS;
52 }
53
54 char *
55 mono_cli_rva_map (MonoCLIImageInfo *iinfo, guint32 addr)
56 {
57         const int top = iinfo->cli_section_count;
58         MonoSectionTable *tables = iinfo->cli_section_tables;
59         int i;
60         
61         for (i = 0; i < top; i++){
62                 if ((addr >= tables->st_virtual_address) &&
63                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
64                         return (char*)iinfo->cli_sections [i] +
65                                 (addr - tables->st_virtual_address);
66                 }
67                 tables++;
68         }
69         return NULL;
70 }
71
72 /**
73  * mono_images_init:
74  *
75  *  Initialize the global variables used by this module.
76  */
77 void
78 mono_images_init (void)
79 {
80         InitializeCriticalSection (&images_mutex);
81
82         loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
83         loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
84 }
85
86 /**
87  * mono_image_ensure_section_idx:
88  * @image: The image we are operating on
89  * @section: section number that we will load/map into memory
90  *
91  * This routine makes sure that we have an in-memory copy of
92  * an image section (.text, .rsrc, .data).
93  *
94  * Returns: TRUE on success
95  */
96 int
97 mono_image_ensure_section_idx (MonoImage *image, int section)
98 {
99         MonoCLIImageInfo *iinfo = image->image_info;
100         MonoSectionTable *sect;
101         gboolean writable;
102         
103         g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
104
105         if (iinfo->cli_sections [section] != NULL)
106                 return TRUE;
107
108         sect = &iinfo->cli_section_tables [section];
109         
110         writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
111
112         if (!image->f) {
113                 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
114                         return FALSE;
115                 /* FIXME: we ignore the writable flag since we don't patch the binary */
116                 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
117                 return TRUE;
118         }
119         iinfo->cli_sections [section] = mono_raw_buffer_load (
120                 fileno (image->f), writable,
121                 sect->st_raw_data_ptr, sect->st_raw_data_size);
122
123         if (iinfo->cli_sections [section] == NULL)
124                 return FALSE;
125
126         return TRUE;
127 }
128
129 /**
130  * mono_image_ensure_section:
131  * @image: The image we are operating on
132  * @section: section name that we will load/map into memory
133  *
134  * This routine makes sure that we have an in-memory copy of
135  * an image section (.text, .rsrc, .data).
136  *
137  * Returns: TRUE on success
138  */
139 int
140 mono_image_ensure_section (MonoImage *image, const char *section)
141 {
142         MonoCLIImageInfo *ii = image->image_info;
143         int i;
144         
145         for (i = 0; i < ii->cli_section_count; i++){
146                 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
147                         continue;
148                 
149                 return mono_image_ensure_section_idx (image, i);
150         }
151         return FALSE;
152 }
153
154 static int
155 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
156 {
157         const int top = iinfo->cli_header.coff.coff_sections;
158         int i;
159
160         iinfo->cli_section_count = top;
161         iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
162         iinfo->cli_sections = g_new0 (void *, top);
163         
164         for (i = 0; i < top; i++){
165                 MonoSectionTable *t = &iinfo->cli_section_tables [i];
166
167                 if (!image->f) {
168                         if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
169                                 return FALSE;
170                         memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
171                         offset += sizeof (MonoSectionTable);
172                 } else {
173                         if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
174                                 return FALSE;
175                 }
176
177 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
178                 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
179                 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
180                 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
181                 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
182                 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
183                 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
184                 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
185                 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
186                 t->st_flags = GUINT32_FROM_LE (t->st_flags);
187 #endif
188                 /* consistency checks here */
189         }
190
191         for (i = 0; i < top; i++)
192                 if (!mono_image_ensure_section_idx (image, i))
193                         return FALSE;
194         
195         return TRUE;
196 }
197
198 static gboolean
199 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
200 {
201         guint32 offset;
202         int n;
203         
204         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
205         if (offset == INVALID_ADDRESS)
206                 return FALSE;
207
208         if (!image->f) {
209                 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
210                         return FALSE;
211                 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
212         } else {
213                 if (fseek (image->f, offset, SEEK_SET) != 0)
214                         return FALSE;
215         
216                 if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
217                         return FALSE;
218         }
219
220 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
221 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
222 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
223 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
224         SWAP32 (iinfo->cli_cli_header.ch_size);
225         SWAP32 (iinfo->cli_cli_header.ch_flags);
226         SWAP32 (iinfo->cli_cli_header.ch_entry_point);
227         SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
228         SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
229         SWAPPDE (iinfo->cli_cli_header.ch_metadata);
230         SWAPPDE (iinfo->cli_cli_header.ch_resources);
231         SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
232         SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
233         SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
234         SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
235         SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
236         SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
237         SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
238         SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
239         SWAPPDE (iinfo->cli_cli_header.ch_module_image);
240         SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
241         SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
242         SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
243         SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
244 #undef SWAP32
245 #undef SWAP16
246 #undef SWAPPDE
247 #endif
248         /* Catch new uses of the fields that are supposed to be zero */
249
250         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
251             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
252             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
253             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
254             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
255             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
256             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
257             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
258             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
259
260                 /*
261                  * No need to scare people who are testing this, I am just
262                  * labelling this as a LAMESPEC
263                  */
264                 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
265
266         }
267             
268         return TRUE;
269 }
270
271 static gboolean
272 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
273 {
274         guint32 offset, size;
275         guint16 streams;
276         int i;
277         guint32 pad;
278         char *ptr;
279         
280         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
281         if (offset == INVALID_ADDRESS)
282                 return FALSE;
283
284         size = iinfo->cli_cli_header.ch_metadata.size;
285
286         if (!image->f) {
287                 if (offset + size > image->raw_data_len)
288                         return FALSE;
289                 image->raw_metadata = image->raw_data + offset;
290         } else {
291                 image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
292                 if (image->raw_metadata == NULL)
293                         return FALSE;
294         }
295
296         ptr = image->raw_metadata;
297
298         if (strncmp (ptr, "BSJB", 4) == 0){
299                 guint32 version_string_len;
300
301                 ptr += 12;
302                 version_string_len = read32 (ptr);
303                 ptr += 4;
304                 image->version = g_strndup (ptr, version_string_len);
305                 ptr += version_string_len;
306                 pad = ptr - image->raw_metadata;
307                 if (pad % 4)
308                         ptr += 4 - (pad % 4);
309         } else
310                 return FALSE;
311
312         /* skip over flags */
313         ptr += 2;
314         
315         streams = read16 (ptr);
316         ptr += 2;
317
318         for (i = 0; i < streams; i++){
319                 if (strncmp (ptr + 8, "#~", 3) == 0){
320                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
321                         image->heap_tables.size = read32 (ptr + 4);
322                         ptr += 8 + 3;
323                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
324                         image->heap_strings.data = image->raw_metadata + read32 (ptr);
325                         image->heap_strings.size = read32 (ptr + 4);
326                         ptr += 8 + 9;
327                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
328                         image->heap_us.data = image->raw_metadata + read32 (ptr);
329                         image->heap_us.size = read32 (ptr + 4);
330                         ptr += 8 + 4;
331                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
332                         image->heap_blob.data = image->raw_metadata + read32 (ptr);
333                         image->heap_blob.size = read32 (ptr + 4);
334                         ptr += 8 + 6;
335                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
336                         image->heap_guid.data = image->raw_metadata + read32 (ptr);
337                         image->heap_guid.size = read32 (ptr + 4);
338                         ptr += 8 + 6;
339                 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
340                         g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
341                         return FALSE;
342                 } else {
343                         g_message ("Unknown heap type: %s\n", ptr + 8);
344                         ptr += 8 + strlen (ptr) + 1;
345                 }
346                 pad = ptr - image->raw_metadata;
347                 if (pad % 4)
348                         ptr += 4 - (pad % 4);
349         }
350
351         g_assert (image->heap_guid.data);
352         g_assert (image->heap_guid.size >= 16);
353
354         image->guid = mono_guid_to_string (image->heap_guid.data);
355
356         return TRUE;
357 }
358
359 /*
360  * Load representation of logical metadata tables, from the "#~" stream
361  */
362 static gboolean
363 load_tables (MonoImage *image)
364 {
365         const char *heap_tables = image->heap_tables.data;
366         const guint32 *rows;
367         guint64 valid_mask, sorted_mask;
368         int valid = 0, table;
369         int heap_sizes;
370         
371         heap_sizes = heap_tables [6];
372         image->idx_string_wide = ((heap_sizes & 0x01) == 1);
373         image->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
374         image->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
375         
376         valid_mask = read64 (heap_tables + 8);
377         sorted_mask = read64 (heap_tables + 16);
378         rows = (const guint32 *) (heap_tables + 24);
379         
380         for (table = 0; table < 64; table++){
381                 if ((valid_mask & ((guint64) 1 << table)) == 0){
382                         image->tables [table].rows = 0;
383                         continue;
384                 }
385                 if (table > MONO_TABLE_LAST) {
386                         g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
387                 }
388                 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
389                         g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
390                 }*/
391                 image->tables [table].rows = read32 (rows);
392                 rows++;
393                 valid++;
394         }
395
396         image->tables_base = (heap_tables + 24) + (4 * valid);
397
398         /* They must be the same */
399         g_assert ((const void *) image->tables_base == (const void *) rows);
400
401         mono_metadata_compute_table_bases (image);
402         return TRUE;
403 }
404
405 static gboolean
406 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
407 {
408         if (!load_metadata_ptrs (image, iinfo))
409                 return FALSE;
410
411         return load_tables (image);
412 }
413
414 void
415 mono_image_add_to_name_cache (MonoImage *image, const char *nspace, 
416                                                           const char *name, guint32 index)
417 {
418         GHashTable *nspace_table;
419         GHashTable *name_cache = image->name_cache;
420
421         if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
422                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
423                 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
424         }
425         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
426 }
427
428 static void
429 load_modules (MonoImage *image, MonoImageOpenStatus *status)
430 {
431         MonoTableInfo *t;
432         int i;
433         char *base_dir;
434
435         if (image->modules)
436                 return;
437
438         t = &image->tables [MONO_TABLE_MODULEREF];
439         image->modules = g_new0 (MonoImage *, t->rows);
440         base_dir = g_path_get_dirname (image->name);
441         for (i = 0; i < t->rows; i++){
442                 char *module_ref;
443                 const char *name;
444                 guint32 cols [MONO_MODULEREF_SIZE];
445
446                 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
447                 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
448                 module_ref = g_build_filename (base_dir, name, NULL);
449                 image->modules [i] = mono_image_open (module_ref, status);
450                 if (image->modules [i]) {
451                         //g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly);
452                 }
453                 /* 
454                  * FIXME: what do we do here? it could be a native dll...
455                  * We should probably do lazy-loading of modules.
456                  */
457                 if (status)
458                         *status = MONO_IMAGE_OK;
459                 g_free (module_ref);
460         }
461
462         g_free (base_dir);
463 }
464
465 static void
466 load_class_names (MonoImage *image)
467 {
468         MonoTableInfo  *t = &image->tables [MONO_TABLE_TYPEDEF];
469         guint32 cols [MONO_TYPEDEF_SIZE];
470         const char *name;
471         const char *nspace;
472         guint32 i, visib, nspace_index;
473         GHashTable *name_cache2, *nspace_table;
474
475         /* Temporary hash table to avoid lookups in the nspace_table */
476         name_cache2 = g_hash_table_new (NULL, NULL);
477
478         for (i = 1; i <= t->rows; ++i) {
479                 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
480                 /* nested types are accessed from the nesting name */
481                 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
482                 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
483                         continue;
484                 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
485                 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
486
487                 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
488                 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
489                 if (!nspace_table) {
490                         nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
491                         g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
492                         g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
493                                                                  nspace_table);
494                 }
495                 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
496         }
497
498         /* Load type names from EXPORTEDTYPES table */
499         {
500                 MonoTableInfo  *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
501                 guint32 cols [MONO_EXP_TYPE_SIZE];
502                 int i;
503
504                 for (i = 0; i < t->rows; ++i) {
505                         mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
506                         name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
507                         nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
508
509                         nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
510                         nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
511                         if (!nspace_table) {
512                                 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
513                                 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
514                                 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
515                                                                          nspace_table);
516                         }
517                         g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
518                 }
519         }
520
521         g_hash_table_destroy (name_cache2);
522 }
523
524 static void
525 register_guid (gpointer key, gpointer value, gpointer user_data)
526 {
527         MonoImage *image = (MonoImage*)value;
528
529         if (!g_hash_table_lookup (loaded_images_guid_hash, image))
530                 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
531 }
532
533 static void
534 build_guid_table (void)
535 {
536         g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
537 }
538
539 void
540 mono_image_init (MonoImage *image)
541 {
542         image->method_cache = g_hash_table_new (NULL, NULL);
543         image->class_cache = g_hash_table_new (NULL, NULL);
544         image->field_cache = g_hash_table_new (NULL, NULL);
545         image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
546         image->array_cache = g_hash_table_new (NULL, NULL);
547
548         image->delegate_begin_invoke_cache = 
549                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
550                                   (GCompareFunc)mono_metadata_signature_equal);
551         image->delegate_end_invoke_cache = 
552                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
553                                   (GCompareFunc)mono_metadata_signature_equal);
554         image->delegate_invoke_cache = 
555                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
556                                   (GCompareFunc)mono_metadata_signature_equal);
557
558         image->runtime_invoke_cache = g_hash_table_new (NULL, NULL);
559         image->managed_wrapper_cache = g_hash_table_new (NULL, NULL);
560         image->native_wrapper_cache = g_hash_table_new (NULL, NULL);
561         image->remoting_invoke_cache = g_hash_table_new (NULL, NULL);
562         image->synchronized_cache = g_hash_table_new (NULL, NULL);
563
564         image->generics_cache = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GEqualFunc)mono_metadata_type_equal);
565         image->typespec_cache = g_hash_table_new (NULL, NULL);
566 }
567
568 static MonoImage *
569 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
570 {
571         MonoCLIImageInfo *iinfo;
572         MonoDotNetHeader *header;
573         MonoMSDOSHeader msdos;
574         int n;
575         guint32 offset = 0;
576
577         mono_image_init (image);
578
579         iinfo = image->image_info;
580         header = &iinfo->cli_header;
581                 
582         if (status)
583                 *status = MONO_IMAGE_IMAGE_INVALID;
584
585         if (!image->f) {
586                 if (offset + sizeof (msdos) > image->raw_data_len)
587                         goto invalid_image;
588                 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
589         } else {
590                 if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
591                         goto invalid_image;
592         }
593         
594         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
595                 goto invalid_image;
596         
597         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
598
599         if (msdos.pe_offset != sizeof (msdos)) {
600                 if (image->f)
601                         fseek (image->f, msdos.pe_offset, SEEK_SET);
602         }
603         offset = msdos.pe_offset;
604
605         if (!image->f) {
606                 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
607                         goto invalid_image;
608                 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
609                 offset += sizeof (MonoDotNetHeader);
610         } else {
611                 if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
612                         goto invalid_image;
613         }
614
615 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
616 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
617 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
618 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
619         SWAP32 (header->coff.coff_time);
620         SWAP32 (header->coff.coff_symptr);
621         SWAP32 (header->coff.coff_symcount);
622         SWAP16 (header->coff.coff_machine);
623         SWAP16 (header->coff.coff_sections);
624         SWAP16 (header->coff.coff_opt_header_size);
625         SWAP16 (header->coff.coff_attributes);
626         /* MonoPEHeader */
627         SWAP32 (header->pe.pe_code_size);
628         SWAP32 (header->pe.pe_data_size);
629         SWAP32 (header->pe.pe_uninit_data_size);
630         SWAP32 (header->pe.pe_rva_entry_point);
631         SWAP32 (header->pe.pe_rva_code_base);
632         SWAP32 (header->pe.pe_rva_data_base);
633         SWAP16 (header->pe.pe_magic);
634
635         /* MonoPEHeaderNT: not used yet */
636         SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
637         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
638         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
639         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
640         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
641         SWAP16  (header->nt.pe_user_major);
642         SWAP16  (header->nt.pe_user_minor);
643         SWAP16  (header->nt.pe_subsys_major);
644         SWAP16  (header->nt.pe_subsys_minor);
645         SWAP32  (header->nt.pe_reserved_1);
646         SWAP32  (header->nt.pe_image_size);
647         SWAP32  (header->nt.pe_header_size);
648         SWAP32  (header->nt.pe_checksum);
649         SWAP16  (header->nt.pe_subsys_required);
650         SWAP16  (header->nt.pe_dll_flags);
651         SWAP32  (header->nt.pe_stack_reserve);
652         SWAP32  (header->nt.pe_stack_commit);
653         SWAP32  (header->nt.pe_heap_reserve);
654         SWAP32  (header->nt.pe_heap_commit);
655         SWAP32  (header->nt.pe_loader_flags);
656         SWAP32  (header->nt.pe_data_dir_count);
657
658         /* MonoDotNetHeader: mostly unused */
659         SWAPPDE (header->datadir.pe_export_table);
660         SWAPPDE (header->datadir.pe_import_table);
661         SWAPPDE (header->datadir.pe_resource_table);
662         SWAPPDE (header->datadir.pe_exception_table);
663         SWAPPDE (header->datadir.pe_certificate_table);
664         SWAPPDE (header->datadir.pe_reloc_table);
665         SWAPPDE (header->datadir.pe_debug);
666         SWAPPDE (header->datadir.pe_copyright);
667         SWAPPDE (header->datadir.pe_global_ptr);
668         SWAPPDE (header->datadir.pe_tls_table);
669         SWAPPDE (header->datadir.pe_load_config_table);
670         SWAPPDE (header->datadir.pe_bound_import);
671         SWAPPDE (header->datadir.pe_iat);
672         SWAPPDE (header->datadir.pe_delay_import_desc);
673         SWAPPDE (header->datadir.pe_cli_header);
674         SWAPPDE (header->datadir.pe_reserved);
675
676 #undef SWAP32
677 #undef SWAP16
678 #undef SWAPPDE
679 #endif
680
681         if (header->coff.coff_machine != 0x14c)
682                 goto invalid_image;
683
684         if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
685                 goto invalid_image;
686
687         if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
688                 goto invalid_image;
689
690 #if 0
691         /*
692          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
693          * which produces binaries with 7.0.  From Sergey:
694          *
695          * The reason is that MSVC7 uses traditional compile/link
696          * sequence for CIL executables, and VS.NET (and Framework
697          * SDK) includes linker version 7, that puts 7.0 in this
698          * field.  That's why it's currently not possible to load VC
699          * binaries with Mono.  This field is pretty much meaningless
700          * anyway (what linker?).
701          */
702         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
703                 goto invalid_image;
704 #endif
705
706         /*
707          * FIXME: byte swap all addresses here for header.
708          */
709         
710         if (!load_section_tables (image, iinfo, offset))
711                 goto invalid_image;
712         
713         /* Load the CLI header */
714         if (!load_cli_header (image, iinfo))
715                 goto invalid_image;
716
717         if (!load_metadata (image, iinfo))
718                 goto invalid_image;
719
720         load_class_names (image);
721
722         /* modules don't have an assembly table row */
723         if (image->tables [MONO_TABLE_ASSEMBLY].rows)
724                 image->assembly_name = mono_metadata_string_heap (image, 
725                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
726                                         0, MONO_ASSEMBLY_NAME));
727
728         image->module_name = mono_metadata_string_heap (image, 
729                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
730                                         0, MONO_MODULE_NAME));
731
732         load_modules (image, status);
733
734         if (status)
735                 *status = MONO_IMAGE_OK;
736
737         image->ref_count=1;
738
739         return image;
740
741 invalid_image:
742         mono_image_close (image);
743                 return NULL;
744 }
745
746 static MonoImage *
747 do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
748 {
749         MonoCLIImageInfo *iinfo;
750         MonoImage *image;
751         FILE *filed;
752
753         if ((filed = fopen (fname, "rb")) == NULL){
754                 if (status)
755                         *status = MONO_IMAGE_ERROR_ERRNO;
756                 return NULL;
757         }
758
759         image = g_new0 (MonoImage, 1);
760         image->ref_count = 1;
761         image->f = filed;
762         image->name = g_strdup (fname);
763         iinfo = g_new0 (MonoCLIImageInfo, 1);
764         image->image_info = iinfo;
765
766         return do_mono_image_load (image, status);
767 }
768
769 MonoImage *
770 mono_image_loaded (const char *name)
771 {
772         MonoImage *res;
773         
774         if (strcmp (name, "corlib") == 0)
775                 name = "mscorlib";
776
777         EnterCriticalSection (&images_mutex);
778         res = g_hash_table_lookup (loaded_images_hash, name);
779         LeaveCriticalSection (&images_mutex);
780         return res;
781 }
782
783 MonoImage *
784 mono_image_loaded_by_guid (const char *guid)
785 {
786         MonoImage *res;
787
788         EnterCriticalSection (&images_mutex);
789         res = g_hash_table_lookup (loaded_images_guid_hash, guid);
790         LeaveCriticalSection (&images_mutex);
791         return res;
792 }
793
794 MonoImage *
795 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
796 {
797         MonoCLIImageInfo *iinfo;
798         MonoImage *image;
799         char *datac;
800
801         if (!data || !data_len) {
802                 if (status)
803                         *status = MONO_IMAGE_IMAGE_INVALID;
804                 return NULL;
805         }
806         datac = data;
807         if (need_copy) {
808                 datac = g_try_malloc (data_len);
809                 if (!datac) {
810                         if (status)
811                                 *status = MONO_IMAGE_ERROR_ERRNO;
812                         return NULL;
813                 }
814                 memcpy (datac, data, data_len);
815         }
816
817         image = g_new0 (MonoImage, 1);
818         image->ref_count = 1;
819         image->raw_data = datac;
820         image->raw_data_len = data_len;
821         image->raw_data_allocated = need_copy;
822         image->name = g_strdup_printf ("data-%p", datac);
823         iinfo = g_new0 (MonoCLIImageInfo, 1);
824         image->image_info = iinfo;
825
826         return do_mono_image_load (image, status);
827 }
828
829 /**
830  * mono_image_open:
831  * @fname: filename that points to the module we want to open
832  * @status: An error condition is returned in this field
833  *
834  * Retuns: An open image of type %MonoImage or NULL on error.
835  * if NULL, then check the value of @status for details on the error
836  */
837 MonoImage *
838 mono_image_open (const char *fname, MonoImageOpenStatus *status)
839 {
840         MonoImage *image, *image2;
841         
842         g_return_val_if_fail (fname != NULL, NULL);
843
844         /*
845          * The easiest solution would be to do all the loading inside the mutex,
846          * but that would lead to scalability problems. So we let the loading
847          * happen outside the mutex, and if multiple threads happen to load
848          * the same image, we discard all but the first copy.
849          */
850         EnterCriticalSection (&images_mutex);
851         image = g_hash_table_lookup (loaded_images_hash, fname);
852         if (image){
853                 image->ref_count++;
854                 LeaveCriticalSection (&images_mutex);
855                 return image;
856         }
857         LeaveCriticalSection (&images_mutex);
858
859         image = do_mono_image_open (fname, status);
860         if (image == NULL)
861                 return NULL;
862
863         EnterCriticalSection (&images_mutex);
864         image2 = g_hash_table_lookup (loaded_images_hash, fname);
865         if (image2) {
866                 /* Somebody else beat us to it */
867                 image2->ref_count ++;
868                 LeaveCriticalSection (&images_mutex);
869                 mono_image_close (image);
870
871                 return image2;
872         }
873         g_hash_table_insert (loaded_images_hash, image->name, image);
874         if (image->assembly_name)
875                 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image); 
876         g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
877         LeaveCriticalSection (&images_mutex);
878
879         return image;
880 }
881
882 static void
883 free_hash_table (gpointer key, gpointer val, gpointer user_data)
884 {
885         g_hash_table_destroy ((GHashTable*)val);
886 }
887
888 /**
889  * mono_image_close:
890  * @image: The image file we wish to close
891  *
892  * Closes an image file, deallocates all memory consumed and
893  * unmaps all possible sections of the file
894  */
895 void
896 mono_image_close (MonoImage *image)
897 {
898         MonoImage *image2;
899
900         g_return_if_fail (image != NULL);
901
902         EnterCriticalSection (&images_mutex);
903         if (--image->ref_count) {
904                 LeaveCriticalSection (&images_mutex);
905                 return;
906         }
907         image2 = g_hash_table_lookup (loaded_images_hash, image->name);
908         if (image == image2) {
909                 /* This is not true if we are called from mono_image_open () */
910                 g_hash_table_remove (loaded_images_hash, image->name);
911                 if (image->assembly_name)
912                         g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);        
913                 g_hash_table_remove (loaded_images_guid_hash, image->guid);
914                 /* Multiple images might have the same guid */
915                 build_guid_table ();
916         }       
917         LeaveCriticalSection (&images_mutex);
918
919         if (image->f)
920                 fclose (image->f);
921         if (image->raw_data_allocated)
922                 g_free (image->raw_data);
923
924         g_free (image->name);
925         g_free (image->files);
926
927         g_hash_table_destroy (image->method_cache);
928         g_hash_table_destroy (image->class_cache);
929         g_hash_table_destroy (image->field_cache);
930         g_hash_table_destroy (image->array_cache);
931         g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
932         g_hash_table_destroy (image->name_cache);
933         g_hash_table_destroy (image->native_wrapper_cache);
934         g_hash_table_destroy (image->managed_wrapper_cache);
935         g_hash_table_destroy (image->delegate_begin_invoke_cache);
936         g_hash_table_destroy (image->delegate_end_invoke_cache);
937         g_hash_table_destroy (image->delegate_invoke_cache);
938         g_hash_table_destroy (image->remoting_invoke_cache);
939         g_hash_table_destroy (image->runtime_invoke_cache);
940         
941         if (image->raw_metadata != NULL)
942                 mono_raw_buffer_free (image->raw_metadata);
943         
944         if (image->image_info){
945                 MonoCLIImageInfo *ii = image->image_info;
946                 int i;
947
948                 for (i = 0; i < ii->cli_section_count; i++){
949                         if (!ii->cli_sections [i])
950                                 continue;
951                         mono_raw_buffer_free (ii->cli_sections [i]);
952                 }
953                 if (ii->cli_section_tables)
954                         g_free (ii->cli_section_tables);
955                 if (ii->cli_sections)
956                         g_free (ii->cli_sections);
957                 g_free (image->image_info);
958         }
959
960         g_free (image);
961 }
962
963 /** 
964  * mono_image_strerror:
965  * @status: an code indicating the result from a recent operation
966  *
967  * Returns: a string describing the error
968  */
969 const char *
970 mono_image_strerror (MonoImageOpenStatus status)
971 {
972         switch (status){
973         case MONO_IMAGE_OK:
974                 return "success";
975         case MONO_IMAGE_ERROR_ERRNO:
976                 return strerror (errno);
977         case MONO_IMAGE_IMAGE_INVALID:
978                 return "File does not contain a valid CIL image";
979         case MONO_IMAGE_MISSING_ASSEMBLYREF:
980                 return "An assembly was referenced, but could not be found";
981         }
982         return "Internal error";
983 }
984
985 static gpointer
986 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
987                                guint32 lang_id, gunichar2 *name,
988                                MonoPEResourceDirEntry *entry,
989                                MonoPEResourceDir *root, guint32 level)
990 {
991         gboolean is_string=entry->name_is_string;
992
993         /* Level 0 holds a directory entry for each type of resource
994          * (identified by ID or name).
995          *
996          * Level 1 holds a directory entry for each named resource
997          * item, and each "anonymous" item of a particular type of
998          * resource.
999          *
1000          * Level 2 holds a directory entry for each language pointing to
1001          * the actual data.
1002          */
1003
1004         if(level==0) {
1005                 if((is_string==FALSE && entry->name_offset!=res_id) ||
1006                    (is_string==TRUE)) {
1007                         return(NULL);
1008                 }
1009         } else if (level==1) {
1010 #if 0
1011                 if(name!=NULL &&
1012                    is_string==TRUE && name!=lookup (entry->name_offset)) {
1013                         return(NULL);
1014                 }
1015 #endif
1016         } else if (level==2) {
1017                 if((is_string==FALSE && entry->name_offset!=lang_id) ||
1018                    (is_string==TRUE)) {
1019                         return(NULL);
1020                 }
1021         } else {
1022                 g_assert_not_reached ();
1023         }
1024
1025         if(entry->is_dir==TRUE) {
1026                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1027                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1028                 guint32 entries, i;
1029                 
1030                 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1031
1032                 for(i=0; i<entries; i++) {
1033                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1034                         gpointer ret;
1035                         
1036                         ret=mono_image_walk_resource_tree (info, res_id,
1037                                                            lang_id, name,
1038                                                            sub_entry, root,
1039                                                            level+1);
1040                         if(ret!=NULL) {
1041                                 return(ret);
1042                         }
1043                 }
1044
1045                 return(NULL);
1046         } else {
1047                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1048                 
1049                 return(data_entry);
1050         }
1051 }
1052
1053 gpointer
1054 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1055 {
1056         MonoCLIImageInfo *info;
1057         MonoDotNetHeader *header;
1058         MonoPEDatadir *datadir;
1059         MonoPEDirEntry *rsrc;
1060         MonoPEResourceDir *resource_dir;
1061         MonoPEResourceDirEntry *res_entries;
1062         guint32 entries, i;
1063
1064         if(image==NULL) {
1065                 return(NULL);
1066         }
1067
1068         info=image->image_info;
1069         if(info==NULL) {
1070                 return(NULL);
1071         }
1072
1073         header=&info->cli_header;
1074         if(header==NULL) {
1075                 return(NULL);
1076         }
1077
1078         datadir=&header->datadir;
1079         if(datadir==NULL) {
1080                 return(NULL);
1081         }
1082
1083         rsrc=&datadir->pe_resource_table;
1084         if(rsrc==NULL) {
1085                 return(NULL);
1086         }
1087
1088         resource_dir=(MonoPEResourceDir *)mono_cli_rva_map (info, rsrc->rva);
1089         if(resource_dir==NULL) {
1090                 return(NULL);
1091         }
1092         
1093         entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1094         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1095         
1096         for(i=0; i<entries; i++) {
1097                 MonoPEResourceDirEntry *entry=&res_entries[i];
1098                 gpointer ret;
1099                 
1100                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1101                                                    name, entry, resource_dir,
1102                                                    0);
1103                 if(ret!=NULL) {
1104                         return(ret);
1105                 }
1106         }
1107
1108         return(NULL);
1109 }
1110
1111 guint32
1112 mono_image_get_entry_point (MonoImage *image)
1113 {
1114         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1115 }
1116
1117 const char*
1118 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1119 {
1120         MonoCLIImageInfo *iinfo = image->image_info;
1121         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1122         const char* data;
1123
1124         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1125                 return NULL;
1126         
1127         data = mono_cli_rva_map (iinfo, ch->ch_resources.rva);
1128         if (!data)
1129                 return NULL;
1130         data += offset;
1131         if (size)
1132                 *size = read32 (data);
1133         data += 4;
1134         return data;
1135 }
1136
1137 MonoImage*
1138 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1139 {
1140         char *base_dir, *name;
1141         MonoImage *res;
1142         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1143         const char *fname;
1144         guint32 fname_id;
1145
1146         if (fileidx < 1 || fileidx > t->rows)
1147                 return NULL;
1148
1149         if (image->files && image->files [fileidx - 1])
1150                 return image->files [fileidx - 1];
1151
1152         if (!image->files)
1153                 image->files = g_new0 (MonoImage*, t->rows);
1154
1155         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1156         fname = mono_metadata_string_heap (image, fname_id);
1157         base_dir = g_path_get_dirname (image->name);
1158         name = g_build_filename (base_dir, fname, NULL);
1159         res = mono_image_open (name, NULL);
1160         if (res) {
1161                 int i;
1162                 t = &res->tables [MONO_TABLE_MODULEREF];
1163                 //g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly);
1164                 res->assembly = image->assembly;
1165                 for (i = 0; i < t->rows; ++i) {
1166                         if (res->modules [i] && !res->modules [i]->assembly)
1167                                 res->modules [i]->assembly = image->assembly;
1168                 }
1169
1170                 image->files [fileidx - 1] = res;
1171         }
1172         g_free (name);
1173         g_free (base_dir);
1174         return res;
1175 }
1176
1177 const char*
1178 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1179 {
1180         MonoCLIImageInfo *iinfo = image->image_info;
1181         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1182         const char* data;
1183
1184         if (!de->size || !de->rva)
1185                 return NULL;
1186         data = mono_cli_rva_map (iinfo, de->rva);
1187         if (!data)
1188                 return NULL;
1189         if (size)
1190                 *size = de->size;
1191         return data;
1192 }
1193
1194 guint32
1195 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1196 {
1197         MonoCLIImageInfo *iinfo = image->image_info;
1198         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1199         const int top = iinfo->cli_section_count;
1200         MonoSectionTable *tables = iinfo->cli_section_tables;
1201         int i;
1202         guint32 addr = de->rva;
1203         
1204         if (size)
1205                 *size = de->size;
1206         if (!de->size || !de->rva)
1207                 return 0;
1208         for (i = 0; i < top; i++){
1209                 if ((addr >= tables->st_virtual_address) &&
1210                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1211                         return tables->st_raw_data_ptr +
1212                                 (addr - tables->st_virtual_address);
1213                 }
1214                 tables++;
1215         }
1216
1217         return 0;
1218 }
1219
1220 const char*
1221 mono_image_get_public_key (MonoImage *image, guint32 *size)
1222 {
1223         const char *pubkey;
1224         guint32 len, tok;
1225         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1226                 return NULL;
1227         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1228         if (!tok)
1229                 return NULL;
1230         pubkey = mono_metadata_blob_heap (image, tok);
1231         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1232         if (size)
1233                 *size = len;
1234         return pubkey;
1235 }
1236