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