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