New test.
[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 "tabledefs.h"
23 #include "tokentype.h"
24 #include "metadata-internals.h"
25 #include "loader.h"
26 #include <mono/io-layer/io-layer.h>
27 #include <mono/utils/mono-logger.h>
28 #include <mono/utils/mono-path.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32
33 #define INVALID_ADDRESS 0xffffffff
34
35 /*
36  * Keeps track of the various assemblies loaded
37  */
38 static GHashTable *loaded_images_hash;
39 static GHashTable *loaded_images_guid_hash;
40 static GHashTable *loaded_images_refonly_hash;
41 static GHashTable *loaded_images_refonly_guid_hash;
42
43 static gboolean debug_assembly_unload = FALSE;
44
45 #define mono_images_lock() EnterCriticalSection (&images_mutex)
46 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
47 static CRITICAL_SECTION images_mutex;
48
49 guint32
50 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
51 {
52         const int top = iinfo->cli_section_count;
53         MonoSectionTable *tables = iinfo->cli_section_tables;
54         int i;
55         
56         for (i = 0; i < top; i++){
57                 if ((addr >= tables->st_virtual_address) &&
58                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
59                         return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
60                 }
61                 tables++;
62         }
63         return INVALID_ADDRESS;
64 }
65
66 char *
67 mono_image_rva_map (MonoImage *image, guint32 addr)
68 {
69         MonoCLIImageInfo *iinfo = image->image_info;
70         const int top = iinfo->cli_section_count;
71         MonoSectionTable *tables = iinfo->cli_section_tables;
72         int i;
73         
74         for (i = 0; i < top; i++){
75                 if ((addr >= tables->st_virtual_address) &&
76                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
77                         if (!iinfo->cli_sections [i]) {
78                                 if (!mono_image_ensure_section_idx (image, i))
79                                         return NULL;
80                         }
81                         return (char*)iinfo->cli_sections [i] +
82                                 (addr - tables->st_virtual_address);
83                 }
84                 tables++;
85         }
86         return NULL;
87 }
88
89 /**
90  * mono_images_init:
91  *
92  *  Initialize the global variables used by this module.
93  */
94 void
95 mono_images_init (void)
96 {
97         InitializeCriticalSection (&images_mutex);
98
99         loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
100         loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
101         loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
102         loaded_images_refonly_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
103
104         debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
105 }
106
107 /**
108  * mono_images_cleanup:
109  *
110  *  Free all resources used by this module.
111  */
112 void
113 mono_images_cleanup (void)
114 {
115         DeleteCriticalSection (&images_mutex);
116
117         g_hash_table_destroy (loaded_images_hash);
118         g_hash_table_destroy (loaded_images_guid_hash);
119         g_hash_table_destroy (loaded_images_refonly_hash);
120         g_hash_table_destroy (loaded_images_refonly_guid_hash);
121 }
122
123 /**
124  * mono_image_ensure_section_idx:
125  * @image: The image we are operating on
126  * @section: section number that we will load/map into memory
127  *
128  * This routine makes sure that we have an in-memory copy of
129  * an image section (.text, .rsrc, .data).
130  *
131  * Returns: TRUE on success
132  */
133 int
134 mono_image_ensure_section_idx (MonoImage *image, int section)
135 {
136         MonoCLIImageInfo *iinfo = image->image_info;
137         MonoSectionTable *sect;
138         gboolean writable;
139         
140         g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
141
142         if (iinfo->cli_sections [section] != NULL)
143                 return TRUE;
144
145         sect = &iinfo->cli_section_tables [section];
146         
147         writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
148
149         if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
150                 return FALSE;
151         /* FIXME: we ignore the writable flag since we don't patch the binary */
152         iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
153         return TRUE;
154 }
155
156 /**
157  * mono_image_ensure_section:
158  * @image: The image we are operating on
159  * @section: section name that we will load/map into memory
160  *
161  * This routine makes sure that we have an in-memory copy of
162  * an image section (.text, .rsrc, .data).
163  *
164  * Returns: TRUE on success
165  */
166 int
167 mono_image_ensure_section (MonoImage *image, const char *section)
168 {
169         MonoCLIImageInfo *ii = image->image_info;
170         int i;
171         
172         for (i = 0; i < ii->cli_section_count; i++){
173                 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
174                         continue;
175                 
176                 return mono_image_ensure_section_idx (image, i);
177         }
178         return FALSE;
179 }
180
181 static int
182 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
183 {
184         const int top = iinfo->cli_header.coff.coff_sections;
185         int i;
186
187         iinfo->cli_section_count = top;
188         iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
189         iinfo->cli_sections = g_new0 (void *, top);
190         
191         for (i = 0; i < top; i++){
192                 MonoSectionTable *t = &iinfo->cli_section_tables [i];
193
194                 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
195                         return FALSE;
196                 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
197                 offset += sizeof (MonoSectionTable);
198
199 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
200                 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
201                 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
202                 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
203                 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
204                 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
205                 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
206                 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
207                 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
208                 t->st_flags = GUINT32_FROM_LE (t->st_flags);
209 #endif
210                 /* consistency checks here */
211         }
212
213         return TRUE;
214 }
215
216 static gboolean
217 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
218 {
219         guint32 offset;
220         
221         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
222         if (offset == INVALID_ADDRESS)
223                 return FALSE;
224
225         if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
226                 return FALSE;
227         memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
228
229 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
230 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
231 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
232 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
233         SWAP32 (iinfo->cli_cli_header.ch_size);
234         SWAP32 (iinfo->cli_cli_header.ch_flags);
235         SWAP32 (iinfo->cli_cli_header.ch_entry_point);
236         SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
237         SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
238         SWAPPDE (iinfo->cli_cli_header.ch_metadata);
239         SWAPPDE (iinfo->cli_cli_header.ch_resources);
240         SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
241         SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
242         SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
243         SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
244         SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
245         SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
246         SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
247         SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
248         SWAPPDE (iinfo->cli_cli_header.ch_module_image);
249         SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
250         SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
251         SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
252         SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
253 #undef SWAP32
254 #undef SWAP16
255 #undef SWAPPDE
256 #endif
257         /* Catch new uses of the fields that are supposed to be zero */
258
259         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
260             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
261             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
262             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
263             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
264             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
265             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
266             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
267             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
268
269                 /*
270                  * No need to scare people who are testing this, I am just
271                  * labelling this as a LAMESPEC
272                  */
273                 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
274
275         }
276             
277         return TRUE;
278 }
279
280 static gboolean
281 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
282 {
283         guint32 offset, size;
284         guint16 streams;
285         int i;
286         guint32 pad;
287         char *ptr;
288         
289         offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
290         if (offset == INVALID_ADDRESS)
291                 return FALSE;
292
293         size = iinfo->cli_cli_header.ch_metadata.size;
294
295         if (offset + size > image->raw_data_len)
296                 return FALSE;
297         image->raw_metadata = image->raw_data + offset;
298
299         ptr = image->raw_metadata;
300
301         if (strncmp (ptr, "BSJB", 4) == 0){
302                 guint32 version_string_len;
303
304                 ptr += 4;
305                 image->md_version_major = read16 (ptr);
306                 ptr += 4;
307                 image->md_version_minor = read16 (ptr);
308                 ptr += 4;
309
310                 version_string_len = read32 (ptr);
311                 ptr += 4;
312                 image->version = g_strndup (ptr, version_string_len);
313                 ptr += version_string_len;
314                 pad = ptr - image->raw_metadata;
315                 if (pad % 4)
316                         ptr += 4 - (pad % 4);
317         } else
318                 return FALSE;
319
320         /* skip over flags */
321         ptr += 2;
322         
323         streams = read16 (ptr);
324         ptr += 2;
325
326         for (i = 0; i < streams; i++){
327                 if (strncmp (ptr + 8, "#~", 3) == 0){
328                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
329                         image->heap_tables.size = read32 (ptr + 4);
330                         ptr += 8 + 3;
331                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
332                         image->heap_strings.data = image->raw_metadata + read32 (ptr);
333                         image->heap_strings.size = read32 (ptr + 4);
334                         ptr += 8 + 9;
335                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
336                         image->heap_us.data = image->raw_metadata + read32 (ptr);
337                         image->heap_us.size = read32 (ptr + 4);
338                         ptr += 8 + 4;
339                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
340                         image->heap_blob.data = image->raw_metadata + read32 (ptr);
341                         image->heap_blob.size = read32 (ptr + 4);
342                         ptr += 8 + 6;
343                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
344                         image->heap_guid.data = image->raw_metadata + read32 (ptr);
345                         image->heap_guid.size = read32 (ptr + 4);
346                         ptr += 8 + 6;
347                 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
348                         g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
349                         return FALSE;
350                 } else {
351                         g_message ("Unknown heap type: %s\n", ptr + 8);
352                         ptr += 8 + strlen (ptr + 8) + 1;
353                 }
354                 pad = ptr - image->raw_metadata;
355                 if (pad % 4)
356                         ptr += 4 - (pad % 4);
357         }
358
359         g_assert (image->heap_guid.data);
360         g_assert (image->heap_guid.size >= 16);
361
362         image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
363
364         return TRUE;
365 }
366
367 /*
368  * Load representation of logical metadata tables, from the "#~" stream
369  */
370 static gboolean
371 load_tables (MonoImage *image)
372 {
373         const char *heap_tables = image->heap_tables.data;
374         const guint32 *rows;
375         guint64 valid_mask, sorted_mask;
376         int valid = 0, table;
377         int heap_sizes;
378         
379         heap_sizes = heap_tables [6];
380         image->idx_string_wide = ((heap_sizes & 0x01) == 1);
381         image->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
382         image->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
383         
384         valid_mask = read64 (heap_tables + 8);
385         sorted_mask = read64 (heap_tables + 16);
386         rows = (const guint32 *) (heap_tables + 24);
387         
388         for (table = 0; table < 64; table++){
389                 if ((valid_mask & ((guint64) 1 << table)) == 0){
390                         if (table > MONO_TABLE_LAST)
391                                 continue;
392                         image->tables [table].rows = 0;
393                         continue;
394                 }
395                 if (table > MONO_TABLE_LAST) {
396                         g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
397                 } else {
398                         image->tables [table].rows = read32 (rows);
399                 }
400                 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
401                         g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
402                 }*/
403                 rows++;
404                 valid++;
405         }
406
407         image->tables_base = (heap_tables + 24) + (4 * valid);
408
409         /* They must be the same */
410         g_assert ((const void *) image->tables_base == (const void *) rows);
411
412         mono_metadata_compute_table_bases (image);
413         return TRUE;
414 }
415
416 static gboolean
417 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
418 {
419         if (!load_metadata_ptrs (image, iinfo))
420                 return FALSE;
421
422         return load_tables (image);
423 }
424
425 static void
426 load_modules (MonoImage *image, MonoImageOpenStatus *status)
427 {
428         MonoTableInfo *t;
429         MonoTableInfo *file_table;
430         int i;
431         char *base_dir;
432         gboolean refonly = image->ref_only;
433         GList *list_iter, *valid_modules = NULL;
434
435         if (image->modules)
436                 return;
437
438         file_table = &image->tables [MONO_TABLE_FILE];
439         for (i = 0; i < file_table->rows; i++) {
440                 guint32 cols [MONO_FILE_SIZE];
441                 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
442                 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
443                         continue;
444                 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
445         }
446
447         t = &image->tables [MONO_TABLE_MODULEREF];
448         image->modules = g_new0 (MonoImage *, t->rows);
449         image->module_count = t->rows;
450         base_dir = g_path_get_dirname (image->name);
451         for (i = 0; i < t->rows; i++){
452                 char *module_ref;
453                 const char *name;
454                 guint32 cols [MONO_MODULEREF_SIZE];
455                 int valid = 0;
456
457                 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
458                 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
459                 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
460                         /* be safe with string dups, but we could just compare string indexes  */
461                         if (strcmp (list_iter->data, name) == 0) {
462                                 valid = TRUE;
463                                 break;
464                         }
465                 }
466                 if (!valid)
467                         continue;
468                 module_ref = g_build_filename (base_dir, name, NULL);
469                 image->modules [i] = mono_image_open_full (module_ref, status, refonly);
470                 if (image->modules [i]) {
471                         mono_image_addref (image->modules [i]);
472                         /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
473                 }
474                 /* 
475                  * FIXME: We should probably do lazy-loading of modules.
476                  */
477                 if (status)
478                         *status = MONO_IMAGE_OK;
479                 g_free (module_ref);
480         }
481
482         g_free (base_dir);
483         g_list_free (valid_modules);
484 }
485
486 static void
487 register_guid (gpointer key, gpointer value, gpointer user_data)
488 {
489         MonoImage *image = (MonoImage*)value;
490
491         if (!g_hash_table_lookup (loaded_images_guid_hash, image))
492                 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
493 }
494
495 static void
496 build_guid_table (gboolean refonly)
497 {
498         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
499         g_hash_table_foreach (loaded_images, register_guid, NULL);
500 }
501
502 void
503 mono_image_init (MonoImage *image)
504 {
505         image->mempool = mono_mempool_new ();
506         image->method_cache = g_hash_table_new (NULL, NULL);
507         image->class_cache = g_hash_table_new (NULL, NULL);
508         image->field_cache = g_hash_table_new (NULL, NULL);
509
510         image->delegate_begin_invoke_cache = 
511                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
512                                   (GCompareFunc)mono_metadata_signature_equal);
513         image->delegate_end_invoke_cache = 
514                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
515                                   (GCompareFunc)mono_metadata_signature_equal);
516         image->delegate_invoke_cache = 
517                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
518                                   (GCompareFunc)mono_metadata_signature_equal);
519         image->runtime_invoke_cache  = 
520                 g_hash_table_new ((GHashFunc)mono_signature_hash, 
521                                   (GCompareFunc)mono_metadata_signature_equal);
522         
523         image->managed_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
524         image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
525         image->remoting_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
526         image->cominterop_invoke_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
527         image->cominterop_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
528         image->synchronized_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
529         image->unbox_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
530
531         image->ldfld_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
532         image->ldflda_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
533         image->ldfld_remote_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
534         image->stfld_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
535         image->stfld_remote_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
536         image->isinst_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
537         image->castclass_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
538         image->proxy_isinst_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
539
540         image->typespec_cache = g_hash_table_new (NULL, NULL);
541         image->memberref_signatures = g_hash_table_new (NULL, NULL);
542         image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
543         image->method_signatures = g_hash_table_new (NULL, NULL);
544 }
545
546 static MonoImage *
547 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
548                     gboolean care_about_cli)
549 {
550         MonoCLIImageInfo *iinfo;
551         MonoDotNetHeader *header;
552         MonoMSDOSHeader msdos;
553         guint32 offset = 0;
554
555         mono_image_init (image);
556
557         iinfo = image->image_info;
558         header = &iinfo->cli_header;
559                 
560         if (status)
561                 *status = MONO_IMAGE_IMAGE_INVALID;
562
563         if (offset + sizeof (msdos) > image->raw_data_len)
564                 goto invalid_image;
565         memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
566         
567         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
568                 goto invalid_image;
569         
570         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
571
572         offset = msdos.pe_offset;
573
574         if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
575                 goto invalid_image;
576         memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
577         offset += sizeof (MonoDotNetHeader);
578
579 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
580 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
581 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
582 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
583         SWAP32 (header->coff.coff_time);
584         SWAP32 (header->coff.coff_symptr);
585         SWAP32 (header->coff.coff_symcount);
586         SWAP16 (header->coff.coff_machine);
587         SWAP16 (header->coff.coff_sections);
588         SWAP16 (header->coff.coff_opt_header_size);
589         SWAP16 (header->coff.coff_attributes);
590         /* MonoPEHeader */
591         SWAP32 (header->pe.pe_code_size);
592         SWAP32 (header->pe.pe_data_size);
593         SWAP32 (header->pe.pe_uninit_data_size);
594         SWAP32 (header->pe.pe_rva_entry_point);
595         SWAP32 (header->pe.pe_rva_code_base);
596         SWAP32 (header->pe.pe_rva_data_base);
597         SWAP16 (header->pe.pe_magic);
598
599         /* MonoPEHeaderNT: not used yet */
600         SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
601         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
602         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
603         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
604         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
605         SWAP16  (header->nt.pe_user_major);
606         SWAP16  (header->nt.pe_user_minor);
607         SWAP16  (header->nt.pe_subsys_major);
608         SWAP16  (header->nt.pe_subsys_minor);
609         SWAP32  (header->nt.pe_reserved_1);
610         SWAP32  (header->nt.pe_image_size);
611         SWAP32  (header->nt.pe_header_size);
612         SWAP32  (header->nt.pe_checksum);
613         SWAP16  (header->nt.pe_subsys_required);
614         SWAP16  (header->nt.pe_dll_flags);
615         SWAP32  (header->nt.pe_stack_reserve);
616         SWAP32  (header->nt.pe_stack_commit);
617         SWAP32  (header->nt.pe_heap_reserve);
618         SWAP32  (header->nt.pe_heap_commit);
619         SWAP32  (header->nt.pe_loader_flags);
620         SWAP32  (header->nt.pe_data_dir_count);
621
622         /* MonoDotNetHeader: mostly unused */
623         SWAPPDE (header->datadir.pe_export_table);
624         SWAPPDE (header->datadir.pe_import_table);
625         SWAPPDE (header->datadir.pe_resource_table);
626         SWAPPDE (header->datadir.pe_exception_table);
627         SWAPPDE (header->datadir.pe_certificate_table);
628         SWAPPDE (header->datadir.pe_reloc_table);
629         SWAPPDE (header->datadir.pe_debug);
630         SWAPPDE (header->datadir.pe_copyright);
631         SWAPPDE (header->datadir.pe_global_ptr);
632         SWAPPDE (header->datadir.pe_tls_table);
633         SWAPPDE (header->datadir.pe_load_config_table);
634         SWAPPDE (header->datadir.pe_bound_import);
635         SWAPPDE (header->datadir.pe_iat);
636         SWAPPDE (header->datadir.pe_delay_import_desc);
637         SWAPPDE (header->datadir.pe_cli_header);
638         SWAPPDE (header->datadir.pe_reserved);
639
640 #undef SWAP32
641 #undef SWAP16
642 #undef SWAPPDE
643 #endif
644
645         if (header->coff.coff_machine != 0x14c)
646                 goto invalid_image;
647
648         if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
649                 goto invalid_image;
650
651         if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
652                 goto invalid_image;
653
654 #if 0
655         /*
656          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
657          * which produces binaries with 7.0.  From Sergey:
658          *
659          * The reason is that MSVC7 uses traditional compile/link
660          * sequence for CIL executables, and VS.NET (and Framework
661          * SDK) includes linker version 7, that puts 7.0 in this
662          * field.  That's why it's currently not possible to load VC
663          * binaries with Mono.  This field is pretty much meaningless
664          * anyway (what linker?).
665          */
666         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
667                 goto invalid_image;
668 #endif
669
670         /*
671          * FIXME: byte swap all addresses here for header.
672          */
673         
674         if (!load_section_tables (image, iinfo, offset))
675                 goto invalid_image;
676         
677         if (care_about_cli == FALSE) {
678                 goto done;
679         }
680         
681         /* Load the CLI header */
682         if (!load_cli_header (image, iinfo))
683                 goto invalid_image;
684
685         if (!load_metadata (image, iinfo))
686                 goto invalid_image;
687
688         /* modules don't have an assembly table row */
689         if (image->tables [MONO_TABLE_ASSEMBLY].rows)
690                 image->assembly_name = mono_metadata_string_heap (image, 
691                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
692                                         0, MONO_ASSEMBLY_NAME));
693
694         image->module_name = mono_metadata_string_heap (image, 
695                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
696                                         0, MONO_MODULE_NAME));
697
698         load_modules (image, status);
699
700 done:
701         if (status)
702                 *status = MONO_IMAGE_OK;
703
704         return image;
705
706 invalid_image:
707         mono_image_close (image);
708                 return NULL;
709 }
710
711 static MonoImage *
712 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
713                     gboolean care_about_cli, gboolean refonly)
714 {
715         MonoCLIImageInfo *iinfo;
716         MonoImage *image;
717         FILE *filed;
718         struct stat stat_buf;
719
720         if ((filed = fopen (fname, "rb")) == NULL){
721                 if (status)
722                         *status = MONO_IMAGE_ERROR_ERRNO;
723                 return NULL;
724         }
725
726         if (fstat (fileno (filed), &stat_buf)) {
727                 fclose (filed);
728                 if (status)
729                         *status = MONO_IMAGE_ERROR_ERRNO;
730                 return NULL;
731         }
732         image = g_new0 (MonoImage, 1);
733         image->file_descr = filed;
734         image->raw_data_len = stat_buf.st_size;
735         image->raw_data = mono_raw_buffer_load (fileno (filed), FALSE, 0, stat_buf.st_size);
736         iinfo = g_new0 (MonoCLIImageInfo, 1);
737         image->image_info = iinfo;
738         image->name = mono_path_resolve_symlinks (fname);
739         image->ref_only = refonly;
740         image->ref_count = 1;
741
742         return do_mono_image_load (image, status, care_about_cli);
743 }
744
745 MonoImage *
746 mono_image_loaded_full (const char *name, gboolean refonly)
747 {
748         MonoImage *res;
749         GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
750         
751         mono_images_lock ();
752         res = g_hash_table_lookup (loaded_images, name);
753         mono_images_unlock ();
754         return res;
755 }
756
757 MonoImage *
758 mono_image_loaded (const char *name)
759 {
760         return mono_image_loaded_full (name, FALSE);
761 }
762
763 MonoImage *
764 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
765 {
766         MonoImage *res;
767         GHashTable *loaded_images = refonly ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
768
769         mono_images_lock ();
770         res = g_hash_table_lookup (loaded_images, guid);
771         mono_images_unlock ();
772         return res;
773 }
774
775 MonoImage *
776 mono_image_loaded_by_guid (const char *guid)
777 {
778         return mono_image_loaded_by_guid_full (guid, FALSE);
779 }
780
781 static MonoImage *
782 register_image (MonoImage *image)
783 {
784         MonoImage *image2;
785         GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
786
787         mono_images_lock ();
788         image2 = g_hash_table_lookup (loaded_images, image->name);
789
790         if (image2) {
791                 /* Somebody else beat us to it */
792                 mono_image_addref (image2);
793                 mono_images_unlock ();
794                 mono_image_close (image);
795                 return image2;
796         }
797         g_hash_table_insert (loaded_images, image->name, image);
798         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
799                 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);      
800         g_hash_table_insert (image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash, image->guid, image);
801         mono_images_unlock ();
802
803         return image;
804 }
805
806 MonoImage *
807 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
808 {
809         MonoCLIImageInfo *iinfo;
810         MonoImage *image;
811         char *datac;
812
813         if (!data || !data_len) {
814                 if (status)
815                         *status = MONO_IMAGE_IMAGE_INVALID;
816                 return NULL;
817         }
818         datac = data;
819         if (need_copy) {
820                 datac = g_try_malloc (data_len);
821                 if (!datac) {
822                         if (status)
823                                 *status = MONO_IMAGE_ERROR_ERRNO;
824                         return NULL;
825                 }
826                 memcpy (datac, data, data_len);
827         }
828
829         image = g_new0 (MonoImage, 1);
830         image->raw_data = datac;
831         image->raw_data_len = data_len;
832         image->raw_data_allocated = need_copy;
833         image->name = g_strdup_printf ("data-%p", datac);
834         iinfo = g_new0 (MonoCLIImageInfo, 1);
835         image->image_info = iinfo;
836         image->ref_only = refonly;
837
838         image = do_mono_image_load (image, status, TRUE);
839         if (image == NULL)
840                 return NULL;
841
842         return register_image (image);
843 }
844
845 MonoImage *
846 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
847 {
848         return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
849 }
850
851 MonoImage *
852 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
853 {
854         MonoImage *image;
855         GHashTable *loaded_images;
856         char *absfname;
857         
858         g_return_val_if_fail (fname != NULL, NULL);
859         
860         absfname = mono_path_canonicalize (fname);
861
862         /*
863          * The easiest solution would be to do all the loading inside the mutex,
864          * but that would lead to scalability problems. So we let the loading
865          * happen outside the mutex, and if multiple threads happen to load
866          * the same image, we discard all but the first copy.
867          */
868         mono_images_lock ();
869         loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
870         image = g_hash_table_lookup (loaded_images, absfname);
871         g_free (absfname);
872         
873         if (image){
874                 mono_image_addref (image);
875                 mono_images_unlock ();
876                 return image;
877         }
878         mono_images_unlock ();
879
880         image = do_mono_image_open (fname, status, TRUE, refonly);
881         if (image == NULL)
882                 return NULL;
883
884         return register_image (image);
885 }
886
887 /**
888  * mono_image_open:
889  * @fname: filename that points to the module we want to open
890  * @status: An error condition is returned in this field
891  *
892  * Returns: An open image of type %MonoImage or NULL on error. 
893  * The caller holds a temporary reference to the returned image which should be cleared 
894  * when no longer needed by calling mono_image_close ().
895  * if NULL, then check the value of @status for details on the error
896  */
897 MonoImage *
898 mono_image_open (const char *fname, MonoImageOpenStatus *status)
899 {
900         return mono_image_open_full (fname, status, FALSE);
901 }
902
903 /**
904  * mono_pe_file_open:
905  * @fname: filename that points to the module we want to open
906  * @status: An error condition is returned in this field
907  *
908  * Returns: An open image of type %MonoImage or NULL on error.  if
909  * NULL, then check the value of @status for details on the error.
910  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
911  * It's just a PE file loader, used for FileVersionInfo.  It also does
912  * not use the image cache.
913  */
914 MonoImage *
915 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
916 {
917         g_return_val_if_fail (fname != NULL, NULL);
918         
919         return(do_mono_image_open (fname, status, FALSE, FALSE));
920 }
921
922 static void
923 free_hash_table (gpointer key, gpointer val, gpointer user_data)
924 {
925         g_hash_table_destroy ((GHashTable*)val);
926 }
927
928 /*
929 static void
930 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
931 {
932         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
933 }
934 */
935
936 static void
937 free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
938 {
939         g_free (key);
940 }
941
942 static void
943 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
944 {
945         g_free (val);
946 }
947
948 static void
949 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
950 {
951         g_slist_free ((GSList*)val);
952 }
953
954 /**
955  * mono_image_addref:
956  * @image: The image file we wish to add a reference to
957  *
958  *  Increases the reference count of an image.
959  */
960 void
961 mono_image_addref (MonoImage *image)
962 {
963         InterlockedIncrement (&image->ref_count);
964 }       
965
966 void
967 mono_dynamic_stream_reset (MonoDynamicStream* stream)
968 {
969         stream->alloc_size = stream->index = stream->offset = 0;
970         g_free (stream->data);
971         stream->data = NULL;
972         if (stream->hash) {
973                 g_hash_table_destroy (stream->hash);
974                 stream->hash = NULL;
975         }
976 }
977
978 /**
979  * mono_image_close:
980  * @image: The image file we wish to close
981  *
982  * Closes an image file, deallocates all memory consumed and
983  * unmaps all possible sections of the file
984  */
985 void
986 mono_image_close (MonoImage *image)
987 {
988         MonoImage *image2;
989         GHashTable *loaded_images, *loaded_images_guid;
990         int i;
991
992         g_return_if_fail (image != NULL);
993
994         if (InterlockedDecrement (&image->ref_count) > 0)
995                 return;
996
997         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
998         
999         mono_images_lock ();
1000         loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1001         loaded_images_guid = image->ref_only ? loaded_images_refonly_guid_hash : loaded_images_guid_hash;
1002         image2 = g_hash_table_lookup (loaded_images, image->name);
1003         if (image == image2) {
1004                 /* This is not true if we are called from mono_image_open () */
1005                 g_hash_table_remove (loaded_images, image->name);
1006                 g_hash_table_remove (loaded_images_guid, image->guid);
1007         }
1008         if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1009                 g_hash_table_remove (loaded_images, (char *) image->assembly_name);     
1010
1011         /* Multiple images might have the same guid */
1012         build_guid_table (image->ref_only);
1013
1014         mono_images_unlock ();
1015
1016         if (image->file_descr) {
1017                 fclose (image->file_descr);
1018                 image->file_descr = NULL;
1019                 if (image->raw_data != NULL)
1020                         mono_raw_buffer_free (image->raw_data);
1021         }
1022         
1023         if (image->raw_data_allocated) {
1024                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1025                 MonoCLIImageInfo *ii = image->image_info;
1026
1027                 if ((image->raw_metadata > image->raw_data) &&
1028                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1029                         image->raw_metadata = NULL;
1030
1031                 for (i = 0; i < ii->cli_section_count; i++)
1032                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1033                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1034                                 ii->cli_sections [i] = NULL;
1035
1036                 g_free (image->raw_data);
1037         }
1038
1039         if (debug_assembly_unload) {
1040                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1041         } else {
1042                 g_free (image->name);
1043                 g_free (image->guid);
1044                 g_free (image->version);
1045                 g_free (image->files);
1046         }
1047
1048         g_hash_table_destroy (image->method_cache);
1049         g_hash_table_destroy (image->class_cache);
1050         g_hash_table_destroy (image->field_cache);
1051         if (image->array_cache) {
1052                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1053                 g_hash_table_destroy (image->array_cache);
1054         }
1055         if (image->ptr_cache)
1056                 g_hash_table_destroy (image->ptr_cache);
1057         if (image->name_cache) {
1058                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1059                 g_hash_table_destroy (image->name_cache);
1060         }
1061         g_hash_table_destroy (image->native_wrapper_cache);
1062         g_hash_table_destroy (image->managed_wrapper_cache);
1063         g_hash_table_destroy (image->delegate_begin_invoke_cache);
1064         g_hash_table_destroy (image->delegate_end_invoke_cache);
1065         g_hash_table_destroy (image->delegate_invoke_cache);
1066         g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1067         g_hash_table_destroy (image->remoting_invoke_cache);
1068         g_hash_table_destroy (image->runtime_invoke_cache);
1069         g_hash_table_destroy (image->synchronized_cache);
1070         g_hash_table_destroy (image->unbox_wrapper_cache);
1071         g_hash_table_destroy (image->cominterop_invoke_cache);
1072         g_hash_table_destroy (image->cominterop_wrapper_cache);
1073         g_hash_table_destroy (image->typespec_cache);
1074         g_hash_table_destroy (image->ldfld_wrapper_cache);
1075         g_hash_table_destroy (image->ldflda_wrapper_cache);
1076         g_hash_table_destroy (image->ldfld_remote_wrapper_cache);
1077         g_hash_table_destroy (image->stfld_wrapper_cache);
1078         g_hash_table_destroy (image->stfld_remote_wrapper_cache);
1079         g_hash_table_destroy (image->isinst_cache);
1080         g_hash_table_destroy (image->castclass_cache);
1081         g_hash_table_destroy (image->proxy_isinst_cache);
1082
1083         /* The ownership of signatures is not well defined */
1084         //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1085         g_hash_table_destroy (image->memberref_signatures);
1086         //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1087         g_hash_table_destroy (image->helper_signatures);
1088         g_hash_table_destroy (image->method_signatures);
1089
1090         if (image->interface_bitset) {
1091                 mono_unload_interface_ids (image->interface_bitset);
1092                 mono_bitset_free (image->interface_bitset);
1093         }
1094         if (image->image_info){
1095                 MonoCLIImageInfo *ii = image->image_info;
1096
1097                 if (ii->cli_section_tables)
1098                         g_free (ii->cli_section_tables);
1099                 if (ii->cli_sections)
1100                         g_free (ii->cli_sections);
1101                 g_free (image->image_info);
1102         }
1103
1104         for (i = 0; i < image->module_count; ++i) {
1105                 if (image->modules [i])
1106                         mono_image_close (image->modules [i]);
1107         }
1108         if (image->modules)
1109                 g_free (image->modules);
1110         if (image->references)
1111                 g_free (image->references);
1112         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1113         if (!image->dynamic) {
1114                 if (debug_assembly_unload)
1115                         mono_mempool_invalidate (image->mempool);
1116                 else {
1117                         mono_mempool_destroy (image->mempool);
1118                         g_free (image);
1119                 }
1120         } else {
1121                 /* Dynamic images are GC_MALLOCed */
1122                 struct _MonoDynamicImage *di = (struct _MonoDynamicImage*)image;
1123                 int i;
1124                 g_free ((char*)image->module_name);
1125                 if (di->typespec)
1126                         g_hash_table_destroy (di->typespec);
1127                 if (di->typeref)
1128                         g_hash_table_destroy (di->typeref);
1129                 if (di->handleref)
1130                         g_hash_table_destroy (di->handleref);
1131                 if (di->tokens)
1132                         mono_g_hash_table_destroy (di->tokens);
1133                 if (di->blob_cache) {
1134                         g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
1135                         g_hash_table_destroy (di->blob_cache);
1136                 }
1137                 g_list_free (di->array_methods);
1138                 if (di->gen_params)
1139                         g_ptr_array_free (di->gen_params, TRUE);
1140                 if (di->token_fixups)
1141                         mono_g_hash_table_destroy (di->token_fixups);
1142                 if (di->method_to_table_idx)
1143                         g_hash_table_destroy (di->method_to_table_idx);
1144                 if (di->field_to_table_idx)
1145                         g_hash_table_destroy (di->field_to_table_idx);
1146                 if (di->method_aux_hash)
1147                         g_hash_table_destroy (di->method_aux_hash);
1148                 g_free (di->strong_name);
1149                 g_free (di->win32_res);
1150                 /*g_print ("string heap destroy for image %p\n", di);*/
1151                 mono_dynamic_stream_reset (&di->sheap);
1152                 mono_dynamic_stream_reset (&di->code);
1153                 mono_dynamic_stream_reset (&di->resources);
1154                 mono_dynamic_stream_reset (&di->us);
1155                 mono_dynamic_stream_reset (&di->blob);
1156                 mono_dynamic_stream_reset (&di->tstream);
1157                 mono_dynamic_stream_reset (&di->guid);
1158                 for (i = 0; i < MONO_TABLE_NUM; ++i) {
1159                         g_free (di->tables [i].values);
1160                 }
1161                 mono_mempool_destroy (image->mempool);
1162         }
1163 }
1164
1165 /** 
1166  * mono_image_strerror:
1167  * @status: an code indicating the result from a recent operation
1168  *
1169  * Returns: a string describing the error
1170  */
1171 const char *
1172 mono_image_strerror (MonoImageOpenStatus status)
1173 {
1174         switch (status){
1175         case MONO_IMAGE_OK:
1176                 return "success";
1177         case MONO_IMAGE_ERROR_ERRNO:
1178                 return strerror (errno);
1179         case MONO_IMAGE_IMAGE_INVALID:
1180                 return "File does not contain a valid CIL image";
1181         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1182                 return "An assembly was referenced, but could not be found";
1183         }
1184         return "Internal error";
1185 }
1186
1187 static gpointer
1188 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1189                                guint32 lang_id, gunichar2 *name,
1190                                MonoPEResourceDirEntry *entry,
1191                                MonoPEResourceDir *root, guint32 level)
1192 {
1193         gboolean is_string=entry->name_is_string;
1194
1195         /* Level 0 holds a directory entry for each type of resource
1196          * (identified by ID or name).
1197          *
1198          * Level 1 holds a directory entry for each named resource
1199          * item, and each "anonymous" item of a particular type of
1200          * resource.
1201          *
1202          * Level 2 holds a directory entry for each language pointing to
1203          * the actual data.
1204          */
1205
1206         if(level==0) {
1207                 if((is_string==FALSE && entry->name_offset!=res_id) ||
1208                    (is_string==TRUE)) {
1209                         return(NULL);
1210                 }
1211         } else if (level==1) {
1212 #if 0
1213                 if(name!=NULL &&
1214                    is_string==TRUE && name!=lookup (entry->name_offset)) {
1215                         return(NULL);
1216                 }
1217 #endif
1218         } else if (level==2) {
1219                 if ((is_string == FALSE &&
1220                     entry->name_offset != lang_id &&
1221                     lang_id != 0) ||
1222                    (is_string == TRUE)) {
1223                         return(NULL);
1224                 }
1225         } else {
1226                 g_assert_not_reached ();
1227         }
1228
1229         if(entry->is_dir==TRUE) {
1230                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1231                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1232                 guint32 entries, i;
1233                 
1234                 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1235
1236                 for(i=0; i<entries; i++) {
1237                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1238                         gpointer ret;
1239                         
1240                         ret=mono_image_walk_resource_tree (info, res_id,
1241                                                            lang_id, name,
1242                                                            sub_entry, root,
1243                                                            level+1);
1244                         if(ret!=NULL) {
1245                                 return(ret);
1246                         }
1247                 }
1248
1249                 return(NULL);
1250         } else {
1251                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1252                 
1253                 return(data_entry);
1254         }
1255 }
1256
1257 /**
1258  * mono_image_lookup_resource:
1259  * @image: the image to look up the resource in
1260  * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1261  * @lang_id: The language id.
1262  * @name: the resource name to lookup.
1263  *
1264  * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1265  * of the given resource.
1266  */
1267 gpointer
1268 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1269 {
1270         MonoCLIImageInfo *info;
1271         MonoDotNetHeader *header;
1272         MonoPEDatadir *datadir;
1273         MonoPEDirEntry *rsrc;
1274         MonoPEResourceDir *resource_dir;
1275         MonoPEResourceDirEntry *res_entries;
1276         guint32 entries, i;
1277
1278         if(image==NULL) {
1279                 return(NULL);
1280         }
1281
1282         info=image->image_info;
1283         if(info==NULL) {
1284                 return(NULL);
1285         }
1286
1287         header=&info->cli_header;
1288         if(header==NULL) {
1289                 return(NULL);
1290         }
1291
1292         datadir=&header->datadir;
1293         if(datadir==NULL) {
1294                 return(NULL);
1295         }
1296
1297         rsrc=&datadir->pe_resource_table;
1298         if(rsrc==NULL) {
1299                 return(NULL);
1300         }
1301
1302         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1303         if(resource_dir==NULL) {
1304                 return(NULL);
1305         }
1306         
1307         entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1308         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1309         
1310         for(i=0; i<entries; i++) {
1311                 MonoPEResourceDirEntry *entry=&res_entries[i];
1312                 gpointer ret;
1313                 
1314                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1315                                                    name, entry, resource_dir,
1316                                                    0);
1317                 if(ret!=NULL) {
1318                         return(ret);
1319                 }
1320         }
1321
1322         return(NULL);
1323 }
1324
1325 /** 
1326  * mono_image_get_entry_point:
1327  * @image: the image where the entry point will be looked up.
1328  *
1329  * Use this routine to determine the metadata token for method that
1330  * has been flagged as the entry point.
1331  *
1332  * Returns: the token for the entry point method in the image
1333  */
1334 guint32
1335 mono_image_get_entry_point (MonoImage *image)
1336 {
1337         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1338 }
1339
1340 /**
1341  * mono_image_get_resource:
1342  * @image: the image where the resource will be looked up.
1343  * @offset: The offset to add to the resource
1344  * @size: a pointer to an int where the size of the resource will be stored
1345  *
1346  * This is a low-level routine that fetches a resource from the
1347  * metadata that starts at a given @offset.  The @size parameter is
1348  * filled with the data field as encoded in the metadata.
1349  *
1350  * Returns: the pointer to the resource whose offset is @offset.
1351  */
1352 const char*
1353 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1354 {
1355         MonoCLIImageInfo *iinfo = image->image_info;
1356         MonoCLIHeader *ch = &iinfo->cli_cli_header;
1357         const char* data;
1358
1359         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1360                 return NULL;
1361         
1362         data = mono_image_rva_map (image, ch->ch_resources.rva);
1363         if (!data)
1364                 return NULL;
1365         data += offset;
1366         if (size)
1367                 *size = read32 (data);
1368         data += 4;
1369         return data;
1370 }
1371
1372 MonoImage*
1373 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1374 {
1375         char *base_dir, *name;
1376         MonoImage *res;
1377         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
1378         const char *fname;
1379         guint32 fname_id;
1380
1381         if (fileidx < 1 || fileidx > t->rows)
1382                 return NULL;
1383
1384         if (image->files && image->files [fileidx - 1])
1385                 return image->files [fileidx - 1];
1386
1387         if (!image->files)
1388                 image->files = g_new0 (MonoImage*, t->rows);
1389
1390         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1391         fname = mono_metadata_string_heap (image, fname_id);
1392         base_dir = g_path_get_dirname (image->name);
1393         name = g_build_filename (base_dir, fname, NULL);
1394         res = mono_image_open (name, NULL);
1395         if (res) {
1396                 int i;
1397                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1398                 res->assembly = image->assembly;
1399                 for (i = 0; i < res->module_count; ++i) {
1400                         if (res->modules [i] && !res->modules [i]->assembly)
1401                                 res->modules [i]->assembly = image->assembly;
1402                 }
1403
1404                 image->files [fileidx - 1] = res;
1405         }
1406         g_free (name);
1407         g_free (base_dir);
1408         return res;
1409 }
1410
1411 const char*
1412 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1413 {
1414         MonoCLIImageInfo *iinfo = image->image_info;
1415         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1416         const char* data;
1417
1418         if (!de->size || !de->rva)
1419                 return NULL;
1420         data = mono_image_rva_map (image, de->rva);
1421         if (!data)
1422                 return NULL;
1423         if (size)
1424                 *size = de->size;
1425         return data;
1426 }
1427
1428 guint32
1429 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1430 {
1431         MonoCLIImageInfo *iinfo = image->image_info;
1432         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1433         const int top = iinfo->cli_section_count;
1434         MonoSectionTable *tables = iinfo->cli_section_tables;
1435         int i;
1436         guint32 addr = de->rva;
1437         
1438         if (size)
1439                 *size = de->size;
1440         if (!de->size || !de->rva)
1441                 return 0;
1442         for (i = 0; i < top; i++){
1443                 if ((addr >= tables->st_virtual_address) &&
1444                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1445                         return tables->st_raw_data_ptr +
1446                                 (addr - tables->st_virtual_address);
1447                 }
1448                 tables++;
1449         }
1450
1451         return 0;
1452 }
1453
1454 const char*
1455 mono_image_get_public_key (MonoImage *image, guint32 *size)
1456 {
1457         const char *pubkey;
1458         guint32 len, tok;
1459         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1460                 return NULL;
1461         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1462         if (!tok)
1463                 return NULL;
1464         pubkey = mono_metadata_blob_heap (image, tok);
1465         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1466         if (size)
1467                 *size = len;
1468         return pubkey;
1469 }
1470
1471 const char*
1472 mono_image_get_name (MonoImage *image)
1473 {
1474         return image->assembly_name;
1475 }
1476
1477 const char*
1478 mono_image_get_filename (MonoImage *image)
1479 {
1480         return image->name;
1481 }
1482
1483 const char*
1484 mono_image_get_guid (MonoImage *image)
1485 {
1486         return image->guid;
1487 }
1488
1489 const MonoTableInfo*
1490 mono_image_get_table_info (MonoImage *image, int table_id)
1491 {
1492         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1493                 return NULL;
1494         return &image->tables [table_id];
1495 }
1496
1497 int
1498 mono_image_get_table_rows (MonoImage *image, int table_id)
1499 {
1500         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1501                 return 0;
1502         return image->tables [table_id].rows;
1503 }
1504
1505 int
1506 mono_table_info_get_rows (const MonoTableInfo *table)
1507 {
1508         return table->rows;
1509 }
1510
1511 MonoAssembly* 
1512 mono_image_get_assembly (MonoImage *image)
1513 {
1514         return image->assembly;
1515 }
1516
1517 gboolean
1518 mono_image_is_dynamic (MonoImage *image)
1519 {
1520         return image->dynamic;
1521 }
1522
1523 gboolean
1524 mono_image_has_authenticode_entry (MonoImage *image)
1525 {
1526         MonoCLIImageInfo *iinfo = image->image_info;
1527         MonoDotNetHeader *header = &iinfo->cli_header;
1528         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1529         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1530         return ((de->rva != 0) && (de->size > 8));
1531 }