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