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