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