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