ab78ab8f23bae36c2c0dda564b8dabff6203bfb0
[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  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11  *
12  */
13 #include <config.h>
14 #include <stdio.h>
15 #include <glib.h>
16 #include <errno.h>
17 #include <time.h>
18 #include <string.h>
19 #include "image.h"
20 #include "cil-coff.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 "marshal.h"
28 #include "coree.h"
29 #include <mono/io-layer/io-layer.h>
30 #include <mono/utils/mono-logger-internal.h>
31 #include <mono/utils/mono-path.h>
32 #include <mono/utils/mono-mmap.h>
33 #include <mono/utils/mono-io-portability.h>
34 #include <mono/utils/atomic.h>
35 #include <mono/metadata/class-internals.h>
36 #include <mono/metadata/assembly.h>
37 #include <mono/metadata/object-internals.h>
38 #include <mono/metadata/security-core-clr.h>
39 #include <mono/metadata/verify-internals.h>
40 #include <mono/metadata/verify.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46
47 #define INVALID_ADDRESS 0xffffffff
48
49 // Amount initially reserved in each image's mempool.
50 // FIXME: This number is arbitrary, a more practical number should be found
51 #define INITIAL_IMAGE_SIZE    512
52
53 /*
54  * The "loaded images" hashes keep track of the various assemblies and netmodules loaded
55  * There are four, for all combinations of [look up by path or assembly name?]
56  * and [normal or reflection-only load?, as in Assembly.ReflectionOnlyLoad]
57  */
58 enum {
59         IMAGES_HASH_PATH = 0,
60         IMAGES_HASH_PATH_REFONLY = 1,
61         IMAGES_HASH_NAME = 2,
62         IMAGES_HASH_NAME_REFONLY = 3,
63         IMAGES_HASH_COUNT = 4
64 };
65 static GHashTable *loaded_images_hashes [4] = {NULL, NULL, NULL, NULL};
66
67 static GHashTable *get_loaded_images_hash (gboolean refonly)
68 {
69         int idx = refonly ? IMAGES_HASH_PATH_REFONLY : IMAGES_HASH_PATH;
70         return loaded_images_hashes [idx];
71 }
72
73 static GHashTable *get_loaded_images_by_name_hash (gboolean refonly)
74 {
75         int idx = refonly ? IMAGES_HASH_NAME_REFONLY : IMAGES_HASH_NAME;
76         return loaded_images_hashes [idx];
77 }
78
79 static gboolean debug_assembly_unload = FALSE;
80
81 #define mono_images_lock() if (mutex_inited) mono_mutex_lock (&images_mutex)
82 #define mono_images_unlock() if (mutex_inited) mono_mutex_unlock (&images_mutex)
83 static gboolean mutex_inited;
84 static mono_mutex_t images_mutex;
85
86 static void install_pe_loader (void);
87
88 typedef struct ImageUnloadHook ImageUnloadHook;
89 struct ImageUnloadHook {
90         MonoImageUnloadFunc func;
91         gpointer user_data;
92 };
93
94 static GSList *image_unload_hooks;
95
96 void
97 mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
98 {
99         ImageUnloadHook *hook;
100         
101         g_return_if_fail (func != NULL);
102
103         hook = g_new0 (ImageUnloadHook, 1);
104         hook->func = func;
105         hook->user_data = user_data;
106         image_unload_hooks = g_slist_prepend (image_unload_hooks, hook);
107 }
108
109 void
110 mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
111 {
112         GSList *l;
113         ImageUnloadHook *hook;
114
115         for (l = image_unload_hooks; l; l = l->next) {
116                 hook = l->data;
117
118                 if (hook->func == func && hook->user_data == user_data) {
119                         g_free (hook);
120                         image_unload_hooks = g_slist_delete_link (image_unload_hooks, l);
121                         break;
122                 }
123         }
124 }
125
126 static void
127 mono_image_invoke_unload_hook (MonoImage *image)
128 {
129         GSList *l;
130         ImageUnloadHook *hook;
131
132         for (l = image_unload_hooks; l; l = l->next) {
133                 hook = l->data;
134
135                 hook->func (image, hook->user_data);
136         }
137 }
138
139 static GSList *image_loaders;
140
141 void
142 mono_install_image_loader (const MonoImageLoader *loader)
143 {
144         image_loaders = g_slist_prepend (image_loaders, (MonoImageLoader*)loader);
145 }
146
147 /* returns offset relative to image->raw_data */
148 guint32
149 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
150 {
151         MonoCLIImageInfo *iinfo = image->image_info;
152         const int top = iinfo->cli_section_count;
153         MonoSectionTable *tables = iinfo->cli_section_tables;
154         int i;
155
156         if (image->metadata_only)
157                 return addr;
158
159         for (i = 0; i < top; i++){
160                 if ((addr >= tables->st_virtual_address) &&
161                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
162 #ifdef HOST_WIN32
163                         if (image->is_module_handle)
164                                 return addr;
165 #endif
166                         return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
167                 }
168                 tables++;
169         }
170         return INVALID_ADDRESS;
171 }
172
173 /**
174  * mono_images_rva_map:
175  * @image: a MonoImage
176  * @addr: relative virtual address (RVA)
177  *
178  * This is a low-level routine used by the runtime to map relative
179  * virtual address (RVA) into their location in memory. 
180  *
181  * Returns: the address in memory for the given RVA, or NULL if the
182  * RVA is not valid for this image. 
183  */
184 char *
185 mono_image_rva_map (MonoImage *image, guint32 addr)
186 {
187         MonoCLIImageInfo *iinfo = image->image_info;
188         const int top = iinfo->cli_section_count;
189         MonoSectionTable *tables = iinfo->cli_section_tables;
190         int i;
191
192 #ifdef HOST_WIN32
193         if (image->is_module_handle) {
194                 if (addr && addr < image->raw_data_len)
195                         return image->raw_data + addr;
196                 else
197                         return NULL;
198         }
199 #endif
200
201         for (i = 0; i < top; i++){
202                 if ((addr >= tables->st_virtual_address) &&
203                     (addr < tables->st_virtual_address + tables->st_raw_data_size)){
204                         if (!iinfo->cli_sections [i]) {
205                                 if (!mono_image_ensure_section_idx (image, i))
206                                         return NULL;
207                         }
208                         return (char*)iinfo->cli_sections [i] +
209                                 (addr - tables->st_virtual_address);
210                 }
211                 tables++;
212         }
213         return NULL;
214 }
215
216 /**
217  * mono_images_init:
218  *
219  *  Initialize the global variables used by this module.
220  */
221 void
222 mono_images_init (void)
223 {
224         mono_mutex_init_recursive (&images_mutex);
225
226         int hash_idx;
227         for(hash_idx = 0; hash_idx < IMAGES_HASH_COUNT; hash_idx++)
228                 loaded_images_hashes [hash_idx] = g_hash_table_new (g_str_hash, g_str_equal);
229
230         debug_assembly_unload = g_getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
231
232         install_pe_loader ();
233
234         mutex_inited = TRUE;
235 }
236
237 /**
238  * mono_images_cleanup:
239  *
240  *  Free all resources used by this module.
241  */
242 void
243 mono_images_cleanup (void)
244 {
245         GHashTableIter iter;
246         MonoImage *image;
247
248         mono_mutex_destroy (&images_mutex);
249
250         // If an assembly image is still loaded at shutdown, this could indicate managed code is still running.
251         // Reflection-only images being still loaded doesn't indicate anything as harmful, so we don't check for it.
252         g_hash_table_iter_init (&iter, get_loaded_images_hash (FALSE));
253         while (g_hash_table_iter_next (&iter, NULL, (void**)&image))
254                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly image '%s' still loaded at shutdown.", image->name);
255
256         int hash_idx;
257         for(hash_idx = 0; hash_idx < IMAGES_HASH_COUNT; hash_idx++)
258                 g_hash_table_destroy (loaded_images_hashes [hash_idx]);
259
260         mutex_inited = FALSE;
261 }
262
263 /**
264  * mono_image_ensure_section_idx:
265  * @image: The image we are operating on
266  * @section: section number that we will load/map into memory
267  *
268  * This routine makes sure that we have an in-memory copy of
269  * an image section (.text, .rsrc, .data).
270  *
271  * Returns: TRUE on success
272  */
273 int
274 mono_image_ensure_section_idx (MonoImage *image, int section)
275 {
276         MonoCLIImageInfo *iinfo = image->image_info;
277         MonoSectionTable *sect;
278         
279         g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
280
281         if (iinfo->cli_sections [section] != NULL)
282                 return TRUE;
283
284         sect = &iinfo->cli_section_tables [section];
285         
286         if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
287                 return FALSE;
288 #ifdef HOST_WIN32
289         if (image->is_module_handle)
290                 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
291         else
292 #endif
293         /* FIXME: we ignore the writable flag since we don't patch the binary */
294         iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
295         return TRUE;
296 }
297
298 /**
299  * mono_image_ensure_section:
300  * @image: The image we are operating on
301  * @section: section name that we will load/map into memory
302  *
303  * This routine makes sure that we have an in-memory copy of
304  * an image section (.text, .rsrc, .data).
305  *
306  * Returns: TRUE on success
307  */
308 int
309 mono_image_ensure_section (MonoImage *image, const char *section)
310 {
311         MonoCLIImageInfo *ii = image->image_info;
312         int i;
313         
314         for (i = 0; i < ii->cli_section_count; i++){
315                 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
316                         continue;
317                 
318                 return mono_image_ensure_section_idx (image, i);
319         }
320         return FALSE;
321 }
322
323 static int
324 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
325 {
326         const int top = iinfo->cli_header.coff.coff_sections;
327         int i;
328
329         iinfo->cli_section_count = top;
330         iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
331         iinfo->cli_sections = g_new0 (void *, top);
332         
333         for (i = 0; i < top; i++){
334                 MonoSectionTable *t = &iinfo->cli_section_tables [i];
335
336                 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
337                         return FALSE;
338                 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
339                 offset += sizeof (MonoSectionTable);
340
341 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
342                 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
343                 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
344                 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
345                 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
346                 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
347                 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
348                 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
349                 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
350                 t->st_flags = GUINT32_FROM_LE (t->st_flags);
351 #endif
352                 /* consistency checks here */
353         }
354
355         return TRUE;
356 }
357
358 gboolean
359 mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
360 {
361         guint32 offset;
362         
363         offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
364         if (offset == INVALID_ADDRESS)
365                 return FALSE;
366
367         if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
368                 return FALSE;
369         memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
370
371 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
372 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
373 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
374 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
375         SWAP32 (iinfo->cli_cli_header.ch_size);
376         SWAP32 (iinfo->cli_cli_header.ch_flags);
377         SWAP32 (iinfo->cli_cli_header.ch_entry_point);
378         SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
379         SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
380         SWAPPDE (iinfo->cli_cli_header.ch_metadata);
381         SWAPPDE (iinfo->cli_cli_header.ch_resources);
382         SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
383         SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
384         SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
385         SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
386         SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
387         SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
388         SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
389         SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
390         SWAPPDE (iinfo->cli_cli_header.ch_module_image);
391         SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
392         SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
393         SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
394         SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
395 #undef SWAP32
396 #undef SWAP16
397 #undef SWAPPDE
398 #endif
399         /* Catch new uses of the fields that are supposed to be zero */
400
401         if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
402             (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
403             (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
404             (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
405             (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
406             (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
407             (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
408             (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
409             (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
410
411                 /*
412                  * No need to scare people who are testing this, I am just
413                  * labelling this as a LAMESPEC
414                  */
415                 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
416
417         }
418             
419         return TRUE;
420 }
421
422 static gboolean
423 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
424 {
425         guint32 offset, size;
426         guint16 streams;
427         int i;
428         guint32 pad;
429         char *ptr;
430         
431         offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
432         if (offset == INVALID_ADDRESS)
433                 return FALSE;
434
435         size = iinfo->cli_cli_header.ch_metadata.size;
436
437         if (offset + size > image->raw_data_len)
438                 return FALSE;
439         image->raw_metadata = image->raw_data + offset;
440
441         /* 24.2.1: Metadata root starts here */
442         ptr = image->raw_metadata;
443
444         if (strncmp (ptr, "BSJB", 4) == 0){
445                 guint32 version_string_len;
446
447                 ptr += 4;
448                 image->md_version_major = read16 (ptr);
449                 ptr += 2;
450                 image->md_version_minor = read16 (ptr);
451                 ptr += 6;
452
453                 version_string_len = read32 (ptr);
454                 ptr += 4;
455                 image->version = g_strndup (ptr, version_string_len);
456                 ptr += version_string_len;
457                 pad = ptr - image->raw_metadata;
458                 if (pad % 4)
459                         ptr += 4 - (pad % 4);
460         } else
461                 return FALSE;
462
463         /* skip over flags */
464         ptr += 2;
465         
466         streams = read16 (ptr);
467         ptr += 2;
468
469         for (i = 0; i < streams; i++){
470                 if (strncmp (ptr + 8, "#~", 3) == 0){
471                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
472                         image->heap_tables.size = read32 (ptr + 4);
473                         ptr += 8 + 3;
474                 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
475                         image->heap_strings.data = image->raw_metadata + read32 (ptr);
476                         image->heap_strings.size = read32 (ptr + 4);
477                         ptr += 8 + 9;
478                 } else if (strncmp (ptr + 8, "#US", 4) == 0){
479                         image->heap_us.data = image->raw_metadata + read32 (ptr);
480                         image->heap_us.size = read32 (ptr + 4);
481                         ptr += 8 + 4;
482                 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
483                         image->heap_blob.data = image->raw_metadata + read32 (ptr);
484                         image->heap_blob.size = read32 (ptr + 4);
485                         ptr += 8 + 6;
486                 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
487                         image->heap_guid.data = image->raw_metadata + read32 (ptr);
488                         image->heap_guid.size = read32 (ptr + 4);
489                         ptr += 8 + 6;
490                 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
491                         image->heap_tables.data = image->raw_metadata + read32 (ptr);
492                         image->heap_tables.size = read32 (ptr + 4);
493                         ptr += 8 + 3;
494                         image->uncompressed_metadata = TRUE;
495                         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);
496                 } else if (strncmp (ptr + 8, "#Pdb", 5) == 0) {
497                         image->heap_pdb.data = image->raw_metadata + read32 (ptr);
498                         image->heap_pdb.size = read32 (ptr + 4);
499                         ptr += 8 + 5;
500                 } else {
501                         g_message ("Unknown heap type: %s\n", ptr + 8);
502                         ptr += 8 + strlen (ptr + 8) + 1;
503                 }
504                 pad = ptr - image->raw_metadata;
505                 if (pad % 4)
506                         ptr += 4 - (pad % 4);
507         }
508
509         i = ((MonoImageLoader*)image->loader)->load_tables (image);
510         g_assert (image->heap_guid.data);
511         g_assert (image->heap_guid.size >= 16);
512
513         image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
514
515         return i;
516 }
517
518 /*
519  * Load representation of logical metadata tables, from the "#~" stream
520  */
521 static gboolean
522 load_tables (MonoImage *image)
523 {
524         const char *heap_tables = image->heap_tables.data;
525         const guint32 *rows;
526         guint64 valid_mask;
527         int valid = 0, table;
528         int heap_sizes;
529         
530         heap_sizes = heap_tables [6];
531         image->idx_string_wide = ((heap_sizes & 0x01) == 1);
532         image->idx_guid_wide   = ((heap_sizes & 0x02) == 2);
533         image->idx_blob_wide   = ((heap_sizes & 0x04) == 4);
534         
535         valid_mask = read64 (heap_tables + 8);
536         rows = (const guint32 *) (heap_tables + 24);
537         
538         for (table = 0; table < 64; table++){
539                 if ((valid_mask & ((guint64) 1 << table)) == 0){
540                         if (table > MONO_TABLE_LAST)
541                                 continue;
542                         image->tables [table].rows = 0;
543                         continue;
544                 }
545                 if (table > MONO_TABLE_LAST) {
546                         g_warning("bits in valid must be zero above 0x37 (II - 23.1.6)");
547                 } else {
548                         image->tables [table].rows = read32 (rows);
549                 }
550                 rows++;
551                 valid++;
552         }
553
554         image->tables_base = (heap_tables + 24) + (4 * valid);
555
556         /* They must be the same */
557         g_assert ((const void *) image->tables_base == (const void *) rows);
558
559         mono_metadata_compute_table_bases (image);
560         return TRUE;
561 }
562
563 gboolean
564 mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
565 {
566         if (!load_metadata_ptrs (image, iinfo))
567                 return FALSE;
568
569         return load_tables (image);
570 }
571
572 void
573 mono_image_check_for_module_cctor (MonoImage *image)
574 {
575         MonoTableInfo *t, *mt;
576         t = &image->tables [MONO_TABLE_TYPEDEF];
577         mt = &image->tables [MONO_TABLE_METHOD];
578         if (image_is_dynamic (image)) {
579                 /* FIXME: */
580                 image->checked_module_cctor = TRUE;
581                 return;
582         }
583         if (t->rows >= 1) {
584                 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
585                 const char *name = mono_metadata_string_heap (image, nameidx);
586                 if (strcmp (name, "<Module>") == 0) {
587                         guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
588                         guint32 last_method;
589                         if (t->rows > 1)
590                                 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
591                         else 
592                                 last_method = mt->rows;
593                         for (; first_method < last_method; first_method++) {
594                                 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
595                                 name = mono_metadata_string_heap (image, nameidx);
596                                 if (strcmp (name, ".cctor") == 0) {
597                                         image->has_module_cctor = TRUE;
598                                         image->checked_module_cctor = TRUE;
599                                         return;
600                                 }
601                         }
602                 }
603         }
604         image->has_module_cctor = FALSE;
605         image->checked_module_cctor = TRUE;
606 }
607
608 static void
609 load_modules (MonoImage *image)
610 {
611         MonoTableInfo *t;
612
613         if (image->modules)
614                 return;
615
616         t = &image->tables [MONO_TABLE_MODULEREF];
617         image->modules = g_new0 (MonoImage *, t->rows);
618         image->modules_loaded = g_new0 (gboolean, t->rows);
619         image->module_count = t->rows;
620 }
621
622 /**
623  * mono_image_load_module:
624  *
625  *   Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
626  * it cannot be loaded.
627  */
628 MonoImage*
629 mono_image_load_module (MonoImage *image, int idx)
630 {
631         MonoTableInfo *t;
632         MonoTableInfo *file_table;
633         int i;
634         char *base_dir;
635         gboolean refonly = image->ref_only;
636         GList *list_iter, *valid_modules = NULL;
637         MonoImageOpenStatus status;
638
639         if ((image->module_count == 0) || (idx > image->module_count || idx <= 0))
640                 return NULL;
641         if (image->modules_loaded [idx - 1])
642                 return image->modules [idx - 1];
643
644         file_table = &image->tables [MONO_TABLE_FILE];
645         for (i = 0; i < file_table->rows; i++) {
646                 guint32 cols [MONO_FILE_SIZE];
647                 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
648                 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
649                         continue;
650                 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
651         }
652
653         t = &image->tables [MONO_TABLE_MODULEREF];
654         base_dir = g_path_get_dirname (image->name);
655
656         {
657                 char *module_ref;
658                 const char *name;
659                 guint32 cols [MONO_MODULEREF_SIZE];
660                 /* if there is no file table, we try to load the module... */
661                 int valid = file_table->rows == 0;
662
663                 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
664                 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
665                 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
666                         /* be safe with string dups, but we could just compare string indexes  */
667                         if (strcmp (list_iter->data, name) == 0) {
668                                 valid = TRUE;
669                                 break;
670                         }
671                 }
672                 if (valid) {
673                         module_ref = g_build_filename (base_dir, name, NULL);
674                         image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
675                         if (image->modules [idx - 1]) {
676                                 mono_image_addref (image->modules [idx - 1]);
677                                 image->modules [idx - 1]->assembly = image->assembly;
678 #ifdef HOST_WIN32
679                                 if (image->modules [idx - 1]->is_module_handle)
680                                         mono_image_fixup_vtable (image->modules [idx - 1]);
681 #endif
682                                 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
683                         }
684                         g_free (module_ref);
685                 }
686         }
687
688         image->modules_loaded [idx - 1] = TRUE;
689
690         g_free (base_dir);
691         g_list_free (valid_modules);
692
693         return image->modules [idx - 1];
694 }
695
696 static gpointer
697 class_key_extract (gpointer value)
698 {
699         MonoClass *class = value;
700
701         return GUINT_TO_POINTER (class->type_token);
702 }
703
704 static gpointer*
705 class_next_value (gpointer value)
706 {
707         MonoClass *class = value;
708
709         return (gpointer*)&class->next_class_cache;
710 }
711
712 void
713 mono_image_init (MonoImage *image)
714 {
715         mono_mutex_init_recursive (&image->lock);
716         mono_mutex_init_recursive (&image->szarray_cache_lock);
717
718         image->mempool = mono_mempool_new_size (INITIAL_IMAGE_SIZE);
719         mono_internal_hash_table_init (&image->class_cache,
720                                        g_direct_hash,
721                                        class_key_extract,
722                                        class_next_value);
723         image->field_cache = mono_conc_hashtable_new (NULL, NULL);
724
725         image->typespec_cache = g_hash_table_new (NULL, NULL);
726         image->memberref_signatures = g_hash_table_new (NULL, NULL);
727         image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
728         image->method_signatures = g_hash_table_new (NULL, NULL);
729
730         image->property_hash = mono_property_hash_new ();
731 }
732
733 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
734 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
735 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
736 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
737 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
738 #else
739 #define SWAP64(x)
740 #define SWAP32(x)
741 #define SWAP16(x)
742 #define SWAPPDE(x)
743 #endif
744
745 /*
746  * Returns < 0 to indicate an error.
747  */
748 static int
749 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
750 {
751         MonoDotNetHeader64 header64;
752
753 #ifdef HOST_WIN32
754         if (!image->is_module_handle)
755 #endif
756         if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
757                 return -1;
758
759         memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
760
761         if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
762                 return -1;
763
764         /* endian swap the fields common between PE and PE+ */
765         SWAP32 (header->coff.coff_time);
766         SWAP32 (header->coff.coff_symptr);
767         SWAP32 (header->coff.coff_symcount);
768         SWAP16 (header->coff.coff_machine);
769         SWAP16 (header->coff.coff_sections);
770         SWAP16 (header->coff.coff_opt_header_size);
771         SWAP16 (header->coff.coff_attributes);
772         /* MonoPEHeader */
773         SWAP32 (header->pe.pe_code_size);
774         SWAP32 (header->pe.pe_uninit_data_size);
775         SWAP32 (header->pe.pe_rva_entry_point);
776         SWAP32 (header->pe.pe_rva_code_base);
777         SWAP32 (header->pe.pe_rva_data_base);
778         SWAP16 (header->pe.pe_magic);
779
780         /* now we are ready for the basic tests */
781
782         if (header->pe.pe_magic == 0x10B) {
783                 offset += sizeof (MonoDotNetHeader);
784                 SWAP32 (header->pe.pe_data_size);
785                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
786                         return -1;
787
788                 SWAP32  (header->nt.pe_image_base);     /* must be 0x400000 */
789                 SWAP32  (header->nt.pe_stack_reserve);
790                 SWAP32  (header->nt.pe_stack_commit);
791                 SWAP32  (header->nt.pe_heap_reserve);
792                 SWAP32  (header->nt.pe_heap_commit);
793         } else if (header->pe.pe_magic == 0x20B) {
794                 /* PE32+ file format */
795                 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
796                         return -1;
797                 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
798                 offset += sizeof (MonoDotNetHeader64);
799                 /* copy the fields already swapped. the last field, pe_data_size, is missing */
800                 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
801                 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
802                  * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
803                  */
804                 SWAP64  (header64.nt.pe_image_base);
805                 header->nt.pe_image_base = header64.nt.pe_image_base;
806                 SWAP64  (header64.nt.pe_stack_reserve);
807                 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
808                 SWAP64  (header64.nt.pe_stack_commit);
809                 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
810                 SWAP64  (header64.nt.pe_heap_reserve);
811                 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
812                 SWAP64  (header64.nt.pe_heap_commit);
813                 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
814
815                 header->nt.pe_section_align = header64.nt.pe_section_align;
816                 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
817                 header->nt.pe_os_major = header64.nt.pe_os_major;
818                 header->nt.pe_os_minor = header64.nt.pe_os_minor;
819                 header->nt.pe_user_major = header64.nt.pe_user_major;
820                 header->nt.pe_user_minor = header64.nt.pe_user_minor;
821                 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
822                 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
823                 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
824                 header->nt.pe_image_size = header64.nt.pe_image_size;
825                 header->nt.pe_header_size = header64.nt.pe_header_size;
826                 header->nt.pe_checksum = header64.nt.pe_checksum;
827                 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
828                 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
829                 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
830                 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
831
832                 /* copy the datadir */
833                 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
834         } else {
835                 return -1;
836         }
837
838         /* MonoPEHeaderNT: not used yet */
839         SWAP32  (header->nt.pe_section_align);       /* must be 8192 */
840         SWAP32  (header->nt.pe_file_alignment);      /* must be 512 or 4096 */
841         SWAP16  (header->nt.pe_os_major);            /* must be 4 */
842         SWAP16  (header->nt.pe_os_minor);            /* must be 0 */
843         SWAP16  (header->nt.pe_user_major);
844         SWAP16  (header->nt.pe_user_minor);
845         SWAP16  (header->nt.pe_subsys_major);
846         SWAP16  (header->nt.pe_subsys_minor);
847         SWAP32  (header->nt.pe_reserved_1);
848         SWAP32  (header->nt.pe_image_size);
849         SWAP32  (header->nt.pe_header_size);
850         SWAP32  (header->nt.pe_checksum);
851         SWAP16  (header->nt.pe_subsys_required);
852         SWAP16  (header->nt.pe_dll_flags);
853         SWAP32  (header->nt.pe_loader_flags);
854         SWAP32  (header->nt.pe_data_dir_count);
855
856         /* MonoDotNetHeader: mostly unused */
857         SWAPPDE (header->datadir.pe_export_table);
858         SWAPPDE (header->datadir.pe_import_table);
859         SWAPPDE (header->datadir.pe_resource_table);
860         SWAPPDE (header->datadir.pe_exception_table);
861         SWAPPDE (header->datadir.pe_certificate_table);
862         SWAPPDE (header->datadir.pe_reloc_table);
863         SWAPPDE (header->datadir.pe_debug);
864         SWAPPDE (header->datadir.pe_copyright);
865         SWAPPDE (header->datadir.pe_global_ptr);
866         SWAPPDE (header->datadir.pe_tls_table);
867         SWAPPDE (header->datadir.pe_load_config_table);
868         SWAPPDE (header->datadir.pe_bound_import);
869         SWAPPDE (header->datadir.pe_iat);
870         SWAPPDE (header->datadir.pe_delay_import_desc);
871         SWAPPDE (header->datadir.pe_cli_header);
872         SWAPPDE (header->datadir.pe_reserved);
873
874 #ifdef HOST_WIN32
875         if (image->is_module_handle)
876                 image->raw_data_len = header->nt.pe_image_size;
877 #endif
878
879         return offset;
880 }
881
882 gboolean
883 mono_image_load_pe_data (MonoImage *image)
884 {
885         return ((MonoImageLoader*)image->loader)->load_pe_data (image);
886 }
887
888 static gboolean
889 pe_image_load_pe_data (MonoImage *image)
890 {
891         MonoCLIImageInfo *iinfo;
892         MonoDotNetHeader *header;
893         MonoMSDOSHeader msdos;
894         gint32 offset = 0;
895
896         iinfo = image->image_info;
897         header = &iinfo->cli_header;
898
899 #ifdef HOST_WIN32
900         if (!image->is_module_handle)
901 #endif
902         if (offset + sizeof (msdos) > image->raw_data_len)
903                 goto invalid_image;
904         memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
905         
906         if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
907                 goto invalid_image;
908         
909         msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
910
911         offset = msdos.pe_offset;
912
913         offset = do_load_header (image, header, offset);
914         if (offset < 0)
915                 goto invalid_image;
916
917         /*
918          * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
919          * we skip this test.
920         if (header->coff.coff_machine != 0x14c)
921                 goto invalid_image;
922         */
923
924 #if 0
925         /*
926          * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
927          * which produces binaries with 7.0.  From Sergey:
928          *
929          * The reason is that MSVC7 uses traditional compile/link
930          * sequence for CIL executables, and VS.NET (and Framework
931          * SDK) includes linker version 7, that puts 7.0 in this
932          * field.  That's why it's currently not possible to load VC
933          * binaries with Mono.  This field is pretty much meaningless
934          * anyway (what linker?).
935          */
936         if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
937                 goto invalid_image;
938 #endif
939
940         /*
941          * FIXME: byte swap all addresses here for header.
942          */
943         
944         if (!load_section_tables (image, iinfo, offset))
945                 goto invalid_image;
946
947         return TRUE;
948
949 invalid_image:
950         return FALSE;
951 }
952
953 gboolean
954 mono_image_load_cli_data (MonoImage *image)
955 {
956         return ((MonoImageLoader*)image->loader)->load_cli_data (image);
957 }
958
959 static gboolean
960 pe_image_load_cli_data (MonoImage *image)
961 {
962         MonoCLIImageInfo *iinfo;
963         MonoDotNetHeader *header;
964
965         iinfo = image->image_info;
966         header = &iinfo->cli_header;
967
968         /* Load the CLI header */
969         if (!mono_image_load_cli_header (image, iinfo))
970                 return FALSE;
971
972         if (!mono_image_load_metadata (image, iinfo))
973                 return FALSE;
974
975         return TRUE;
976 }
977
978 void
979 mono_image_load_names (MonoImage *image)
980 {
981         /* modules don't have an assembly table row */
982         if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
983                 image->assembly_name = mono_metadata_string_heap (image, 
984                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
985                                         0, MONO_ASSEMBLY_NAME));
986         }
987
988         /* Portable pdb images don't have a MODULE row */
989         if (image->tables [MONO_TABLE_MODULE].rows) {
990                 image->module_name = mono_metadata_string_heap (image,
991                         mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
992                                         0, MONO_MODULE_NAME));
993         }
994 }
995
996 static gboolean
997 pe_image_load_tables (MonoImage *image)
998 {
999         return TRUE;
1000 }
1001
1002 static gboolean
1003 pe_image_match (MonoImage *image)
1004 {
1005         if (image->raw_data [0] == 'M' && image->raw_data [1] == 'Z')
1006                 return TRUE;
1007         return FALSE;
1008 }
1009
1010 static const MonoImageLoader pe_loader = {
1011         pe_image_match,
1012         pe_image_load_pe_data,
1013         pe_image_load_cli_data,
1014         pe_image_load_tables,
1015 };
1016
1017 static void
1018 install_pe_loader (void)
1019 {
1020         mono_install_image_loader (&pe_loader);
1021 }
1022
1023 static MonoImage *
1024 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
1025                     gboolean care_about_cli, gboolean care_about_pecoff)
1026 {
1027         MonoCLIImageInfo *iinfo;
1028         MonoDotNetHeader *header;
1029         GSList *errors = NULL;
1030         GSList *l;
1031
1032         mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
1033
1034         mono_image_init (image);
1035
1036         iinfo = image->image_info;
1037         header = &iinfo->cli_header;
1038
1039         for (l = image_loaders; l; l = l->next) {
1040                 MonoImageLoader *loader = l->data;
1041                 if (loader->match (image)) {
1042                         image->loader = loader;
1043                         break;
1044                 }
1045         }
1046         if (!image->loader) {
1047                 *status = MONO_IMAGE_IMAGE_INVALID;
1048                 goto invalid_image;
1049         }
1050
1051         if (status)
1052                 *status = MONO_IMAGE_IMAGE_INVALID;
1053
1054         if (care_about_pecoff == FALSE)
1055                 goto done;
1056
1057         if (!image->metadata_only) {
1058                 if (image->loader == &pe_loader && !mono_verifier_verify_pe_data (image, &errors))
1059                         goto invalid_image;
1060
1061                 if (!mono_image_load_pe_data (image))
1062                         goto invalid_image;
1063         }
1064
1065         if (care_about_cli == FALSE) {
1066                 goto done;
1067         }
1068
1069         if (image->loader == &pe_loader && !mono_verifier_verify_cli_data (image, &errors))
1070                 goto invalid_image;
1071
1072         if (!mono_image_load_cli_data (image))
1073                 goto invalid_image;
1074
1075         if (image->loader == &pe_loader && !mono_verifier_verify_table_data (image, &errors))
1076                 goto invalid_image;
1077
1078         mono_image_load_names (image);
1079
1080         load_modules (image);
1081
1082 done:
1083         mono_profiler_module_loaded (image, MONO_PROFILE_OK);
1084         if (status)
1085                 *status = MONO_IMAGE_OK;
1086
1087         return image;
1088
1089 invalid_image:
1090         if (errors) {
1091                 MonoVerifyInfo *info = errors->data;
1092                 g_warning ("Could not load image %s due to %s", image->name, info->message);
1093                 mono_free_verify_list (errors);
1094         }
1095         mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
1096         mono_image_close (image);
1097         return NULL;
1098 }
1099
1100 static MonoImage *
1101 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
1102                                         gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly, gboolean metadata_only)
1103 {
1104         MonoCLIImageInfo *iinfo;
1105         MonoImage *image;
1106         MonoFileMap *filed;
1107
1108         if ((filed = mono_file_map_open (fname)) == NULL){
1109                 if (IS_PORTABILITY_SET) {
1110                         gchar *ffname = mono_portability_find_file (fname, TRUE);
1111                         if (ffname) {
1112                                 filed = mono_file_map_open (ffname);
1113                                 g_free (ffname);
1114                         }
1115                 }
1116
1117                 if (filed == NULL) {
1118                         if (status)
1119                                 *status = MONO_IMAGE_ERROR_ERRNO;
1120                         return NULL;
1121                 }
1122         }
1123
1124         image = g_new0 (MonoImage, 1);
1125         image->raw_buffer_used = TRUE;
1126         image->raw_data_len = mono_file_map_size (filed);
1127         image->raw_data = mono_file_map (image->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &image->raw_data_handle);
1128 #if defined(HAVE_MMAP) && !defined (HOST_WIN32)
1129         if (!image->raw_data) {
1130                 image->fileio_used = TRUE;
1131                 image->raw_data = mono_file_map_fileio (image->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &image->raw_data_handle);
1132         }
1133 #endif
1134         if (!image->raw_data) {
1135                 mono_file_map_close (filed);
1136                 g_free (image);
1137                 if (status)
1138                         *status = MONO_IMAGE_IMAGE_INVALID;
1139                 return NULL;
1140         }
1141         iinfo = g_new0 (MonoCLIImageInfo, 1);
1142         image->image_info = iinfo;
1143         image->name = mono_path_resolve_symlinks (fname);
1144         image->ref_only = refonly;
1145         image->metadata_only = metadata_only;
1146         image->ref_count = 1;
1147         /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
1148         image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
1149
1150         mono_file_map_close (filed);
1151         return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
1152 }
1153
1154 /**
1155  * mono_image_loaded:
1156  * @name: path or assembly name of the image to load
1157  * @refonly: Check with respect to reflection-only loads?
1158  *
1159  * This routine verifies that the given image is loaded.
1160  * It checks either reflection-only loads only, or normal loads only, as specified by parameter.
1161  *
1162  * Returns: the loaded MonoImage, or NULL on failure.
1163  */
1164 MonoImage *
1165 mono_image_loaded_full (const char *name, gboolean refonly)
1166 {
1167         MonoImage *res;
1168
1169         mono_images_lock ();
1170         res = g_hash_table_lookup (get_loaded_images_hash (refonly), name);
1171         if (!res)
1172                 res = g_hash_table_lookup (get_loaded_images_by_name_hash (refonly), name);
1173         mono_images_unlock ();
1174
1175         return res;
1176 }
1177
1178 /**
1179  * mono_image_loaded:
1180  * @name: path or assembly name of the image to load
1181  *
1182  * This routine verifies that the given image is loaded. Reflection-only loads do not count.
1183  *
1184  * Returns: the loaded MonoImage, or NULL on failure.
1185  */
1186 MonoImage *
1187 mono_image_loaded (const char *name)
1188 {
1189         return mono_image_loaded_full (name, FALSE);
1190 }
1191
1192 typedef struct {
1193         MonoImage *res;
1194         const char* guid;
1195 } GuidData;
1196
1197 static void
1198 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1199 {
1200         GuidData *data = user_data;
1201         MonoImage *image;
1202
1203         if (data->res)
1204                 return;
1205         image = val;
1206         if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1207                 data->res = image;
1208 }
1209
1210 MonoImage *
1211 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1212 {
1213         GuidData data;
1214         GHashTable *loaded_images = get_loaded_images_hash (refonly);
1215         data.res = NULL;
1216         data.guid = guid;
1217
1218         mono_images_lock ();
1219         g_hash_table_foreach (loaded_images, find_by_guid, &data);
1220         mono_images_unlock ();
1221         return data.res;
1222 }
1223
1224 MonoImage *
1225 mono_image_loaded_by_guid (const char *guid)
1226 {
1227         return mono_image_loaded_by_guid_full (guid, FALSE);
1228 }
1229
1230 static MonoImage *
1231 register_image (MonoImage *image)
1232 {
1233         MonoImage *image2;
1234         GHashTable *loaded_images = get_loaded_images_hash (image->ref_only);
1235
1236         mono_images_lock ();
1237         image2 = g_hash_table_lookup (loaded_images, image->name);
1238
1239         if (image2) {
1240                 /* Somebody else beat us to it */
1241                 mono_image_addref (image2);
1242                 mono_images_unlock ();
1243                 mono_image_close (image);
1244                 return image2;
1245         }
1246
1247         GHashTable *loaded_images_by_name = get_loaded_images_by_name_hash (image->ref_only);
1248         g_hash_table_insert (loaded_images, image->name, image);
1249         if (image->assembly_name && (g_hash_table_lookup (loaded_images_by_name, image->assembly_name) == NULL))
1250                 g_hash_table_insert (loaded_images_by_name, (char *) image->assembly_name, image);
1251         mono_images_unlock ();
1252
1253         return image;
1254 }
1255
1256 MonoImage *
1257 mono_image_open_from_data_internal (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, gboolean metadata_only, const char *name)
1258 {
1259         MonoCLIImageInfo *iinfo;
1260         MonoImage *image;
1261         char *datac;
1262
1263         if (!data || !data_len) {
1264                 if (status)
1265                         *status = MONO_IMAGE_IMAGE_INVALID;
1266                 return NULL;
1267         }
1268         datac = data;
1269         if (need_copy) {
1270                 datac = g_try_malloc (data_len);
1271                 if (!datac) {
1272                         if (status)
1273                                 *status = MONO_IMAGE_ERROR_ERRNO;
1274                         return NULL;
1275                 }
1276                 memcpy (datac, data, data_len);
1277         }
1278
1279         image = g_new0 (MonoImage, 1);
1280         image->raw_data = datac;
1281         image->raw_data_len = data_len;
1282         image->raw_data_allocated = need_copy;
1283         image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup(name);
1284         iinfo = g_new0 (MonoCLIImageInfo, 1);
1285         image->image_info = iinfo;
1286         image->ref_only = refonly;
1287         image->metadata_only = metadata_only;
1288
1289         image = do_mono_image_load (image, status, TRUE, TRUE);
1290         if (image == NULL)
1291                 return NULL;
1292
1293         return register_image (image);
1294 }
1295
1296 MonoImage *
1297 mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
1298 {
1299         return mono_image_open_from_data_internal (data, data_len, need_copy, status, refonly, FALSE, name);
1300 }
1301
1302 MonoImage *
1303 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1304 {
1305   return mono_image_open_from_data_with_name (data, data_len, need_copy, status, refonly, NULL);
1306 }
1307
1308 MonoImage *
1309 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1310 {
1311         return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1312 }
1313
1314 #ifdef HOST_WIN32
1315 /* fname is not duplicated. */
1316 MonoImage*
1317 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1318 {
1319         MonoImage* image;
1320         MonoCLIImageInfo* iinfo;
1321
1322         image = g_new0 (MonoImage, 1);
1323         image->raw_data = (char*) module_handle;
1324         image->is_module_handle = TRUE;
1325         iinfo = g_new0 (MonoCLIImageInfo, 1);
1326         image->image_info = iinfo;
1327         image->name = fname;
1328         image->ref_count = has_entry_point ? 0 : 1;
1329         image->has_entry_point = has_entry_point;
1330
1331         image = do_mono_image_load (image, status, TRUE, TRUE);
1332         if (image == NULL)
1333                 return NULL;
1334
1335         return register_image (image);
1336 }
1337 #endif
1338
1339 MonoImage *
1340 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1341 {
1342         MonoImage *image;
1343         GHashTable *loaded_images = get_loaded_images_hash (refonly);
1344         char *absfname;
1345         
1346         g_return_val_if_fail (fname != NULL, NULL);
1347         
1348 #ifdef HOST_WIN32
1349         // Win32 path: If we are running with mixed-mode assemblies enabled (ie have loaded mscoree.dll),
1350         // then assemblies need to be loaded with LoadLibrary:
1351         if (!refonly && coree_module_handle) {
1352                 HMODULE module_handle;
1353                 guint16 *fname_utf16;
1354                 DWORD last_error;
1355
1356                 absfname = mono_path_resolve_symlinks (fname);
1357                 fname_utf16 = NULL;
1358
1359                 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1360                 mono_images_lock ();
1361                 image = g_hash_table_lookup (loaded_images, absfname);
1362                 if (image) { // Image already loaded
1363                         g_assert (image->is_module_handle);
1364                         if (image->has_entry_point && image->ref_count == 0) {
1365                                 /* Increment reference count on images loaded outside of the runtime. */
1366                                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1367                                 /* The image is already loaded because _CorDllMain removes images from the hash. */
1368                                 module_handle = LoadLibrary (fname_utf16);
1369                                 g_assert (module_handle == (HMODULE) image->raw_data);
1370                         }
1371                         mono_image_addref (image);
1372                         mono_images_unlock ();
1373                         if (fname_utf16)
1374                                 g_free (fname_utf16);
1375                         g_free (absfname);
1376                         return image;
1377                 }
1378
1379                 // Image not loaded, load it now
1380                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1381                 module_handle = MonoLoadImage (fname_utf16);
1382                 if (status && module_handle == NULL)
1383                         last_error = GetLastError ();
1384
1385                 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1386                 image = g_hash_table_lookup (loaded_images, absfname);
1387                 if (image)
1388                         mono_image_addref (image);
1389                 mono_images_unlock ();
1390
1391                 g_free (fname_utf16);
1392
1393                 if (module_handle == NULL) {
1394                         g_assert (!image);
1395                         g_free (absfname);
1396                         if (status) {
1397                                 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1398                                         *status = MONO_IMAGE_IMAGE_INVALID;
1399                                 else {
1400                                         if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND)
1401                                                 errno = ENOENT;
1402                                         else
1403                                                 errno = 0;
1404                                 }
1405                         }
1406                         return NULL;
1407                 }
1408
1409                 if (image) {
1410                         g_assert (image->is_module_handle);
1411                         g_assert (image->has_entry_point);
1412                         g_free (absfname);
1413                         return image;
1414                 }
1415
1416                 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1417         }
1418 #endif
1419
1420         absfname = mono_path_canonicalize (fname);
1421
1422         /*
1423          * The easiest solution would be to do all the loading inside the mutex,
1424          * but that would lead to scalability problems. So we let the loading
1425          * happen outside the mutex, and if multiple threads happen to load
1426          * the same image, we discard all but the first copy.
1427          */
1428         mono_images_lock ();
1429         image = g_hash_table_lookup (loaded_images, absfname);
1430         g_free (absfname);
1431
1432         if (image) { // Image already loaded
1433                 mono_image_addref (image);
1434                 mono_images_unlock ();
1435                 return image;
1436         }
1437         mono_images_unlock ();
1438
1439         // Image not loaded, load it now
1440         image = do_mono_image_open (fname, status, TRUE, TRUE, refonly, FALSE);
1441         if (image == NULL)
1442                 return NULL;
1443
1444         return register_image (image);
1445 }
1446
1447 /**
1448  * mono_image_open:
1449  * @fname: filename that points to the module we want to open
1450  * @status: An error condition is returned in this field
1451  *
1452  * Returns: An open image of type %MonoImage or NULL on error. 
1453  * The caller holds a temporary reference to the returned image which should be cleared 
1454  * when no longer needed by calling mono_image_close ().
1455  * if NULL, then check the value of @status for details on the error
1456  */
1457 MonoImage *
1458 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1459 {
1460         return mono_image_open_full (fname, status, FALSE);
1461 }
1462
1463 /**
1464  * mono_pe_file_open:
1465  * @fname: filename that points to the module we want to open
1466  * @status: An error condition is returned in this field
1467  *
1468  * Returns: An open image of type %MonoImage or NULL on error.  if
1469  * NULL, then check the value of @status for details on the error.
1470  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1471  * It's just a PE file loader, used for FileVersionInfo.  It also does
1472  * not use the image cache.
1473  */
1474 MonoImage *
1475 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1476 {
1477         g_return_val_if_fail (fname != NULL, NULL);
1478         
1479         return do_mono_image_open (fname, status, FALSE, TRUE, FALSE, FALSE);
1480 }
1481
1482 /**
1483  * mono_image_open_raw
1484  * @fname: filename that points to the module we want to open
1485  * @status: An error condition is returned in this field
1486  * 
1487  * Returns an image without loading neither pe or cli data.
1488  * 
1489  * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.  
1490  */
1491 MonoImage *
1492 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1493 {
1494         g_return_val_if_fail (fname != NULL, NULL);
1495         
1496         return do_mono_image_open (fname, status, FALSE, FALSE, FALSE, FALSE);
1497 }
1498
1499 /*
1500  * mono_image_open_metadata_only:
1501  *
1502  *   Open an image which contains metadata only without a PE header.
1503  */
1504 MonoImage *
1505 mono_image_open_metadata_only (const char *fname, MonoImageOpenStatus *status)
1506 {
1507         return do_mono_image_open (fname, status, TRUE, TRUE, FALSE, TRUE);
1508 }
1509
1510 void
1511 mono_image_fixup_vtable (MonoImage *image)
1512 {
1513 #ifdef HOST_WIN32
1514         MonoCLIImageInfo *iinfo;
1515         MonoPEDirEntry *de;
1516         MonoVTableFixup *vtfixup;
1517         int count;
1518         gpointer slot;
1519         guint16 slot_type;
1520         int slot_count;
1521
1522         g_assert (image->is_module_handle);
1523
1524         iinfo = image->image_info;
1525         de = &iinfo->cli_cli_header.ch_vtable_fixups;
1526         if (!de->rva || !de->size)
1527                 return;
1528         vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1529         if (!vtfixup)
1530                 return;
1531         
1532         count = de->size / sizeof (MonoVTableFixup);
1533         while (count--) {
1534                 if (!vtfixup->rva || !vtfixup->count)
1535                         continue;
1536
1537                 slot = mono_image_rva_map (image, vtfixup->rva);
1538                 g_assert (slot);
1539                 slot_type = vtfixup->type;
1540                 slot_count = vtfixup->count;
1541                 if (slot_type & VTFIXUP_TYPE_32BIT)
1542                         while (slot_count--) {
1543                                 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1544                                 slot = ((guint32*) slot) + 1;
1545                         }
1546                 else if (slot_type & VTFIXUP_TYPE_64BIT)
1547                         while (slot_count--) {
1548                                 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1549                                 slot = ((guint32*) slot) + 1;
1550                         }
1551                 else
1552                         g_assert_not_reached();
1553
1554                 vtfixup++;
1555         }
1556 #else
1557         g_assert_not_reached();
1558 #endif
1559 }
1560
1561 static void
1562 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1563 {
1564         g_hash_table_destroy ((GHashTable*)val);
1565 }
1566
1567 /*
1568 static void
1569 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1570 {
1571         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1572 }
1573 */
1574
1575 static void
1576 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1577 {
1578         g_slist_free ((GSList*)val);
1579 }
1580
1581 /**
1582  * mono_image_addref:
1583  * @image: The image file we wish to add a reference to
1584  *
1585  *  Increases the reference count of an image.
1586  */
1587 void
1588 mono_image_addref (MonoImage *image)
1589 {
1590         InterlockedIncrement (&image->ref_count);
1591 }       
1592
1593 void
1594 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1595 {
1596         stream->alloc_size = stream->index = stream->offset = 0;
1597         g_free (stream->data);
1598         stream->data = NULL;
1599         if (stream->hash) {
1600                 g_hash_table_destroy (stream->hash);
1601                 stream->hash = NULL;
1602         }
1603 }
1604
1605 static inline void
1606 free_hash (GHashTable *hash)
1607 {
1608         if (hash)
1609                 g_hash_table_destroy (hash);
1610 }
1611
1612 void
1613 mono_wrapper_caches_free (MonoWrapperCaches *cache)
1614 {
1615         free_hash (cache->delegate_invoke_cache);
1616         free_hash (cache->delegate_begin_invoke_cache);
1617         free_hash (cache->delegate_end_invoke_cache);
1618         free_hash (cache->runtime_invoke_cache);
1619         free_hash (cache->runtime_invoke_vtype_cache);
1620         
1621         free_hash (cache->delegate_abstract_invoke_cache);
1622
1623         free_hash (cache->runtime_invoke_direct_cache);
1624         free_hash (cache->managed_wrapper_cache);
1625
1626         free_hash (cache->native_wrapper_cache);
1627         free_hash (cache->native_wrapper_aot_cache);
1628         free_hash (cache->native_wrapper_check_cache);
1629         free_hash (cache->native_wrapper_aot_check_cache);
1630
1631         free_hash (cache->native_func_wrapper_aot_cache);
1632         free_hash (cache->remoting_invoke_cache);
1633         free_hash (cache->synchronized_cache);
1634         free_hash (cache->unbox_wrapper_cache);
1635         free_hash (cache->cominterop_invoke_cache);
1636         free_hash (cache->cominterop_wrapper_cache);
1637         free_hash (cache->thunk_invoke_cache);
1638 }
1639
1640 /*
1641  * Returns whether mono_image_close_finish() must be called as well.
1642  * We must unload images in two steps because clearing the domain in
1643  * SGen requires the class metadata to be intact, but we need to free
1644  * the mono_g_hash_tables in case a collection occurs during domain
1645  * unloading and the roots would trip up the GC.
1646  */
1647 gboolean
1648 mono_image_close_except_pools (MonoImage *image)
1649 {
1650         MonoImage *image2;
1651         GHashTable *loaded_images, *loaded_images_by_name;
1652         int i;
1653
1654         g_return_val_if_fail (image != NULL, FALSE);
1655
1656         /*
1657          * Atomically decrement the refcount and remove ourselves from the hash tables, so
1658          * register_image () can't grab an image which is being closed.
1659          */
1660         mono_images_lock ();
1661
1662         if (InterlockedDecrement (&image->ref_count) > 0) {
1663                 mono_images_unlock ();
1664                 return FALSE;
1665         }
1666
1667         loaded_images         = get_loaded_images_hash (image->ref_only);
1668         loaded_images_by_name = get_loaded_images_by_name_hash (image->ref_only);
1669         image2 = g_hash_table_lookup (loaded_images, image->name);
1670         if (image == image2) {
1671                 /* This is not true if we are called from mono_image_open () */
1672                 g_hash_table_remove (loaded_images, image->name);
1673         }
1674         if (image->assembly_name && (g_hash_table_lookup (loaded_images_by_name, image->assembly_name) == image))
1675                 g_hash_table_remove (loaded_images_by_name, (char *) image->assembly_name);     
1676
1677         mono_images_unlock ();
1678
1679 #ifdef HOST_WIN32
1680         if (image->is_module_handle && image->has_entry_point) {
1681                 mono_images_lock ();
1682                 if (image->ref_count == 0) {
1683                         /* Image will be closed by _CorDllMain. */
1684                         FreeLibrary ((HMODULE) image->raw_data);
1685                         mono_images_unlock ();
1686                         return FALSE;
1687                 }
1688                 mono_images_unlock ();
1689         }
1690 #endif
1691
1692         mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1693
1694         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1695
1696         mono_image_invoke_unload_hook (image);
1697
1698         mono_metadata_clean_for_image (image);
1699
1700         /*
1701          * The caches inside a MonoImage might refer to metadata which is stored in referenced 
1702          * assemblies, so we can't release these references in mono_assembly_close () since the
1703          * MonoImage might outlive its associated MonoAssembly.
1704          */
1705         if (image->references && !image_is_dynamic (image)) {
1706                 for (i = 0; i < image->nreferences; i++) {
1707                         if (image->references [i] && image->references [i] != REFERENCE_MISSING) {
1708                                 if (!mono_assembly_close_except_image_pools (image->references [i]))
1709                                         image->references [i] = NULL;
1710                         }
1711                 }
1712         } else {
1713                 if (image->references) {
1714                         g_free (image->references);
1715                         image->references = NULL;
1716                 }
1717         }
1718
1719 #ifdef HOST_WIN32
1720         mono_images_lock ();
1721         if (image->is_module_handle && !image->has_entry_point)
1722                 FreeLibrary ((HMODULE) image->raw_data);
1723         mono_images_unlock ();
1724 #endif
1725
1726         if (image->raw_buffer_used) {
1727                 if (image->raw_data != NULL) {
1728 #ifndef HOST_WIN32
1729                         if (image->fileio_used)
1730                                 mono_file_unmap_fileio (image->raw_data, image->raw_data_handle);
1731                         else
1732 #endif
1733                                 mono_file_unmap (image->raw_data, image->raw_data_handle);
1734                 }
1735         }
1736         
1737         if (image->raw_data_allocated) {
1738                 /* FIXME: do we need this? (image is disposed anyway) */
1739                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1740                 MonoCLIImageInfo *ii = image->image_info;
1741
1742                 if ((image->raw_metadata > image->raw_data) &&
1743                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1744                         image->raw_metadata = NULL;
1745
1746                 for (i = 0; i < ii->cli_section_count; i++)
1747                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1748                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1749                                 ii->cli_sections [i] = NULL;
1750
1751                 g_free (image->raw_data);
1752         }
1753
1754         if (debug_assembly_unload) {
1755                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1756         } else {
1757                 g_free (image->name);
1758                 g_free (image->guid);
1759                 g_free (image->version);
1760                 g_free (image->files);
1761         }
1762
1763         if (image->method_cache)
1764                 g_hash_table_destroy (image->method_cache);
1765         if (image->methodref_cache)
1766                 g_hash_table_destroy (image->methodref_cache);
1767         mono_internal_hash_table_destroy (&image->class_cache);
1768         mono_conc_hashtable_destroy (image->field_cache);
1769         if (image->array_cache) {
1770                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1771                 g_hash_table_destroy (image->array_cache);
1772         }
1773         if (image->szarray_cache)
1774                 g_hash_table_destroy (image->szarray_cache);
1775         if (image->ptr_cache)
1776                 g_hash_table_destroy (image->ptr_cache);
1777         if (image->name_cache) {
1778                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1779                 g_hash_table_destroy (image->name_cache);
1780         }
1781
1782         free_hash (image->delegate_bound_static_invoke_cache);
1783         free_hash (image->runtime_invoke_vcall_cache);
1784         free_hash (image->ldfld_wrapper_cache);
1785         free_hash (image->ldflda_wrapper_cache);
1786         free_hash (image->stfld_wrapper_cache);
1787         free_hash (image->isinst_cache);
1788         free_hash (image->castclass_cache);
1789         free_hash (image->proxy_isinst_cache);
1790         free_hash (image->var_cache_slow);
1791         free_hash (image->mvar_cache_slow);
1792         free_hash (image->var_cache_constrained);
1793         free_hash (image->mvar_cache_constrained);
1794         free_hash (image->wrapper_param_names);
1795         free_hash (image->pinvoke_scopes);
1796         free_hash (image->pinvoke_scope_filenames);
1797         free_hash (image->native_func_wrapper_cache);
1798         free_hash (image->typespec_cache);
1799
1800         mono_wrapper_caches_free (&image->wrapper_caches);
1801
1802         for (i = 0; i < image->gshared_types_len; ++i)
1803                 free_hash (image->gshared_types [i]);
1804         g_free (image->gshared_types);
1805
1806         /* The ownership of signatures is not well defined */
1807         g_hash_table_destroy (image->memberref_signatures);
1808         g_hash_table_destroy (image->helper_signatures);
1809         g_hash_table_destroy (image->method_signatures);
1810
1811         if (image->rgctx_template_hash)
1812                 g_hash_table_destroy (image->rgctx_template_hash);
1813
1814         if (image->property_hash)
1815                 mono_property_hash_destroy (image->property_hash);
1816
1817         /*
1818         reflection_info_unregister_classes is only required by dynamic images, which will not be properly
1819         cleared during shutdown as we don't perform regular appdomain unload for the root one.
1820         */
1821         g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ());
1822         image->reflection_info_unregister_classes = NULL;
1823
1824         if (image->interface_bitset) {
1825                 mono_unload_interface_ids (image->interface_bitset);
1826                 mono_bitset_free (image->interface_bitset);
1827         }
1828         if (image->image_info){
1829                 MonoCLIImageInfo *ii = image->image_info;
1830
1831                 if (ii->cli_section_tables)
1832                         g_free (ii->cli_section_tables);
1833                 if (ii->cli_sections)
1834                         g_free (ii->cli_sections);
1835                 g_free (image->image_info);
1836         }
1837
1838         for (i = 0; i < image->module_count; ++i) {
1839                 if (image->modules [i]) {
1840                         if (!mono_image_close_except_pools (image->modules [i]))
1841                                 image->modules [i] = NULL;
1842                 }
1843         }
1844         if (image->modules_loaded)
1845                 g_free (image->modules_loaded);
1846
1847         mono_mutex_destroy (&image->szarray_cache_lock);
1848         mono_mutex_destroy (&image->lock);
1849
1850         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1851         if (image_is_dynamic (image)) {
1852                 /* Dynamic images are GC_MALLOCed */
1853                 g_free ((char*)image->module_name);
1854                 mono_dynamic_image_free ((MonoDynamicImage*)image);
1855         }
1856
1857         mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1858
1859         return TRUE;
1860 }
1861
1862 void
1863 mono_image_close_finish (MonoImage *image)
1864 {
1865         int i;
1866
1867         if (image->references && !image_is_dynamic (image)) {
1868                 for (i = 0; i < image->nreferences; i++) {
1869                         if (image->references [i] && image->references [i] != REFERENCE_MISSING)
1870                                 mono_assembly_close_finish (image->references [i]);
1871                 }
1872
1873                 g_free (image->references);
1874                 image->references = NULL;
1875         }
1876
1877         for (i = 0; i < image->module_count; ++i) {
1878                 if (image->modules [i])
1879                         mono_image_close_finish (image->modules [i]);
1880         }
1881         if (image->modules)
1882                 g_free (image->modules);
1883
1884 #ifndef DISABLE_PERFCOUNTERS
1885         mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1886 #endif
1887
1888         if (!image_is_dynamic (image)) {
1889                 if (debug_assembly_unload)
1890                         mono_mempool_invalidate (image->mempool);
1891                 else {
1892                         mono_mempool_destroy (image->mempool);
1893                         g_free (image);
1894                 }
1895         } else {
1896                 if (debug_assembly_unload)
1897                         mono_mempool_invalidate (image->mempool);
1898                 else {
1899                         mono_mempool_destroy (image->mempool);
1900                         mono_dynamic_image_free_image ((MonoDynamicImage*)image);
1901                 }
1902         }
1903 }
1904
1905 /**
1906  * mono_image_close:
1907  * @image: The image file we wish to close
1908  *
1909  * Closes an image file, deallocates all memory consumed and
1910  * unmaps all possible sections of the file
1911  */
1912 void
1913 mono_image_close (MonoImage *image)
1914 {
1915         if (mono_image_close_except_pools (image))
1916                 mono_image_close_finish (image);
1917 }
1918
1919 /** 
1920  * mono_image_strerror:
1921  * @status: an code indicating the result from a recent operation
1922  *
1923  * Returns: a string describing the error
1924  */
1925 const char *
1926 mono_image_strerror (MonoImageOpenStatus status)
1927 {
1928         switch (status){
1929         case MONO_IMAGE_OK:
1930                 return "success";
1931         case MONO_IMAGE_ERROR_ERRNO:
1932                 return strerror (errno);
1933         case MONO_IMAGE_IMAGE_INVALID:
1934                 return "File does not contain a valid CIL image";
1935         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1936                 return "An assembly was referenced, but could not be found";
1937         }
1938         return "Internal error";
1939 }
1940
1941 static gpointer
1942 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1943                                guint32 lang_id, gunichar2 *name,
1944                                MonoPEResourceDirEntry *entry,
1945                                MonoPEResourceDir *root, guint32 level)
1946 {
1947         gboolean is_string, is_dir;
1948         guint32 name_offset, dir_offset;
1949
1950         /* Level 0 holds a directory entry for each type of resource
1951          * (identified by ID or name).
1952          *
1953          * Level 1 holds a directory entry for each named resource
1954          * item, and each "anonymous" item of a particular type of
1955          * resource.
1956          *
1957          * Level 2 holds a directory entry for each language pointing to
1958          * the actual data.
1959          */
1960         is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1961         name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1962
1963         is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1964         dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1965
1966         if(level==0) {
1967                 if (is_string)
1968                         return NULL;
1969         } else if (level==1) {
1970                 if (res_id != name_offset)
1971                         return NULL;
1972 #if 0
1973                 if(name!=NULL &&
1974                    is_string==TRUE && name!=lookup (name_offset)) {
1975                         return(NULL);
1976                 }
1977 #endif
1978         } else if (level==2) {
1979                 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1980                         return NULL;
1981         } else {
1982                 g_assert_not_reached ();
1983         }
1984
1985         if(is_dir==TRUE) {
1986                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1987                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1988                 guint32 entries, i;
1989
1990                 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1991
1992                 for(i=0; i<entries; i++) {
1993                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1994                         gpointer ret;
1995                         
1996                         ret=mono_image_walk_resource_tree (info, res_id,
1997                                                            lang_id, name,
1998                                                            sub_entry, root,
1999                                                            level+1);
2000                         if(ret!=NULL) {
2001                                 return(ret);
2002                         }
2003                 }
2004
2005                 return(NULL);
2006         } else {
2007                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
2008                 MonoPEResourceDataEntry *res;
2009
2010                 res = g_new0 (MonoPEResourceDataEntry, 1);
2011
2012                 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
2013                 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
2014                 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
2015                 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
2016
2017                 return (res);
2018         }
2019 }
2020
2021 /**
2022  * mono_image_lookup_resource:
2023  * @image: the image to look up the resource in
2024  * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
2025  * @lang_id: The language id.
2026  * @name: the resource name to lookup.
2027  *
2028  * Returns: NULL if not found, otherwise a pointer to the in-memory representation
2029  * of the given resource. The caller should free it using g_free () when no longer
2030  * needed.
2031  */
2032 gpointer
2033 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
2034 {
2035         MonoCLIImageInfo *info;
2036         MonoDotNetHeader *header;
2037         MonoPEDatadir *datadir;
2038         MonoPEDirEntry *rsrc;
2039         MonoPEResourceDir *resource_dir;
2040         MonoPEResourceDirEntry *res_entries;
2041         guint32 entries, i;
2042
2043         if(image==NULL) {
2044                 return(NULL);
2045         }
2046
2047         mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
2048
2049         info=image->image_info;
2050         if(info==NULL) {
2051                 return(NULL);
2052         }
2053
2054         header=&info->cli_header;
2055         if(header==NULL) {
2056                 return(NULL);
2057         }
2058
2059         datadir=&header->datadir;
2060         if(datadir==NULL) {
2061                 return(NULL);
2062         }
2063
2064         rsrc=&datadir->pe_resource_table;
2065         if(rsrc==NULL) {
2066                 return(NULL);
2067         }
2068
2069         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
2070         if(resource_dir==NULL) {
2071                 return(NULL);
2072         }
2073
2074         entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
2075         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
2076         
2077         for(i=0; i<entries; i++) {
2078                 MonoPEResourceDirEntry *entry=&res_entries[i];
2079                 gpointer ret;
2080                 
2081                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
2082                                                    name, entry, resource_dir,
2083                                                    0);
2084                 if(ret!=NULL) {
2085                         return(ret);
2086                 }
2087         }
2088
2089         return(NULL);
2090 }
2091
2092 /** 
2093  * mono_image_get_entry_point:
2094  * @image: the image where the entry point will be looked up.
2095  *
2096  * Use this routine to determine the metadata token for method that
2097  * has been flagged as the entry point.
2098  *
2099  * Returns: the token for the entry point method in the image
2100  */
2101 guint32
2102 mono_image_get_entry_point (MonoImage *image)
2103 {
2104         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
2105 }
2106
2107 /**
2108  * mono_image_get_resource:
2109  * @image: the image where the resource will be looked up.
2110  * @offset: The offset to add to the resource
2111  * @size: a pointer to an int where the size of the resource will be stored
2112  *
2113  * This is a low-level routine that fetches a resource from the
2114  * metadata that starts at a given @offset.  The @size parameter is
2115  * filled with the data field as encoded in the metadata.
2116  *
2117  * Returns: the pointer to the resource whose offset is @offset.
2118  */
2119 const char*
2120 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
2121 {
2122         MonoCLIImageInfo *iinfo = image->image_info;
2123         MonoCLIHeader *ch = &iinfo->cli_cli_header;
2124         const char* data;
2125
2126         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
2127                 return NULL;
2128         
2129         data = mono_image_rva_map (image, ch->ch_resources.rva);
2130         if (!data)
2131                 return NULL;
2132         data += offset;
2133         if (size)
2134                 *size = read32 (data);
2135         data += 4;
2136         return data;
2137 }
2138
2139 MonoImage*
2140 mono_image_load_file_for_image (MonoImage *image, int fileidx)
2141 {
2142         char *base_dir, *name;
2143         MonoImage *res;
2144         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
2145         const char *fname;
2146         guint32 fname_id;
2147
2148         if (fileidx < 1 || fileidx > t->rows)
2149                 return NULL;
2150
2151         mono_image_lock (image);
2152         if (image->files && image->files [fileidx - 1]) {
2153                 mono_image_unlock (image);
2154                 return image->files [fileidx - 1];
2155         }
2156         mono_image_unlock (image);
2157
2158         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
2159         fname = mono_metadata_string_heap (image, fname_id);
2160         base_dir = g_path_get_dirname (image->name);
2161         name = g_build_filename (base_dir, fname, NULL);
2162         res = mono_image_open (name, NULL);
2163         if (!res)
2164                 goto done;
2165
2166         mono_image_lock (image);
2167         if (image->files && image->files [fileidx - 1]) {
2168                 MonoImage *old = res;
2169                 res = image->files [fileidx - 1];
2170                 mono_image_unlock (image);
2171                 mono_image_close (old);
2172         } else {
2173                 int i;
2174                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
2175                 res->assembly = image->assembly;
2176                 for (i = 0; i < res->module_count; ++i) {
2177                         if (res->modules [i] && !res->modules [i]->assembly)
2178                                 res->modules [i]->assembly = image->assembly;
2179                 }
2180
2181                 if (!image->files)
2182                         image->files = g_new0 (MonoImage*, t->rows);
2183                 image->files [fileidx - 1] = res;
2184                 mono_image_unlock (image);
2185                 /* vtable fixup can't happen with the image lock held */
2186 #ifdef HOST_WIN32
2187                 if (res->is_module_handle)
2188                         mono_image_fixup_vtable (res);
2189 #endif
2190         }
2191
2192 done:
2193         g_free (name);
2194         g_free (base_dir);
2195         return res;
2196 }
2197
2198 /**
2199  * mono_image_get_strong_name:
2200  * @image: a MonoImage
2201  * @size: a guint32 pointer, or NULL.
2202  *
2203  * If the image has a strong name, and @size is not NULL, the value
2204  * pointed to by size will have the size of the strong name.
2205  *
2206  * Returns: NULL if the image does not have a strong name, or a
2207  * pointer to the public key.
2208  */
2209 const char*
2210 mono_image_get_strong_name (MonoImage *image, guint32 *size)
2211 {
2212         MonoCLIImageInfo *iinfo = image->image_info;
2213         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2214         const char* data;
2215
2216         if (!de->size || !de->rva)
2217                 return NULL;
2218         data = mono_image_rva_map (image, de->rva);
2219         if (!data)
2220                 return NULL;
2221         if (size)
2222                 *size = de->size;
2223         return data;
2224 }
2225
2226 /**
2227  * mono_image_strong_name_position:
2228  * @image: a MonoImage
2229  * @size: a guint32 pointer, or NULL.
2230  *
2231  * If the image has a strong name, and @size is not NULL, the value
2232  * pointed to by size will have the size of the strong name.
2233  *
2234  * Returns: the position within the image file where the strong name
2235  * is stored.
2236  */
2237 guint32
2238 mono_image_strong_name_position (MonoImage *image, guint32 *size)
2239 {
2240         MonoCLIImageInfo *iinfo = image->image_info;
2241         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2242         guint32 pos;
2243
2244         if (size)
2245                 *size = de->size;
2246         if (!de->size || !de->rva)
2247                 return 0;
2248         pos = mono_cli_rva_image_map (image, de->rva);
2249         return pos == INVALID_ADDRESS ? 0 : pos;
2250 }
2251
2252 /**
2253  * mono_image_get_public_key:
2254  * @image: a MonoImage
2255  * @size: a guint32 pointer, or NULL.
2256  *
2257  * This is used to obtain the public key in the @image.
2258  * 
2259  * If the image has a public key, and @size is not NULL, the value
2260  * pointed to by size will have the size of the public key.
2261  * 
2262  * Returns: NULL if the image does not have a public key, or a pointer
2263  * to the public key.
2264  */
2265 const char*
2266 mono_image_get_public_key (MonoImage *image, guint32 *size)
2267 {
2268         const char *pubkey;
2269         guint32 len, tok;
2270
2271         if (image_is_dynamic (image)) {
2272                 if (size)
2273                         *size = ((MonoDynamicImage*)image)->public_key_len;
2274                 return (char*)((MonoDynamicImage*)image)->public_key;
2275         }
2276         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
2277                 return NULL;
2278         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
2279         if (!tok)
2280                 return NULL;
2281         pubkey = mono_metadata_blob_heap (image, tok);
2282         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
2283         if (size)
2284                 *size = len;
2285         return pubkey;
2286 }
2287
2288 /**
2289  * mono_image_get_name:
2290  * @name: a MonoImage
2291  *
2292  * Returns: the name of the assembly.
2293  */
2294 const char*
2295 mono_image_get_name (MonoImage *image)
2296 {
2297         return image->assembly_name;
2298 }
2299
2300 /**
2301  * mono_image_get_filename:
2302  * @image: a MonoImage
2303  *
2304  * Used to get the filename that hold the actual MonoImage
2305  *
2306  * Returns: the filename.
2307  */
2308 const char*
2309 mono_image_get_filename (MonoImage *image)
2310 {
2311         return image->name;
2312 }
2313
2314 const char*
2315 mono_image_get_guid (MonoImage *image)
2316 {
2317         return image->guid;
2318 }
2319
2320 const MonoTableInfo*
2321 mono_image_get_table_info (MonoImage *image, int table_id)
2322 {
2323         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2324                 return NULL;
2325         return &image->tables [table_id];
2326 }
2327
2328 int
2329 mono_image_get_table_rows (MonoImage *image, int table_id)
2330 {
2331         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2332                 return 0;
2333         return image->tables [table_id].rows;
2334 }
2335
2336 int
2337 mono_table_info_get_rows (const MonoTableInfo *table)
2338 {
2339         return table->rows;
2340 }
2341
2342 /**
2343  * mono_image_get_assembly:
2344  * @image: the MonoImage.
2345  *
2346  * Use this routine to get the assembly that owns this image.
2347  *
2348  * Returns: the assembly that holds this image.
2349  */
2350 MonoAssembly* 
2351 mono_image_get_assembly (MonoImage *image)
2352 {
2353         return image->assembly;
2354 }
2355
2356 /**
2357  * mono_image_is_dynamic:
2358  * @image: the MonoImage
2359  *
2360  * Determines if the given image was created dynamically through the
2361  * System.Reflection.Emit API
2362  *
2363  * Returns: TRUE if the image was created dynamically, FALSE if not.
2364  */
2365 gboolean
2366 mono_image_is_dynamic (MonoImage *image)
2367 {
2368         return image_is_dynamic (image);
2369 }
2370
2371 /**
2372  * mono_image_has_authenticode_entry:
2373  * @image: the MonoImage
2374  *
2375  * Use this routine to determine if the image has a Authenticode
2376  * Certificate Table.
2377  *
2378  * Returns: TRUE if the image contains an authenticode entry in the PE
2379  * directory.
2380  */
2381 gboolean
2382 mono_image_has_authenticode_entry (MonoImage *image)
2383 {
2384         MonoCLIImageInfo *iinfo = image->image_info;
2385         MonoDotNetHeader *header = &iinfo->cli_header;
2386         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2387         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2388         return ((de->rva != 0) && (de->size > 8));
2389 }
2390
2391 gpointer
2392 mono_image_alloc (MonoImage *image, guint size)
2393 {
2394         gpointer res;
2395
2396 #ifndef DISABLE_PERFCOUNTERS
2397         mono_perfcounters->loader_bytes += size;
2398 #endif
2399         mono_image_lock (image);
2400         res = mono_mempool_alloc (image->mempool, size);
2401         mono_image_unlock (image);
2402
2403         return res;
2404 }
2405
2406 gpointer
2407 mono_image_alloc0 (MonoImage *image, guint size)
2408 {
2409         gpointer res;
2410
2411 #ifndef DISABLE_PERFCOUNTERS
2412         mono_perfcounters->loader_bytes += size;
2413 #endif
2414         mono_image_lock (image);
2415         res = mono_mempool_alloc0 (image->mempool, size);
2416         mono_image_unlock (image);
2417
2418         return res;
2419 }
2420
2421 char*
2422 mono_image_strdup (MonoImage *image, const char *s)
2423 {
2424         char *res;
2425
2426 #ifndef DISABLE_PERFCOUNTERS
2427         mono_perfcounters->loader_bytes += strlen (s);
2428 #endif
2429         mono_image_lock (image);
2430         res = mono_mempool_strdup (image->mempool, s);
2431         mono_image_unlock (image);
2432
2433         return res;
2434 }
2435
2436 GList*
2437 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2438 {
2439         GList *new_list;
2440         
2441         new_list = mono_image_alloc (image, sizeof (GList));
2442         new_list->data = data;
2443         new_list->prev = list ? list->prev : NULL;
2444     new_list->next = list;
2445
2446     if (new_list->prev)
2447             new_list->prev->next = new_list;
2448     if (list)
2449             list->prev = new_list;
2450
2451         return new_list;
2452 }
2453
2454 GSList*
2455 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2456 {
2457         GSList *new_list;
2458
2459         new_list = mono_image_alloc (image, sizeof (GSList));
2460         new_list->data = data;
2461         new_list->next = NULL;
2462
2463         return g_slist_concat (list, new_list);
2464 }
2465
2466 void
2467 mono_image_lock (MonoImage *image)
2468 {
2469         mono_locks_acquire (&image->lock, ImageDataLock);
2470 }
2471
2472 void
2473 mono_image_unlock (MonoImage *image)
2474 {
2475         mono_locks_release (&image->lock, ImageDataLock);
2476 }
2477
2478
2479 /**
2480  * mono_image_property_lookup:
2481  *
2482  * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2483  *
2484  * LOCKING: Takes the image lock
2485  */
2486 gpointer 
2487 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2488 {
2489         gpointer res;
2490
2491         mono_image_lock (image);
2492         res = mono_property_hash_lookup (image->property_hash, subject, property);
2493         mono_image_unlock (image);
2494
2495         return res;
2496 }
2497
2498 /**
2499  * mono_image_property_insert:
2500  *
2501  * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2502  *
2503  * LOCKING: Takes the image lock
2504  */
2505 void
2506 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2507 {
2508         mono_image_lock (image);
2509         mono_property_hash_insert (image->property_hash, subject, property, value);
2510         mono_image_unlock (image);
2511 }
2512
2513 /**
2514  * mono_image_property_remove:
2515  *
2516  * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2517  *
2518  * LOCKING: Takes the image lock
2519  */
2520 void
2521 mono_image_property_remove (MonoImage *image, gpointer subject)
2522 {
2523         mono_image_lock (image);
2524         mono_property_hash_remove_object (image->property_hash, subject);
2525         mono_image_unlock (image);
2526 }
2527
2528 void
2529 mono_image_append_class_to_reflection_info_set (MonoClass *class)
2530 {
2531         MonoImage *image = class->image;
2532         g_assert (image_is_dynamic (image));
2533         mono_image_lock (image);
2534         image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, class);
2535         mono_image_unlock (image);
2536 }