Fri Jun 6 11:41:18 CEST 2003 Paolo Molaro <lupus@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         image->synchronized_cache = g_hash_table_new (g_direct_hash, g_direct_equal);
477
478         header = &iinfo->cli_header;
479                 
480         if (image->f == NULL){
481                 if (status)
482                         *status = MONO_IMAGE_ERROR_ERRNO;
483                 mono_image_close (image);
484                 return NULL;
485         }
486
487         if (status)
488                 *status = MONO_IMAGE_IMAGE_INVALID;
489         
490         if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
491                 goto invalid_image;
492         
493         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
494                 goto invalid_image;
495         
496         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
497
498         if (msdos.pe_offset != sizeof (msdos))
499                 fseek (image->f, msdos.pe_offset, SEEK_SET);
500         
501         if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
502                 goto invalid_image;
503
504 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
505 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
506 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
507 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
508         SWAP32 (header->coff.coff_time);
509         SWAP32 (header->coff.coff_symptr);
510         SWAP32 (header->coff.coff_symcount);
511         SWAP16 (header->coff.coff_machine);
512         SWAP16 (header->coff.coff_sections);
513         SWAP16 (header->coff.coff_opt_header_size);
514         SWAP16 (header->coff.coff_attributes);
515         /* MonoPEHeader */
516         SWAP32 (header->pe.pe_code_size);
517         SWAP32 (header->pe.pe_data_size);
518         SWAP32 (header->pe.pe_uninit_data_size);
519         SWAP32 (header->pe.pe_rva_entry_point);
520         SWAP32 (header->pe.pe_rva_code_base);
521         SWAP32 (header->pe.pe_rva_data_base);
522         SWAP16 (header->pe.pe_magic);
523
524         /* MonoPEHeaderNT: not used yet */
525         SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
526         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
527         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
528         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
529         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
530         SWAP16  (header->nt.pe_user_major);
531         SWAP16  (header->nt.pe_user_minor);
532         SWAP16  (header->nt.pe_subsys_major);
533         SWAP16  (header->nt.pe_subsys_minor);
534         SWAP32  (header->nt.pe_reserved_1);
535         SWAP32  (header->nt.pe_image_size);
536         SWAP32  (header->nt.pe_header_size);
537         SWAP32  (header->nt.pe_checksum);
538         SWAP16  (header->nt.pe_subsys_required);
539         SWAP16  (header->nt.pe_dll_flags);
540         SWAP32  (header->nt.pe_stack_reserve);
541         SWAP32  (header->nt.pe_stack_commit);
542         SWAP32  (header->nt.pe_heap_reserve);
543         SWAP32  (header->nt.pe_heap_commit);
544         SWAP32  (header->nt.pe_loader_flags);
545         SWAP32  (header->nt.pe_data_dir_count);
546
547         /* MonoDotNetHeader: mostly unused */
548         SWAPPDE (header->datadir.pe_export_table);
549         SWAPPDE (header->datadir.pe_import_table);
550         SWAPPDE (header->datadir.pe_resource_table);
551         SWAPPDE (header->datadir.pe_exception_table);
552         SWAPPDE (header->datadir.pe_certificate_table);
553         SWAPPDE (header->datadir.pe_reloc_table);
554         SWAPPDE (header->datadir.pe_debug);
555         SWAPPDE (header->datadir.pe_copyright);
556         SWAPPDE (header->datadir.pe_global_ptr);
557         SWAPPDE (header->datadir.pe_tls_table);
558         SWAPPDE (header->datadir.pe_load_config_table);
559         SWAPPDE (header->datadir.pe_bound_import);
560         SWAPPDE (header->datadir.pe_iat);
561         SWAPPDE (header->datadir.pe_delay_import_desc);
562         SWAPPDE (header->datadir.pe_cli_header);
563         SWAPPDE (header->datadir.pe_reserved);
564
565 #undef SWAP32
566 #undef SWAP16
567 #undef SWAPPDE
568 #endif
569
570         if (header->coff.coff_machine != 0x14c)
571                 goto invalid_image;
572
573         if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
574                 goto invalid_image;
575
576         if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
577                 goto invalid_image;
578
579 #if 0
580         /*
581          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
582          * which produces binaries with 7.0.  From Sergey:
583          *
584          * The reason is that MSVC7 uses traditional compile/link
585          * sequence for CIL executables, and VS.NET (and Framework
586          * SDK) includes linker version 7, that puts 7.0 in this
587          * field.  That's why it's currently not possible to load VC
588          * binaries with Mono.  This field is pretty much meaningless
589          * anyway (what linker?).
590          */
591         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
592                 goto invalid_image;
593 #endif
594
595         /*
596          * FIXME: byte swap all addresses here for header.
597          */
598         
599         if (!load_section_tables (image, iinfo))
600                 goto invalid_image;
601         
602         /* Load the CLI header */
603         if (!load_cli_header (image, iinfo))
604                 goto invalid_image;
605
606         if (!load_metadata (image, iinfo))
607                 goto invalid_image;
608
609         load_class_names (image);
610
611         /* modules don't have an assembly table row */
612         if (image->tables [MONO_TABLE_ASSEMBLY].rows)
613                 image->assembly_name = mono_metadata_string_heap (image, 
614                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
615                                         0, MONO_ASSEMBLY_NAME));
616
617         image->module_name = mono_metadata_string_heap (image, 
618                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
619                                         0, MONO_MODULE_NAME));
620
621         load_modules (image, status);
622
623         if (status)
624                 *status = MONO_IMAGE_OK;
625
626         image->ref_count=1;
627
628         return image;
629
630 invalid_image:
631         mono_image_close (image);
632                 return NULL;
633 }
634
635 MonoImage *
636 mono_image_loaded (const char *name) {
637         if (strcmp (name, "mscorlib") == 0)
638                 name = "corlib";
639         if (loaded_images_hash)
640                 return g_hash_table_lookup (loaded_images_hash, name);
641         return NULL;
642 }
643
644 MonoImage *
645 mono_image_loaded_by_guid (const char *guid) {
646         if (loaded_images_guid_hash)
647                 return g_hash_table_lookup (loaded_images_guid_hash, guid);
648         return NULL;
649 }
650
651 /**
652  * mono_image_open:
653  * @fname: filename that points to the module we want to open
654  * @status: An error condition is returned in this field
655  *
656  * Retuns: An open image of type %MonoImage or NULL on error.
657  * if NULL, then check the value of @status for details on the error
658  */
659 MonoImage *
660 mono_image_open (const char *fname, MonoImageOpenStatus *status)
661 {
662         MonoImage *image;
663         
664         g_return_val_if_fail (fname != NULL, NULL);
665
666         if (loaded_images_hash){
667                 image = g_hash_table_lookup (loaded_images_hash, fname);
668                 if (image){
669                         image->ref_count++;
670                         return image;
671                 }
672         }
673
674         image = do_mono_image_open (fname, status);
675         if (image == NULL)
676                 return NULL;
677
678         if (!loaded_images_hash)
679                 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
680         g_hash_table_insert (loaded_images_hash, image->name, image);
681         if (image->assembly_name)
682                 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image);
683         
684         if (!loaded_images_guid_hash)
685                 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
686         g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
687
688         return image;
689 }
690
691 static void
692 free_hash_table(gpointer key, gpointer val, gpointer user_data)
693 {
694         g_hash_table_destroy ((GHashTable*)val);
695 }
696
697 /**
698  * mono_image_close:
699  * @image: The image file we wish to close
700  *
701  * Closes an image file, deallocates all memory consumed and
702  * unmaps all possible sections of the file
703  */
704 void
705 mono_image_close (MonoImage *image)
706 {
707         g_return_if_fail (image != NULL);
708
709         if (--image->ref_count)
710                 return;
711
712         if (!loaded_images_hash)
713                 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
714         g_hash_table_remove (loaded_images_hash, image->name);
715         
716         if (image->f)
717                 fclose (image->f);
718
719         g_free (image->name);
720
721         g_hash_table_destroy (image->method_cache);
722         g_hash_table_destroy (image->class_cache);
723         g_hash_table_destroy (image->array_cache);
724         g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
725         g_hash_table_destroy (image->name_cache);
726         g_hash_table_destroy (image->native_wrapper_cache);
727         g_hash_table_destroy (image->managed_wrapper_cache);
728         g_hash_table_destroy (image->delegate_begin_invoke_cache);
729         g_hash_table_destroy (image->delegate_end_invoke_cache);
730         g_hash_table_destroy (image->delegate_invoke_cache);
731         g_hash_table_destroy (image->remoting_invoke_cache);
732         g_hash_table_destroy (image->runtime_invoke_cache);
733         
734         if (image->raw_metadata != NULL)
735                 mono_raw_buffer_free (image->raw_metadata);
736         
737         if (image->image_info){
738                 MonoCLIImageInfo *ii = image->image_info;
739                 int i;
740
741                 for (i = 0; i < ii->cli_section_count; i++){
742                         if (!ii->cli_sections [i])
743                                 continue;
744                         mono_raw_buffer_free (ii->cli_sections [i]);
745                 }
746                 if (ii->cli_section_tables)
747                         g_free (ii->cli_section_tables);
748                 if (ii->cli_sections)
749                         g_free (ii->cli_sections);
750                 g_free (image->image_info);
751         }
752         
753         g_free (image);
754 }
755
756 /** 
757  * mono_image_strerror:
758  * @status: an code indicating the result from a recent operation
759  *
760  * Returns: a string describing the error
761  */
762 const char *
763 mono_image_strerror (MonoImageOpenStatus status)
764 {
765         switch (status){
766         case MONO_IMAGE_OK:
767                 return "success";
768         case MONO_IMAGE_ERROR_ERRNO:
769                 return strerror (errno);
770         case MONO_IMAGE_IMAGE_INVALID:
771                 return "File does not contain a valid CIL image";
772         case MONO_IMAGE_MISSING_ASSEMBLYREF:
773                 return "An assembly was referenced, but could not be found";
774         }
775         return "Internal error";
776 }
777
778 static gpointer
779 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
780                                guint32 lang_id, gunichar2 *name,
781                                MonoPEResourceDirEntry *entry,
782                                MonoPEResourceDir *root, guint32 level)
783 {
784         gboolean is_string=entry->name_is_string;
785
786         /* Level 0 holds a directory entry for each type of resource
787          * (identified by ID or name).
788          *
789          * Level 1 holds a directory entry for each named resource
790          * item, and each "anonymous" item of a particular type of
791          * resource.
792          *
793          * Level 2 holds a directory entry for each language pointing to
794          * the actual data.
795          */
796
797         if(level==0) {
798                 if((is_string==FALSE && entry->name_offset!=res_id) ||
799                    (is_string==TRUE)) {
800                         return(NULL);
801                 }
802         } else if (level==1) {
803 #if 0
804                 if(name!=NULL &&
805                    is_string==TRUE && name!=lookup (entry->name_offset)) {
806                         return(NULL);
807                 }
808 #endif
809         } else if (level==2) {
810                 if((is_string==FALSE && entry->name_offset!=lang_id) ||
811                    (is_string==TRUE)) {
812                         return(NULL);
813                 }
814         } else {
815                 g_assert_not_reached ();
816         }
817
818         if(entry->is_dir==TRUE) {
819                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
820                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
821                 guint32 entries, i;
822                 
823                 entries=res_dir->res_named_entries + res_dir->res_id_entries;
824
825                 for(i=0; i<entries; i++) {
826                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
827                         gpointer ret;
828                         
829                         ret=mono_image_walk_resource_tree (info, res_id,
830                                                            lang_id, name,
831                                                            sub_entry, root,
832                                                            level+1);
833                         if(ret!=NULL) {
834                                 return(ret);
835                         }
836                 }
837
838                 return(NULL);
839         } else {
840                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
841                 
842                 return(data_entry);
843         }
844 }
845
846 gpointer
847 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
848 {
849         MonoCLIImageInfo *info;
850         MonoDotNetHeader *header;
851         MonoPEDatadir *datadir;
852         MonoPEDirEntry *rsrc;
853         MonoPEResourceDir *resource_dir;
854         MonoPEResourceDirEntry *res_entries;
855         guint32 entries, i;
856
857         if(image==NULL) {
858                 return(NULL);
859         }
860
861         info=image->image_info;
862         if(info==NULL) {
863                 return(NULL);
864         }
865
866         header=&info->cli_header;
867         if(header==NULL) {
868                 return(NULL);
869         }
870
871         datadir=&header->datadir;
872         if(datadir==NULL) {
873                 return(NULL);
874         }
875
876         rsrc=&datadir->pe_resource_table;
877         if(rsrc==NULL) {
878                 return(NULL);
879         }
880
881         resource_dir=(MonoPEResourceDir *)mono_cli_rva_map (info, rsrc->rva);
882         if(resource_dir==NULL) {
883                 return(NULL);
884         }
885         
886         entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
887         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
888         
889         for(i=0; i<entries; i++) {
890                 MonoPEResourceDirEntry *entry=&res_entries[i];
891                 gpointer ret;
892                 
893                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
894                                                    name, entry, resource_dir,
895                                                    0);
896                 if(ret!=NULL) {
897                         return(ret);
898                 }
899         }
900
901         return(NULL);
902 }
903
904 guint32
905 mono_image_get_entry_point (MonoImage *image)
906 {
907         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
908 }
909
910 const char*
911 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
912 {
913         MonoCLIImageInfo *iinfo = image->image_info;
914         MonoCLIHeader *ch = &iinfo->cli_cli_header;
915         const char* data;
916
917         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
918                 return NULL;
919         
920         data = mono_cli_rva_map (iinfo, ch->ch_resources.rva);
921         if (!data)
922                 return NULL;
923         data += offset;
924         if (size)
925                 *size = read32 (data);
926         data += 4;
927         return data;
928 }
929
930 const char*
931 mono_image_get_strong_name (MonoImage *image, guint32 *size)
932 {
933         MonoCLIImageInfo *iinfo = image->image_info;
934         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
935         const char* data;
936
937         if (!de->size || !de->rva)
938                 return NULL;
939         data = mono_cli_rva_map (iinfo, de->rva);
940         if (!data)
941                 return NULL;
942         if (size)
943                 *size = de->size;
944         return data;
945 }
946
947 guint32
948 mono_image_strong_name_position (MonoImage *image, guint32 *size)
949 {
950         MonoCLIImageInfo *iinfo = image->image_info;
951         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
952         const int top = iinfo->cli_section_count;
953         MonoSectionTable *tables = iinfo->cli_section_tables;
954         int i;
955         guint32 addr = de->rva;
956         
957         if (size)
958                 *size = de->size;
959         if (!de->size || !de->rva)
960                 return 0;
961         for (i = 0; i < top; i++){
962                 if ((addr >= tables->st_virtual_address) &&
963                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
964                         return tables->st_raw_data_ptr +
965                                 (addr - tables->st_virtual_address);
966                 }
967                 tables++;
968         }
969
970         return 0;
971 }
972
973 const char*
974 mono_image_get_public_key (MonoImage *image, guint32 *size)
975 {
976         const char *pubkey;
977         guint32 len, tok;
978         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
979                 return NULL;
980         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
981         if (!tok)
982                 return NULL;
983         pubkey = mono_metadata_blob_heap (image, tok);
984         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
985         if (size)
986                 *size = len;
987         return pubkey;
988 }
989