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