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