[runtime] Ensure uniqueness of icall wrappers (#3143)
[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         image->ref_count = 1;
1304
1305         image = do_mono_image_load (image, status, TRUE, TRUE);
1306         if (image == NULL)
1307                 return NULL;
1308
1309         return register_image (image);
1310 }
1311
1312 MonoImage *
1313 mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
1314 {
1315         return mono_image_open_from_data_internal (data, data_len, need_copy, status, refonly, FALSE, name);
1316 }
1317
1318 MonoImage *
1319 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1320 {
1321   return mono_image_open_from_data_with_name (data, data_len, need_copy, status, refonly, NULL);
1322 }
1323
1324 MonoImage *
1325 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1326 {
1327         return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1328 }
1329
1330 #ifdef HOST_WIN32
1331 /* fname is not duplicated. */
1332 MonoImage*
1333 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1334 {
1335         MonoImage* image;
1336         MonoCLIImageInfo* iinfo;
1337
1338         image = g_new0 (MonoImage, 1);
1339         image->raw_data = (char*) module_handle;
1340         image->is_module_handle = TRUE;
1341         iinfo = g_new0 (MonoCLIImageInfo, 1);
1342         image->image_info = iinfo;
1343         image->name = fname;
1344         image->ref_count = has_entry_point ? 0 : 1;
1345         image->has_entry_point = has_entry_point;
1346
1347         image = do_mono_image_load (image, status, TRUE, TRUE);
1348         if (image == NULL)
1349                 return NULL;
1350
1351         return register_image (image);
1352 }
1353 #endif
1354
1355 MonoImage *
1356 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1357 {
1358         MonoImage *image;
1359         GHashTable *loaded_images = get_loaded_images_hash (refonly);
1360         char *absfname;
1361         
1362         g_return_val_if_fail (fname != NULL, NULL);
1363         
1364 #ifdef HOST_WIN32
1365         // Win32 path: If we are running with mixed-mode assemblies enabled (ie have loaded mscoree.dll),
1366         // then assemblies need to be loaded with LoadLibrary:
1367         if (!refonly && coree_module_handle) {
1368                 HMODULE module_handle;
1369                 guint16 *fname_utf16;
1370                 DWORD last_error;
1371
1372                 absfname = mono_path_resolve_symlinks (fname);
1373                 fname_utf16 = NULL;
1374
1375                 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1376                 mono_images_lock ();
1377                 image = g_hash_table_lookup (loaded_images, absfname);
1378                 if (image) { // Image already loaded
1379                         g_assert (image->is_module_handle);
1380                         if (image->has_entry_point && image->ref_count == 0) {
1381                                 /* Increment reference count on images loaded outside of the runtime. */
1382                                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1383                                 /* The image is already loaded because _CorDllMain removes images from the hash. */
1384                                 module_handle = LoadLibrary (fname_utf16);
1385                                 g_assert (module_handle == (HMODULE) image->raw_data);
1386                         }
1387                         mono_image_addref (image);
1388                         mono_images_unlock ();
1389                         if (fname_utf16)
1390                                 g_free (fname_utf16);
1391                         g_free (absfname);
1392                         return image;
1393                 }
1394
1395                 // Image not loaded, load it now
1396                 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1397                 module_handle = MonoLoadImage (fname_utf16);
1398                 if (status && module_handle == NULL)
1399                         last_error = GetLastError ();
1400
1401                 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1402                 image = g_hash_table_lookup (loaded_images, absfname);
1403                 if (image)
1404                         mono_image_addref (image);
1405                 mono_images_unlock ();
1406
1407                 g_free (fname_utf16);
1408
1409                 if (module_handle == NULL) {
1410                         g_assert (!image);
1411                         g_free (absfname);
1412                         if (status) {
1413                                 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1414                                         *status = MONO_IMAGE_IMAGE_INVALID;
1415                                 else {
1416                                         if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND)
1417                                                 errno = ENOENT;
1418                                         else
1419                                                 errno = 0;
1420                                 }
1421                         }
1422                         return NULL;
1423                 }
1424
1425                 if (image) {
1426                         g_assert (image->is_module_handle);
1427                         g_assert (image->has_entry_point);
1428                         g_free (absfname);
1429                         return image;
1430                 }
1431
1432                 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1433         }
1434 #endif
1435
1436         absfname = mono_path_canonicalize (fname);
1437
1438         /*
1439          * The easiest solution would be to do all the loading inside the mutex,
1440          * but that would lead to scalability problems. So we let the loading
1441          * happen outside the mutex, and if multiple threads happen to load
1442          * the same image, we discard all but the first copy.
1443          */
1444         mono_images_lock ();
1445         image = (MonoImage *)g_hash_table_lookup (loaded_images, absfname);
1446         g_free (absfname);
1447
1448         if (image) { // Image already loaded
1449                 mono_image_addref (image);
1450                 mono_images_unlock ();
1451                 return image;
1452         }
1453         mono_images_unlock ();
1454
1455         // Image not loaded, load it now
1456         image = do_mono_image_open (fname, status, TRUE, TRUE, refonly, FALSE);
1457         if (image == NULL)
1458                 return NULL;
1459
1460         return register_image (image);
1461 }
1462
1463 /**
1464  * mono_image_open:
1465  * @fname: filename that points to the module we want to open
1466  * @status: An error condition is returned in this field
1467  *
1468  * Returns: An open image of type %MonoImage or NULL on error. 
1469  * The caller holds a temporary reference to the returned image which should be cleared 
1470  * when no longer needed by calling mono_image_close ().
1471  * if NULL, then check the value of @status for details on the error
1472  */
1473 MonoImage *
1474 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1475 {
1476         return mono_image_open_full (fname, status, FALSE);
1477 }
1478
1479 /**
1480  * mono_pe_file_open:
1481  * @fname: filename that points to the module we want to open
1482  * @status: An error condition is returned in this field
1483  *
1484  * Returns: An open image of type %MonoImage or NULL on error.  if
1485  * NULL, then check the value of @status for details on the error.
1486  * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1487  * It's just a PE file loader, used for FileVersionInfo.  It also does
1488  * not use the image cache.
1489  */
1490 MonoImage *
1491 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1492 {
1493         g_return_val_if_fail (fname != NULL, NULL);
1494         
1495         return do_mono_image_open (fname, status, FALSE, TRUE, FALSE, FALSE);
1496 }
1497
1498 /**
1499  * mono_image_open_raw
1500  * @fname: filename that points to the module we want to open
1501  * @status: An error condition is returned in this field
1502  * 
1503  * Returns an image without loading neither pe or cli data.
1504  * 
1505  * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.  
1506  */
1507 MonoImage *
1508 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1509 {
1510         g_return_val_if_fail (fname != NULL, NULL);
1511         
1512         return do_mono_image_open (fname, status, FALSE, FALSE, FALSE, FALSE);
1513 }
1514
1515 /*
1516  * mono_image_open_metadata_only:
1517  *
1518  *   Open an image which contains metadata only without a PE header.
1519  */
1520 MonoImage *
1521 mono_image_open_metadata_only (const char *fname, MonoImageOpenStatus *status)
1522 {
1523         return do_mono_image_open (fname, status, TRUE, TRUE, FALSE, TRUE);
1524 }
1525
1526 void
1527 mono_image_fixup_vtable (MonoImage *image)
1528 {
1529 #ifdef HOST_WIN32
1530         MonoCLIImageInfo *iinfo;
1531         MonoPEDirEntry *de;
1532         MonoVTableFixup *vtfixup;
1533         int count;
1534         gpointer slot;
1535         guint16 slot_type;
1536         int slot_count;
1537
1538         g_assert (image->is_module_handle);
1539
1540         iinfo = image->image_info;
1541         de = &iinfo->cli_cli_header.ch_vtable_fixups;
1542         if (!de->rva || !de->size)
1543                 return;
1544         vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1545         if (!vtfixup)
1546                 return;
1547         
1548         count = de->size / sizeof (MonoVTableFixup);
1549         while (count--) {
1550                 if (!vtfixup->rva || !vtfixup->count)
1551                         continue;
1552
1553                 slot = mono_image_rva_map (image, vtfixup->rva);
1554                 g_assert (slot);
1555                 slot_type = vtfixup->type;
1556                 slot_count = vtfixup->count;
1557                 if (slot_type & VTFIXUP_TYPE_32BIT)
1558                         while (slot_count--) {
1559                                 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1560                                 slot = ((guint32*) slot) + 1;
1561                         }
1562                 else if (slot_type & VTFIXUP_TYPE_64BIT)
1563                         while (slot_count--) {
1564                                 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1565                                 slot = ((guint32*) slot) + 1;
1566                         }
1567                 else
1568                         g_assert_not_reached();
1569
1570                 vtfixup++;
1571         }
1572 #else
1573         g_assert_not_reached();
1574 #endif
1575 }
1576
1577 static void
1578 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1579 {
1580         g_hash_table_destroy ((GHashTable*)val);
1581 }
1582
1583 /*
1584 static void
1585 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1586 {
1587         mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1588 }
1589 */
1590
1591 static void
1592 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1593 {
1594         g_slist_free ((GSList*)val);
1595 }
1596
1597 /**
1598  * mono_image_addref:
1599  * @image: The image file we wish to add a reference to
1600  *
1601  *  Increases the reference count of an image.
1602  */
1603 void
1604 mono_image_addref (MonoImage *image)
1605 {
1606         InterlockedIncrement (&image->ref_count);
1607 }       
1608
1609 void
1610 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1611 {
1612         stream->alloc_size = stream->index = stream->offset = 0;
1613         g_free (stream->data);
1614         stream->data = NULL;
1615         if (stream->hash) {
1616                 g_hash_table_destroy (stream->hash);
1617                 stream->hash = NULL;
1618         }
1619 }
1620
1621 static inline void
1622 free_hash (GHashTable *hash)
1623 {
1624         if (hash)
1625                 g_hash_table_destroy (hash);
1626 }
1627
1628 void
1629 mono_wrapper_caches_free (MonoWrapperCaches *cache)
1630 {
1631         free_hash (cache->delegate_invoke_cache);
1632         free_hash (cache->delegate_begin_invoke_cache);
1633         free_hash (cache->delegate_end_invoke_cache);
1634         free_hash (cache->runtime_invoke_cache);
1635         free_hash (cache->runtime_invoke_vtype_cache);
1636         
1637         free_hash (cache->delegate_abstract_invoke_cache);
1638
1639         free_hash (cache->runtime_invoke_direct_cache);
1640         free_hash (cache->managed_wrapper_cache);
1641
1642         free_hash (cache->native_wrapper_cache);
1643         free_hash (cache->native_wrapper_aot_cache);
1644         free_hash (cache->native_wrapper_check_cache);
1645         free_hash (cache->native_wrapper_aot_check_cache);
1646
1647         free_hash (cache->native_func_wrapper_aot_cache);
1648         free_hash (cache->remoting_invoke_cache);
1649         free_hash (cache->synchronized_cache);
1650         free_hash (cache->unbox_wrapper_cache);
1651         free_hash (cache->cominterop_invoke_cache);
1652         free_hash (cache->cominterop_wrapper_cache);
1653         free_hash (cache->thunk_invoke_cache);
1654 }
1655
1656 /*
1657  * Returns whether mono_image_close_finish() must be called as well.
1658  * We must unload images in two steps because clearing the domain in
1659  * SGen requires the class metadata to be intact, but we need to free
1660  * the mono_g_hash_tables in case a collection occurs during domain
1661  * unloading and the roots would trip up the GC.
1662  */
1663 gboolean
1664 mono_image_close_except_pools (MonoImage *image)
1665 {
1666         MonoImage *image2;
1667         GHashTable *loaded_images, *loaded_images_by_name;
1668         int i;
1669
1670         g_return_val_if_fail (image != NULL, FALSE);
1671
1672         /*
1673          * Atomically decrement the refcount and remove ourselves from the hash tables, so
1674          * register_image () can't grab an image which is being closed.
1675          */
1676         mono_images_lock ();
1677
1678         if (InterlockedDecrement (&image->ref_count) > 0) {
1679                 mono_images_unlock ();
1680                 return FALSE;
1681         }
1682
1683         loaded_images         = get_loaded_images_hash (image->ref_only);
1684         loaded_images_by_name = get_loaded_images_by_name_hash (image->ref_only);
1685         image2 = (MonoImage *)g_hash_table_lookup (loaded_images, image->name);
1686         if (image == image2) {
1687                 /* This is not true if we are called from mono_image_open () */
1688                 g_hash_table_remove (loaded_images, image->name);
1689         }
1690         if (image->assembly_name && (g_hash_table_lookup (loaded_images_by_name, image->assembly_name) == image))
1691                 g_hash_table_remove (loaded_images_by_name, (char *) image->assembly_name);     
1692
1693         mono_images_unlock ();
1694
1695 #ifdef HOST_WIN32
1696         if (image->is_module_handle && image->has_entry_point) {
1697                 mono_images_lock ();
1698                 if (image->ref_count == 0) {
1699                         /* Image will be closed by _CorDllMain. */
1700                         FreeLibrary ((HMODULE) image->raw_data);
1701                         mono_images_unlock ();
1702                         return FALSE;
1703                 }
1704                 mono_images_unlock ();
1705         }
1706 #endif
1707
1708         mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1709
1710         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1711
1712         mono_image_invoke_unload_hook (image);
1713
1714         mono_metadata_clean_for_image (image);
1715
1716         /*
1717          * The caches inside a MonoImage might refer to metadata which is stored in referenced 
1718          * assemblies, so we can't release these references in mono_assembly_close () since the
1719          * MonoImage might outlive its associated MonoAssembly.
1720          */
1721         if (image->references && !image_is_dynamic (image)) {
1722                 for (i = 0; i < image->nreferences; i++) {
1723                         if (image->references [i] && image->references [i] != REFERENCE_MISSING) {
1724                                 if (!mono_assembly_close_except_image_pools (image->references [i]))
1725                                         image->references [i] = NULL;
1726                         }
1727                 }
1728         } else {
1729                 if (image->references) {
1730                         g_free (image->references);
1731                         image->references = NULL;
1732                 }
1733         }
1734
1735 #ifdef HOST_WIN32
1736         mono_images_lock ();
1737         if (image->is_module_handle && !image->has_entry_point)
1738                 FreeLibrary ((HMODULE) image->raw_data);
1739         mono_images_unlock ();
1740 #endif
1741
1742         if (image->raw_buffer_used) {
1743                 if (image->raw_data != NULL) {
1744 #ifndef HOST_WIN32
1745                         if (image->fileio_used)
1746                                 mono_file_unmap_fileio (image->raw_data, image->raw_data_handle);
1747                         else
1748 #endif
1749                                 mono_file_unmap (image->raw_data, image->raw_data_handle);
1750                 }
1751         }
1752         
1753         if (image->raw_data_allocated) {
1754                 /* FIXME: do we need this? (image is disposed anyway) */
1755                 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1756                 MonoCLIImageInfo *ii = (MonoCLIImageInfo *)image->image_info;
1757
1758                 if ((image->raw_metadata > image->raw_data) &&
1759                         (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1760                         image->raw_metadata = NULL;
1761
1762                 for (i = 0; i < ii->cli_section_count; i++)
1763                         if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1764                                 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1765                                 ii->cli_sections [i] = NULL;
1766
1767                 g_free (image->raw_data);
1768         }
1769
1770         if (debug_assembly_unload) {
1771                 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1772         } else {
1773                 g_free (image->name);
1774                 g_free (image->guid);
1775                 g_free (image->version);
1776                 g_free (image->files);
1777         }
1778
1779         if (image->method_cache)
1780                 g_hash_table_destroy (image->method_cache);
1781         if (image->methodref_cache)
1782                 g_hash_table_destroy (image->methodref_cache);
1783         mono_internal_hash_table_destroy (&image->class_cache);
1784         mono_conc_hashtable_destroy (image->field_cache);
1785         if (image->array_cache) {
1786                 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1787                 g_hash_table_destroy (image->array_cache);
1788         }
1789         if (image->szarray_cache)
1790                 g_hash_table_destroy (image->szarray_cache);
1791         if (image->ptr_cache)
1792                 g_hash_table_destroy (image->ptr_cache);
1793         if (image->name_cache) {
1794                 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1795                 g_hash_table_destroy (image->name_cache);
1796         }
1797
1798         free_hash (image->delegate_bound_static_invoke_cache);
1799         free_hash (image->runtime_invoke_vcall_cache);
1800         free_hash (image->ldfld_wrapper_cache);
1801         free_hash (image->ldflda_wrapper_cache);
1802         free_hash (image->stfld_wrapper_cache);
1803         free_hash (image->isinst_cache);
1804         free_hash (image->castclass_cache);
1805         free_hash (image->icall_wrapper_cache);
1806         free_hash (image->proxy_isinst_cache);
1807         free_hash (image->var_cache_slow);
1808         free_hash (image->mvar_cache_slow);
1809         free_hash (image->var_cache_constrained);
1810         free_hash (image->mvar_cache_constrained);
1811         free_hash (image->wrapper_param_names);
1812         free_hash (image->pinvoke_scopes);
1813         free_hash (image->pinvoke_scope_filenames);
1814         free_hash (image->native_func_wrapper_cache);
1815         free_hash (image->typespec_cache);
1816
1817         mono_wrapper_caches_free (&image->wrapper_caches);
1818
1819         for (i = 0; i < image->gshared_types_len; ++i)
1820                 free_hash (image->gshared_types [i]);
1821         g_free (image->gshared_types);
1822
1823         /* The ownership of signatures is not well defined */
1824         g_hash_table_destroy (image->memberref_signatures);
1825         g_hash_table_destroy (image->helper_signatures);
1826         g_hash_table_destroy (image->method_signatures);
1827
1828         if (image->rgctx_template_hash)
1829                 g_hash_table_destroy (image->rgctx_template_hash);
1830
1831         if (image->property_hash)
1832                 mono_property_hash_destroy (image->property_hash);
1833
1834         /*
1835         reflection_info_unregister_classes is only required by dynamic images, which will not be properly
1836         cleared during shutdown as we don't perform regular appdomain unload for the root one.
1837         */
1838         g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ());
1839         image->reflection_info_unregister_classes = NULL;
1840
1841         if (image->interface_bitset) {
1842                 mono_unload_interface_ids (image->interface_bitset);
1843                 mono_bitset_free (image->interface_bitset);
1844         }
1845         if (image->image_info){
1846                 MonoCLIImageInfo *ii = (MonoCLIImageInfo *)image->image_info;
1847
1848                 if (ii->cli_section_tables)
1849                         g_free (ii->cli_section_tables);
1850                 if (ii->cli_sections)
1851                         g_free (ii->cli_sections);
1852                 g_free (image->image_info);
1853         }
1854
1855         for (i = 0; i < image->module_count; ++i) {
1856                 if (image->modules [i]) {
1857                         if (!mono_image_close_except_pools (image->modules [i]))
1858                                 image->modules [i] = NULL;
1859                 }
1860         }
1861         if (image->modules_loaded)
1862                 g_free (image->modules_loaded);
1863
1864         mono_os_mutex_destroy (&image->szarray_cache_lock);
1865         mono_os_mutex_destroy (&image->lock);
1866
1867         /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1868         if (image_is_dynamic (image)) {
1869                 /* Dynamic images are GC_MALLOCed */
1870                 g_free ((char*)image->module_name);
1871                 mono_dynamic_image_free ((MonoDynamicImage*)image);
1872         }
1873
1874         mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1875
1876         return TRUE;
1877 }
1878
1879 void
1880 mono_image_close_finish (MonoImage *image)
1881 {
1882         int i;
1883
1884         if (image->references && !image_is_dynamic (image)) {
1885                 for (i = 0; i < image->nreferences; i++) {
1886                         if (image->references [i] && image->references [i] != REFERENCE_MISSING)
1887                                 mono_assembly_close_finish (image->references [i]);
1888                 }
1889
1890                 g_free (image->references);
1891                 image->references = NULL;
1892         }
1893
1894         for (i = 0; i < image->module_count; ++i) {
1895                 if (image->modules [i])
1896                         mono_image_close_finish (image->modules [i]);
1897         }
1898         if (image->modules)
1899                 g_free (image->modules);
1900
1901 #ifndef DISABLE_PERFCOUNTERS
1902         mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1903 #endif
1904
1905         if (!image_is_dynamic (image)) {
1906                 if (debug_assembly_unload)
1907                         mono_mempool_invalidate (image->mempool);
1908                 else {
1909                         mono_mempool_destroy (image->mempool);
1910                         g_free (image);
1911                 }
1912         } else {
1913                 if (debug_assembly_unload)
1914                         mono_mempool_invalidate (image->mempool);
1915                 else {
1916                         mono_mempool_destroy (image->mempool);
1917                         mono_dynamic_image_free_image ((MonoDynamicImage*)image);
1918                 }
1919         }
1920 }
1921
1922 /**
1923  * mono_image_close:
1924  * @image: The image file we wish to close
1925  *
1926  * Closes an image file, deallocates all memory consumed and
1927  * unmaps all possible sections of the file
1928  */
1929 void
1930 mono_image_close (MonoImage *image)
1931 {
1932         if (mono_image_close_except_pools (image))
1933                 mono_image_close_finish (image);
1934 }
1935
1936 /** 
1937  * mono_image_strerror:
1938  * @status: an code indicating the result from a recent operation
1939  *
1940  * Returns: a string describing the error
1941  */
1942 const char *
1943 mono_image_strerror (MonoImageOpenStatus status)
1944 {
1945         switch (status){
1946         case MONO_IMAGE_OK:
1947                 return "success";
1948         case MONO_IMAGE_ERROR_ERRNO:
1949                 return strerror (errno);
1950         case MONO_IMAGE_IMAGE_INVALID:
1951                 return "File does not contain a valid CIL image";
1952         case MONO_IMAGE_MISSING_ASSEMBLYREF:
1953                 return "An assembly was referenced, but could not be found";
1954         }
1955         return "Internal error";
1956 }
1957
1958 static gpointer
1959 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1960                                guint32 lang_id, gunichar2 *name,
1961                                MonoPEResourceDirEntry *entry,
1962                                MonoPEResourceDir *root, guint32 level)
1963 {
1964         gboolean is_string, is_dir;
1965         guint32 name_offset, dir_offset;
1966
1967         /* Level 0 holds a directory entry for each type of resource
1968          * (identified by ID or name).
1969          *
1970          * Level 1 holds a directory entry for each named resource
1971          * item, and each "anonymous" item of a particular type of
1972          * resource.
1973          *
1974          * Level 2 holds a directory entry for each language pointing to
1975          * the actual data.
1976          */
1977         is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1978         name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1979
1980         is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1981         dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1982
1983         if(level==0) {
1984                 if (is_string)
1985                         return NULL;
1986         } else if (level==1) {
1987                 if (res_id != name_offset)
1988                         return NULL;
1989 #if 0
1990                 if(name!=NULL &&
1991                    is_string==TRUE && name!=lookup (name_offset)) {
1992                         return(NULL);
1993                 }
1994 #endif
1995         } else if (level==2) {
1996                 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1997                         return NULL;
1998         } else {
1999                 g_assert_not_reached ();
2000         }
2001
2002         if(is_dir==TRUE) {
2003                 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
2004                 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
2005                 guint32 entries, i;
2006
2007                 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
2008
2009                 for(i=0; i<entries; i++) {
2010                         MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
2011                         gpointer ret;
2012                         
2013                         ret=mono_image_walk_resource_tree (info, res_id,
2014                                                            lang_id, name,
2015                                                            sub_entry, root,
2016                                                            level+1);
2017                         if(ret!=NULL) {
2018                                 return(ret);
2019                         }
2020                 }
2021
2022                 return(NULL);
2023         } else {
2024                 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
2025                 MonoPEResourceDataEntry *res;
2026
2027                 res = g_new0 (MonoPEResourceDataEntry, 1);
2028
2029                 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
2030                 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
2031                 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
2032                 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
2033
2034                 return (res);
2035         }
2036 }
2037
2038 /**
2039  * mono_image_lookup_resource:
2040  * @image: the image to look up the resource in
2041  * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
2042  * @lang_id: The language id.
2043  * @name: the resource name to lookup.
2044  *
2045  * Returns: NULL if not found, otherwise a pointer to the in-memory representation
2046  * of the given resource. The caller should free it using g_free () when no longer
2047  * needed.
2048  */
2049 gpointer
2050 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
2051 {
2052         MonoCLIImageInfo *info;
2053         MonoDotNetHeader *header;
2054         MonoPEDatadir *datadir;
2055         MonoPEDirEntry *rsrc;
2056         MonoPEResourceDir *resource_dir;
2057         MonoPEResourceDirEntry *res_entries;
2058         guint32 entries, i;
2059
2060         if(image==NULL) {
2061                 return(NULL);
2062         }
2063
2064         mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
2065
2066         info = (MonoCLIImageInfo *)image->image_info;
2067         if(info==NULL) {
2068                 return(NULL);
2069         }
2070
2071         header=&info->cli_header;
2072         if(header==NULL) {
2073                 return(NULL);
2074         }
2075
2076         datadir=&header->datadir;
2077         if(datadir==NULL) {
2078                 return(NULL);
2079         }
2080
2081         rsrc=&datadir->pe_resource_table;
2082         if(rsrc==NULL) {
2083                 return(NULL);
2084         }
2085
2086         resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
2087         if(resource_dir==NULL) {
2088                 return(NULL);
2089         }
2090
2091         entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
2092         res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
2093         
2094         for(i=0; i<entries; i++) {
2095                 MonoPEResourceDirEntry *entry=&res_entries[i];
2096                 gpointer ret;
2097                 
2098                 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
2099                                                    name, entry, resource_dir,
2100                                                    0);
2101                 if(ret!=NULL) {
2102                         return(ret);
2103                 }
2104         }
2105
2106         return(NULL);
2107 }
2108
2109 /** 
2110  * mono_image_get_entry_point:
2111  * @image: the image where the entry point will be looked up.
2112  *
2113  * Use this routine to determine the metadata token for method that
2114  * has been flagged as the entry point.
2115  *
2116  * Returns: the token for the entry point method in the image
2117  */
2118 guint32
2119 mono_image_get_entry_point (MonoImage *image)
2120 {
2121         return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
2122 }
2123
2124 /**
2125  * mono_image_get_resource:
2126  * @image: the image where the resource will be looked up.
2127  * @offset: The offset to add to the resource
2128  * @size: a pointer to an int where the size of the resource will be stored
2129  *
2130  * This is a low-level routine that fetches a resource from the
2131  * metadata that starts at a given @offset.  The @size parameter is
2132  * filled with the data field as encoded in the metadata.
2133  *
2134  * Returns: the pointer to the resource whose offset is @offset.
2135  */
2136 const char*
2137 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
2138 {
2139         MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info;
2140         MonoCLIHeader *ch = &iinfo->cli_cli_header;
2141         const char* data;
2142
2143         if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
2144                 return NULL;
2145         
2146         data = mono_image_rva_map (image, ch->ch_resources.rva);
2147         if (!data)
2148                 return NULL;
2149         data += offset;
2150         if (size)
2151                 *size = read32 (data);
2152         data += 4;
2153         return data;
2154 }
2155
2156 MonoImage*
2157 mono_image_load_file_for_image (MonoImage *image, int fileidx)
2158 {
2159         char *base_dir, *name;
2160         MonoImage *res;
2161         MonoTableInfo  *t = &image->tables [MONO_TABLE_FILE];
2162         const char *fname;
2163         guint32 fname_id;
2164
2165         if (fileidx < 1 || fileidx > t->rows)
2166                 return NULL;
2167
2168         mono_image_lock (image);
2169         if (image->files && image->files [fileidx - 1]) {
2170                 mono_image_unlock (image);
2171                 return image->files [fileidx - 1];
2172         }
2173         mono_image_unlock (image);
2174
2175         fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
2176         fname = mono_metadata_string_heap (image, fname_id);
2177         base_dir = g_path_get_dirname (image->name);
2178         name = g_build_filename (base_dir, fname, NULL);
2179         res = mono_image_open (name, NULL);
2180         if (!res)
2181                 goto done;
2182
2183         mono_image_lock (image);
2184         if (image->files && image->files [fileidx - 1]) {
2185                 MonoImage *old = res;
2186                 res = image->files [fileidx - 1];
2187                 mono_image_unlock (image);
2188                 mono_image_close (old);
2189         } else {
2190                 int i;
2191                 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
2192                 res->assembly = image->assembly;
2193                 for (i = 0; i < res->module_count; ++i) {
2194                         if (res->modules [i] && !res->modules [i]->assembly)
2195                                 res->modules [i]->assembly = image->assembly;
2196                 }
2197
2198                 if (!image->files)
2199                         image->files = g_new0 (MonoImage*, t->rows);
2200                 image->files [fileidx - 1] = res;
2201                 mono_image_unlock (image);
2202                 /* vtable fixup can't happen with the image lock held */
2203 #ifdef HOST_WIN32
2204                 if (res->is_module_handle)
2205                         mono_image_fixup_vtable (res);
2206 #endif
2207         }
2208
2209 done:
2210         g_free (name);
2211         g_free (base_dir);
2212         return res;
2213 }
2214
2215 /**
2216  * mono_image_get_strong_name:
2217  * @image: a MonoImage
2218  * @size: a guint32 pointer, or NULL.
2219  *
2220  * If the image has a strong name, and @size is not NULL, the value
2221  * pointed to by size will have the size of the strong name.
2222  *
2223  * Returns: NULL if the image does not have a strong name, or a
2224  * pointer to the public key.
2225  */
2226 const char*
2227 mono_image_get_strong_name (MonoImage *image, guint32 *size)
2228 {
2229         MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info;
2230         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2231         const char* data;
2232
2233         if (!de->size || !de->rva)
2234                 return NULL;
2235         data = mono_image_rva_map (image, de->rva);
2236         if (!data)
2237                 return NULL;
2238         if (size)
2239                 *size = de->size;
2240         return data;
2241 }
2242
2243 /**
2244  * mono_image_strong_name_position:
2245  * @image: a MonoImage
2246  * @size: a guint32 pointer, or NULL.
2247  *
2248  * If the image has a strong name, and @size is not NULL, the value
2249  * pointed to by size will have the size of the strong name.
2250  *
2251  * Returns: the position within the image file where the strong name
2252  * is stored.
2253  */
2254 guint32
2255 mono_image_strong_name_position (MonoImage *image, guint32 *size)
2256 {
2257         MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info;
2258         MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2259         guint32 pos;
2260
2261         if (size)
2262                 *size = de->size;
2263         if (!de->size || !de->rva)
2264                 return 0;
2265         pos = mono_cli_rva_image_map (image, de->rva);
2266         return pos == INVALID_ADDRESS ? 0 : pos;
2267 }
2268
2269 /**
2270  * mono_image_get_public_key:
2271  * @image: a MonoImage
2272  * @size: a guint32 pointer, or NULL.
2273  *
2274  * This is used to obtain the public key in the @image.
2275  * 
2276  * If the image has a public key, and @size is not NULL, the value
2277  * pointed to by size will have the size of the public key.
2278  * 
2279  * Returns: NULL if the image does not have a public key, or a pointer
2280  * to the public key.
2281  */
2282 const char*
2283 mono_image_get_public_key (MonoImage *image, guint32 *size)
2284 {
2285         const char *pubkey;
2286         guint32 len, tok;
2287
2288         if (image_is_dynamic (image)) {
2289                 if (size)
2290                         *size = ((MonoDynamicImage*)image)->public_key_len;
2291                 return (char*)((MonoDynamicImage*)image)->public_key;
2292         }
2293         if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
2294                 return NULL;
2295         tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
2296         if (!tok)
2297                 return NULL;
2298         pubkey = mono_metadata_blob_heap (image, tok);
2299         len = mono_metadata_decode_blob_size (pubkey, &pubkey);
2300         if (size)
2301                 *size = len;
2302         return pubkey;
2303 }
2304
2305 /**
2306  * mono_image_get_name:
2307  * @name: a MonoImage
2308  *
2309  * Returns: the name of the assembly.
2310  */
2311 const char*
2312 mono_image_get_name (MonoImage *image)
2313 {
2314         return image->assembly_name;
2315 }
2316
2317 /**
2318  * mono_image_get_filename:
2319  * @image: a MonoImage
2320  *
2321  * Used to get the filename that hold the actual MonoImage
2322  *
2323  * Returns: the filename.
2324  */
2325 const char*
2326 mono_image_get_filename (MonoImage *image)
2327 {
2328         return image->name;
2329 }
2330
2331 const char*
2332 mono_image_get_guid (MonoImage *image)
2333 {
2334         return image->guid;
2335 }
2336
2337 const MonoTableInfo*
2338 mono_image_get_table_info (MonoImage *image, int table_id)
2339 {
2340         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2341                 return NULL;
2342         return &image->tables [table_id];
2343 }
2344
2345 int
2346 mono_image_get_table_rows (MonoImage *image, int table_id)
2347 {
2348         if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2349                 return 0;
2350         return image->tables [table_id].rows;
2351 }
2352
2353 int
2354 mono_table_info_get_rows (const MonoTableInfo *table)
2355 {
2356         return table->rows;
2357 }
2358
2359 /**
2360  * mono_image_get_assembly:
2361  * @image: the MonoImage.
2362  *
2363  * Use this routine to get the assembly that owns this image.
2364  *
2365  * Returns: the assembly that holds this image.
2366  */
2367 MonoAssembly* 
2368 mono_image_get_assembly (MonoImage *image)
2369 {
2370         return image->assembly;
2371 }
2372
2373 /**
2374  * mono_image_is_dynamic:
2375  * @image: the MonoImage
2376  *
2377  * Determines if the given image was created dynamically through the
2378  * System.Reflection.Emit API
2379  *
2380  * Returns: TRUE if the image was created dynamically, FALSE if not.
2381  */
2382 gboolean
2383 mono_image_is_dynamic (MonoImage *image)
2384 {
2385         return image_is_dynamic (image);
2386 }
2387
2388 /**
2389  * mono_image_has_authenticode_entry:
2390  * @image: the MonoImage
2391  *
2392  * Use this routine to determine if the image has a Authenticode
2393  * Certificate Table.
2394  *
2395  * Returns: TRUE if the image contains an authenticode entry in the PE
2396  * directory.
2397  */
2398 gboolean
2399 mono_image_has_authenticode_entry (MonoImage *image)
2400 {
2401         MonoCLIImageInfo *iinfo = (MonoCLIImageInfo *)image->image_info;
2402         MonoDotNetHeader *header = &iinfo->cli_header;
2403         MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2404         // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2405         return ((de->rva != 0) && (de->size > 8));
2406 }
2407
2408 gpointer
2409 mono_image_alloc (MonoImage *image, guint size)
2410 {
2411         gpointer res;
2412
2413 #ifndef DISABLE_PERFCOUNTERS
2414         mono_perfcounters->loader_bytes += size;
2415 #endif
2416         mono_image_lock (image);
2417         res = mono_mempool_alloc (image->mempool, size);
2418         mono_image_unlock (image);
2419
2420         return res;
2421 }
2422
2423 gpointer
2424 mono_image_alloc0 (MonoImage *image, guint size)
2425 {
2426         gpointer res;
2427
2428 #ifndef DISABLE_PERFCOUNTERS
2429         mono_perfcounters->loader_bytes += size;
2430 #endif
2431         mono_image_lock (image);
2432         res = mono_mempool_alloc0 (image->mempool, size);
2433         mono_image_unlock (image);
2434
2435         return res;
2436 }
2437
2438 char*
2439 mono_image_strdup (MonoImage *image, const char *s)
2440 {
2441         char *res;
2442
2443 #ifndef DISABLE_PERFCOUNTERS
2444         mono_perfcounters->loader_bytes += strlen (s);
2445 #endif
2446         mono_image_lock (image);
2447         res = mono_mempool_strdup (image->mempool, s);
2448         mono_image_unlock (image);
2449
2450         return res;
2451 }
2452
2453 GList*
2454 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2455 {
2456         GList *new_list;
2457         
2458         new_list = (GList *)mono_image_alloc (image, sizeof (GList));
2459         new_list->data = data;
2460         new_list->prev = list ? list->prev : NULL;
2461     new_list->next = list;
2462
2463     if (new_list->prev)
2464             new_list->prev->next = new_list;
2465     if (list)
2466             list->prev = new_list;
2467
2468         return new_list;
2469 }
2470
2471 GSList*
2472 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2473 {
2474         GSList *new_list;
2475
2476         new_list = (GSList *)mono_image_alloc (image, sizeof (GSList));
2477         new_list->data = data;
2478         new_list->next = NULL;
2479
2480         return g_slist_concat (list, new_list);
2481 }
2482
2483 void
2484 mono_image_lock (MonoImage *image)
2485 {
2486         mono_locks_os_acquire (&image->lock, ImageDataLock);
2487 }
2488
2489 void
2490 mono_image_unlock (MonoImage *image)
2491 {
2492         mono_locks_os_release (&image->lock, ImageDataLock);
2493 }
2494
2495
2496 /**
2497  * mono_image_property_lookup:
2498  *
2499  * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2500  *
2501  * LOCKING: Takes the image lock
2502  */
2503 gpointer 
2504 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2505 {
2506         gpointer res;
2507
2508         mono_image_lock (image);
2509         res = mono_property_hash_lookup (image->property_hash, subject, property);
2510         mono_image_unlock (image);
2511
2512         return res;
2513 }
2514
2515 /**
2516  * mono_image_property_insert:
2517  *
2518  * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2519  *
2520  * LOCKING: Takes the image lock
2521  */
2522 void
2523 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2524 {
2525         mono_image_lock (image);
2526         mono_property_hash_insert (image->property_hash, subject, property, value);
2527         mono_image_unlock (image);
2528 }
2529
2530 /**
2531  * mono_image_property_remove:
2532  *
2533  * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2534  *
2535  * LOCKING: Takes the image lock
2536  */
2537 void
2538 mono_image_property_remove (MonoImage *image, gpointer subject)
2539 {
2540         mono_image_lock (image);
2541         mono_property_hash_remove_object (image->property_hash, subject);
2542         mono_image_unlock (image);
2543 }
2544
2545 void
2546 mono_image_append_class_to_reflection_info_set (MonoClass *klass)
2547 {
2548         MonoImage *image = klass->image;
2549         g_assert (image_is_dynamic (image));
2550         mono_image_lock (image);
2551         image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, klass);
2552         mono_image_unlock (image);
2553 }
2554
2555 // 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.
2556
2557 /**
2558  * mono_find_image_owner:
2559  *
2560  * Find the image, if any, which a given pointer is located in the memory of.
2561  */
2562 MonoImage *
2563 mono_find_image_owner (void *ptr)
2564 {
2565         mono_images_lock ();
2566
2567         MonoImage *owner = NULL;
2568
2569         // Iterate over both by-path image hashes
2570         const int hash_candidates[] = {IMAGES_HASH_PATH, IMAGES_HASH_PATH_REFONLY};
2571         int hash_idx;
2572         for (hash_idx = 0; !owner && hash_idx < G_N_ELEMENTS (hash_candidates); hash_idx++)
2573         {
2574                 GHashTable *target = loaded_images_hashes [hash_candidates [hash_idx]];
2575                 GHashTableIter iter;
2576                 MonoImage *image;
2577
2578                 // Iterate over images within a hash
2579                 g_hash_table_iter_init (&iter, target);
2580                 while (!owner && g_hash_table_iter_next(&iter, NULL, (gpointer *)&image))
2581                 {
2582                         mono_image_lock (image);
2583                         if (mono_mempool_contains_addr (image->mempool, ptr))
2584                                 owner = image;
2585                         mono_image_unlock (image);
2586                 }
2587         }
2588
2589         mono_images_unlock ();
2590
2591         return owner;
2592 }