2 * image.c: Routines for manipulating an image stored in an
3 * extended PE/COFF file.
6 * Miguel de Icaza (miguel@ximian.com)
7 * Paolo Molaro (lupus@ximian.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
21 #include "mono-endian.h"
22 #include "tabledefs.h"
23 #include "tokentype.h"
24 #include "metadata-internals.h"
25 #include "profiler-private.h"
29 #include <mono/io-layer/io-layer.h>
30 #include <mono/utils/mono-logger-internal.h>
31 #include <mono/utils/mono-path.h>
32 #include <mono/utils/mono-mmap.h>
33 #include <mono/utils/mono-io-portability.h>
34 #include <mono/utils/atomic.h>
35 #include <mono/metadata/class-internals.h>
36 #include <mono/metadata/assembly.h>
37 #include <mono/metadata/object-internals.h>
38 #include <mono/metadata/security-core-clr.h>
39 #include <mono/metadata/verify-internals.h>
40 #include <mono/metadata/verify.h>
41 #include <sys/types.h>
47 #define INVALID_ADDRESS 0xffffffff
50 * Keeps track of the various assemblies loaded
52 static GHashTable *loaded_images_hash;
53 static GHashTable *loaded_images_refonly_hash;
55 static gboolean debug_assembly_unload = FALSE;
57 #define mono_images_lock() if (mutex_inited) mono_mutex_lock (&images_mutex)
58 #define mono_images_unlock() if (mutex_inited) mono_mutex_unlock (&images_mutex)
59 static gboolean mutex_inited;
60 static mono_mutex_t images_mutex;
62 typedef struct ImageUnloadHook ImageUnloadHook;
63 struct ImageUnloadHook {
64 MonoImageUnloadFunc func;
68 GSList *image_unload_hooks;
71 mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
73 ImageUnloadHook *hook;
75 g_return_if_fail (func != NULL);
77 hook = g_new0 (ImageUnloadHook, 1);
79 hook->user_data = user_data;
80 image_unload_hooks = g_slist_prepend (image_unload_hooks, hook);
84 mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
87 ImageUnloadHook *hook;
89 for (l = image_unload_hooks; l; l = l->next) {
92 if (hook->func == func && hook->user_data == user_data) {
94 image_unload_hooks = g_slist_delete_link (image_unload_hooks, l);
101 mono_image_invoke_unload_hook (MonoImage *image)
104 ImageUnloadHook *hook;
106 for (l = image_unload_hooks; l; l = l->next) {
109 hook->func (image, hook->user_data);
113 /* returns offset relative to image->raw_data */
115 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
117 MonoCLIImageInfo *iinfo = image->image_info;
118 const int top = iinfo->cli_section_count;
119 MonoSectionTable *tables = iinfo->cli_section_tables;
122 for (i = 0; i < top; i++){
123 if ((addr >= tables->st_virtual_address) &&
124 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
126 if (image->is_module_handle)
129 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
133 return INVALID_ADDRESS;
137 * mono_images_rva_map:
138 * @image: a MonoImage
139 * @addr: relative virtual address (RVA)
141 * This is a low-level routine used by the runtime to map relative
142 * virtual address (RVA) into their location in memory.
144 * Returns: the address in memory for the given RVA, or NULL if the
145 * RVA is not valid for this image.
148 mono_image_rva_map (MonoImage *image, guint32 addr)
150 MonoCLIImageInfo *iinfo = image->image_info;
151 const int top = iinfo->cli_section_count;
152 MonoSectionTable *tables = iinfo->cli_section_tables;
156 if (image->is_module_handle) {
157 if (addr && addr < image->raw_data_len)
158 return image->raw_data + addr;
164 for (i = 0; i < top; i++){
165 if ((addr >= tables->st_virtual_address) &&
166 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
167 if (!iinfo->cli_sections [i]) {
168 if (!mono_image_ensure_section_idx (image, i))
171 return (char*)iinfo->cli_sections [i] +
172 (addr - tables->st_virtual_address);
182 * Initialize the global variables used by this module.
185 mono_images_init (void)
187 mono_mutex_init_recursive (&images_mutex);
189 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
190 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
192 debug_assembly_unload = g_getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
198 * mono_images_cleanup:
200 * Free all resources used by this module.
203 mono_images_cleanup (void)
208 mono_mutex_destroy (&images_mutex);
210 g_hash_table_iter_init (&iter, loaded_images_hash);
211 while (g_hash_table_iter_next (&iter, NULL, (void**)&image))
212 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly image '%s' still loaded at shutdown.", image->name);
214 g_hash_table_destroy (loaded_images_hash);
215 g_hash_table_destroy (loaded_images_refonly_hash);
217 mutex_inited = FALSE;
221 * mono_image_ensure_section_idx:
222 * @image: The image we are operating on
223 * @section: section number that we will load/map into memory
225 * This routine makes sure that we have an in-memory copy of
226 * an image section (.text, .rsrc, .data).
228 * Returns: TRUE on success
231 mono_image_ensure_section_idx (MonoImage *image, int section)
233 MonoCLIImageInfo *iinfo = image->image_info;
234 MonoSectionTable *sect;
237 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
239 if (iinfo->cli_sections [section] != NULL)
242 sect = &iinfo->cli_section_tables [section];
244 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
246 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
249 if (image->is_module_handle)
250 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
253 /* FIXME: we ignore the writable flag since we don't patch the binary */
254 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
259 * mono_image_ensure_section:
260 * @image: The image we are operating on
261 * @section: section name that we will load/map into memory
263 * This routine makes sure that we have an in-memory copy of
264 * an image section (.text, .rsrc, .data).
266 * Returns: TRUE on success
269 mono_image_ensure_section (MonoImage *image, const char *section)
271 MonoCLIImageInfo *ii = image->image_info;
274 for (i = 0; i < ii->cli_section_count; i++){
275 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
278 return mono_image_ensure_section_idx (image, i);
284 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
286 const int top = iinfo->cli_header.coff.coff_sections;
289 iinfo->cli_section_count = top;
290 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
291 iinfo->cli_sections = g_new0 (void *, top);
293 for (i = 0; i < top; i++){
294 MonoSectionTable *t = &iinfo->cli_section_tables [i];
296 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
298 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
299 offset += sizeof (MonoSectionTable);
301 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
302 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
303 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
304 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
305 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
306 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
307 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
308 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
309 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
310 t->st_flags = GUINT32_FROM_LE (t->st_flags);
312 /* consistency checks here */
319 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
323 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
324 if (offset == INVALID_ADDRESS)
327 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
329 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
331 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
332 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
333 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
334 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
335 SWAP32 (iinfo->cli_cli_header.ch_size);
336 SWAP32 (iinfo->cli_cli_header.ch_flags);
337 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
338 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
339 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
340 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
341 SWAPPDE (iinfo->cli_cli_header.ch_resources);
342 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
343 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
344 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
345 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
346 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
347 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
348 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
349 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
350 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
351 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
352 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
353 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
354 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
359 /* Catch new uses of the fields that are supposed to be zero */
361 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
362 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
363 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
364 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
365 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
366 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
367 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
368 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
369 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
372 * No need to scare people who are testing this, I am just
373 * labelling this as a LAMESPEC
375 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
383 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
385 guint32 offset, size;
391 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
392 if (offset == INVALID_ADDRESS)
395 size = iinfo->cli_cli_header.ch_metadata.size;
397 if (offset + size > image->raw_data_len)
399 image->raw_metadata = image->raw_data + offset;
401 /* 24.2.1: Metadata root starts here */
402 ptr = image->raw_metadata;
404 if (strncmp (ptr, "BSJB", 4) == 0){
405 guint32 version_string_len;
408 image->md_version_major = read16 (ptr);
410 image->md_version_minor = read16 (ptr);
413 version_string_len = read32 (ptr);
415 image->version = g_strndup (ptr, version_string_len);
416 ptr += version_string_len;
417 pad = ptr - image->raw_metadata;
419 ptr += 4 - (pad % 4);
423 /* skip over flags */
426 streams = read16 (ptr);
429 for (i = 0; i < streams; i++){
430 if (strncmp (ptr + 8, "#~", 3) == 0){
431 image->heap_tables.data = image->raw_metadata + read32 (ptr);
432 image->heap_tables.size = read32 (ptr + 4);
434 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
435 image->heap_strings.data = image->raw_metadata + read32 (ptr);
436 image->heap_strings.size = read32 (ptr + 4);
438 } else if (strncmp (ptr + 8, "#US", 4) == 0){
439 image->heap_us.data = image->raw_metadata + read32 (ptr);
440 image->heap_us.size = read32 (ptr + 4);
442 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
443 image->heap_blob.data = image->raw_metadata + read32 (ptr);
444 image->heap_blob.size = read32 (ptr + 4);
446 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
447 image->heap_guid.data = image->raw_metadata + read32 (ptr);
448 image->heap_guid.size = read32 (ptr + 4);
450 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
451 image->heap_tables.data = image->raw_metadata + read32 (ptr);
452 image->heap_tables.size = read32 (ptr + 4);
454 image->uncompressed_metadata = TRUE;
455 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);
457 g_message ("Unknown heap type: %s\n", ptr + 8);
458 ptr += 8 + strlen (ptr + 8) + 1;
460 pad = ptr - image->raw_metadata;
462 ptr += 4 - (pad % 4);
465 g_assert (image->heap_guid.data);
466 g_assert (image->heap_guid.size >= 16);
468 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
474 * Load representation of logical metadata tables, from the "#~" stream
477 load_tables (MonoImage *image)
479 const char *heap_tables = image->heap_tables.data;
481 guint64 valid_mask, sorted_mask;
482 int valid = 0, table;
485 heap_sizes = heap_tables [6];
486 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
487 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
488 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
490 valid_mask = read64 (heap_tables + 8);
491 sorted_mask = read64 (heap_tables + 16);
492 rows = (const guint32 *) (heap_tables + 24);
494 for (table = 0; table < 64; table++){
495 if ((valid_mask & ((guint64) 1 << table)) == 0){
496 if (table > MONO_TABLE_LAST)
498 image->tables [table].rows = 0;
501 if (table > MONO_TABLE_LAST) {
502 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
504 image->tables [table].rows = read32 (rows);
506 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
507 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
513 image->tables_base = (heap_tables + 24) + (4 * valid);
515 /* They must be the same */
516 g_assert ((const void *) image->tables_base == (const void *) rows);
518 mono_metadata_compute_table_bases (image);
523 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
525 if (!load_metadata_ptrs (image, iinfo))
528 return load_tables (image);
532 mono_image_check_for_module_cctor (MonoImage *image)
534 MonoTableInfo *t, *mt;
535 t = &image->tables [MONO_TABLE_TYPEDEF];
536 mt = &image->tables [MONO_TABLE_METHOD];
537 if (image_is_dynamic (image)) {
539 image->checked_module_cctor = TRUE;
543 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
544 const char *name = mono_metadata_string_heap (image, nameidx);
545 if (strcmp (name, "<Module>") == 0) {
546 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
549 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
551 last_method = mt->rows;
552 for (; first_method < last_method; first_method++) {
553 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
554 name = mono_metadata_string_heap (image, nameidx);
555 if (strcmp (name, ".cctor") == 0) {
556 image->has_module_cctor = TRUE;
557 image->checked_module_cctor = TRUE;
563 image->has_module_cctor = FALSE;
564 image->checked_module_cctor = TRUE;
568 load_modules (MonoImage *image)
575 t = &image->tables [MONO_TABLE_MODULEREF];
576 image->modules = g_new0 (MonoImage *, t->rows);
577 image->modules_loaded = g_new0 (gboolean, t->rows);
578 image->module_count = t->rows;
582 * mono_image_load_module:
584 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
585 * it cannot be loaded.
588 mono_image_load_module (MonoImage *image, int idx)
591 MonoTableInfo *file_table;
594 gboolean refonly = image->ref_only;
595 GList *list_iter, *valid_modules = NULL;
596 MonoImageOpenStatus status;
598 if ((image->module_count == 0) || (idx > image->module_count || idx <= 0))
600 if (image->modules_loaded [idx - 1])
601 return image->modules [idx - 1];
603 file_table = &image->tables [MONO_TABLE_FILE];
604 for (i = 0; i < file_table->rows; i++) {
605 guint32 cols [MONO_FILE_SIZE];
606 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
607 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
609 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
612 t = &image->tables [MONO_TABLE_MODULEREF];
613 base_dir = g_path_get_dirname (image->name);
618 guint32 cols [MONO_MODULEREF_SIZE];
619 /* if there is no file table, we try to load the module... */
620 int valid = file_table->rows == 0;
622 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
623 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
624 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
625 /* be safe with string dups, but we could just compare string indexes */
626 if (strcmp (list_iter->data, name) == 0) {
632 module_ref = g_build_filename (base_dir, name, NULL);
633 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
634 if (image->modules [idx - 1]) {
635 mono_image_addref (image->modules [idx - 1]);
636 image->modules [idx - 1]->assembly = image->assembly;
638 if (image->modules [idx - 1]->is_module_handle)
639 mono_image_fixup_vtable (image->modules [idx - 1]);
641 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
647 image->modules_loaded [idx - 1] = TRUE;
650 g_list_free (valid_modules);
652 return image->modules [idx - 1];
656 class_key_extract (gpointer value)
658 MonoClass *class = value;
660 return GUINT_TO_POINTER (class->type_token);
664 class_next_value (gpointer value)
666 MonoClass *class = value;
668 return (gpointer*)&class->next_class_cache;
672 mono_image_init (MonoImage *image)
674 mono_mutex_init_recursive (&image->lock);
675 mono_mutex_init_recursive (&image->szarray_cache_lock);
677 image->mempool = mono_mempool_new_size (512);
678 mono_internal_hash_table_init (&image->class_cache,
682 image->field_cache = mono_conc_hashtable_new (&image->lock, NULL, NULL);
684 image->typespec_cache = g_hash_table_new (NULL, NULL);
685 image->memberref_signatures = g_hash_table_new (NULL, NULL);
686 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
687 image->method_signatures = g_hash_table_new (NULL, NULL);
689 image->property_hash = mono_property_hash_new ();
692 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
693 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
694 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
695 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
696 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
705 * Returns < 0 to indicate an error.
708 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
710 MonoDotNetHeader64 header64;
713 if (!image->is_module_handle)
715 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
718 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
720 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
723 /* endian swap the fields common between PE and PE+ */
724 SWAP32 (header->coff.coff_time);
725 SWAP32 (header->coff.coff_symptr);
726 SWAP32 (header->coff.coff_symcount);
727 SWAP16 (header->coff.coff_machine);
728 SWAP16 (header->coff.coff_sections);
729 SWAP16 (header->coff.coff_opt_header_size);
730 SWAP16 (header->coff.coff_attributes);
732 SWAP32 (header->pe.pe_code_size);
733 SWAP32 (header->pe.pe_uninit_data_size);
734 SWAP32 (header->pe.pe_rva_entry_point);
735 SWAP32 (header->pe.pe_rva_code_base);
736 SWAP32 (header->pe.pe_rva_data_base);
737 SWAP16 (header->pe.pe_magic);
739 /* now we are ready for the basic tests */
741 if (header->pe.pe_magic == 0x10B) {
742 offset += sizeof (MonoDotNetHeader);
743 SWAP32 (header->pe.pe_data_size);
744 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
747 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
748 SWAP32 (header->nt.pe_stack_reserve);
749 SWAP32 (header->nt.pe_stack_commit);
750 SWAP32 (header->nt.pe_heap_reserve);
751 SWAP32 (header->nt.pe_heap_commit);
752 } else if (header->pe.pe_magic == 0x20B) {
753 /* PE32+ file format */
754 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
756 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
757 offset += sizeof (MonoDotNetHeader64);
758 /* copy the fields already swapped. the last field, pe_data_size, is missing */
759 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
760 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
761 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
763 SWAP64 (header64.nt.pe_image_base);
764 header->nt.pe_image_base = header64.nt.pe_image_base;
765 SWAP64 (header64.nt.pe_stack_reserve);
766 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
767 SWAP64 (header64.nt.pe_stack_commit);
768 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
769 SWAP64 (header64.nt.pe_heap_reserve);
770 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
771 SWAP64 (header64.nt.pe_heap_commit);
772 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
774 header->nt.pe_section_align = header64.nt.pe_section_align;
775 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
776 header->nt.pe_os_major = header64.nt.pe_os_major;
777 header->nt.pe_os_minor = header64.nt.pe_os_minor;
778 header->nt.pe_user_major = header64.nt.pe_user_major;
779 header->nt.pe_user_minor = header64.nt.pe_user_minor;
780 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
781 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
782 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
783 header->nt.pe_image_size = header64.nt.pe_image_size;
784 header->nt.pe_header_size = header64.nt.pe_header_size;
785 header->nt.pe_checksum = header64.nt.pe_checksum;
786 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
787 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
788 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
789 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
791 /* copy the datadir */
792 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
797 /* MonoPEHeaderNT: not used yet */
798 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
799 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
800 SWAP16 (header->nt.pe_os_major); /* must be 4 */
801 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
802 SWAP16 (header->nt.pe_user_major);
803 SWAP16 (header->nt.pe_user_minor);
804 SWAP16 (header->nt.pe_subsys_major);
805 SWAP16 (header->nt.pe_subsys_minor);
806 SWAP32 (header->nt.pe_reserved_1);
807 SWAP32 (header->nt.pe_image_size);
808 SWAP32 (header->nt.pe_header_size);
809 SWAP32 (header->nt.pe_checksum);
810 SWAP16 (header->nt.pe_subsys_required);
811 SWAP16 (header->nt.pe_dll_flags);
812 SWAP32 (header->nt.pe_loader_flags);
813 SWAP32 (header->nt.pe_data_dir_count);
815 /* MonoDotNetHeader: mostly unused */
816 SWAPPDE (header->datadir.pe_export_table);
817 SWAPPDE (header->datadir.pe_import_table);
818 SWAPPDE (header->datadir.pe_resource_table);
819 SWAPPDE (header->datadir.pe_exception_table);
820 SWAPPDE (header->datadir.pe_certificate_table);
821 SWAPPDE (header->datadir.pe_reloc_table);
822 SWAPPDE (header->datadir.pe_debug);
823 SWAPPDE (header->datadir.pe_copyright);
824 SWAPPDE (header->datadir.pe_global_ptr);
825 SWAPPDE (header->datadir.pe_tls_table);
826 SWAPPDE (header->datadir.pe_load_config_table);
827 SWAPPDE (header->datadir.pe_bound_import);
828 SWAPPDE (header->datadir.pe_iat);
829 SWAPPDE (header->datadir.pe_delay_import_desc);
830 SWAPPDE (header->datadir.pe_cli_header);
831 SWAPPDE (header->datadir.pe_reserved);
834 if (image->is_module_handle)
835 image->raw_data_len = header->nt.pe_image_size;
842 mono_image_load_pe_data (MonoImage *image)
844 MonoCLIImageInfo *iinfo;
845 MonoDotNetHeader *header;
846 MonoMSDOSHeader msdos;
849 iinfo = image->image_info;
850 header = &iinfo->cli_header;
853 if (!image->is_module_handle)
855 if (offset + sizeof (msdos) > image->raw_data_len)
857 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
859 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
862 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
864 offset = msdos.pe_offset;
866 offset = do_load_header (image, header, offset);
871 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
873 if (header->coff.coff_machine != 0x14c)
879 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
880 * which produces binaries with 7.0. From Sergey:
882 * The reason is that MSVC7 uses traditional compile/link
883 * sequence for CIL executables, and VS.NET (and Framework
884 * SDK) includes linker version 7, that puts 7.0 in this
885 * field. That's why it's currently not possible to load VC
886 * binaries with Mono. This field is pretty much meaningless
887 * anyway (what linker?).
889 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
894 * FIXME: byte swap all addresses here for header.
897 if (!load_section_tables (image, iinfo, offset))
907 mono_image_load_cli_data (MonoImage *image)
909 MonoCLIImageInfo *iinfo;
910 MonoDotNetHeader *header;
912 iinfo = image->image_info;
913 header = &iinfo->cli_header;
915 /* Load the CLI header */
916 if (!load_cli_header (image, iinfo))
919 if (!load_metadata (image, iinfo))
926 mono_image_load_names (MonoImage *image)
928 /* modules don't have an assembly table row */
929 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
930 image->assembly_name = mono_metadata_string_heap (image,
931 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
932 0, MONO_ASSEMBLY_NAME));
935 image->module_name = mono_metadata_string_heap (image,
936 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
937 0, MONO_MODULE_NAME));
941 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
942 gboolean care_about_cli, gboolean care_about_pecoff)
944 MonoCLIImageInfo *iinfo;
945 MonoDotNetHeader *header;
946 GSList *errors = NULL;
948 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
950 mono_image_init (image);
952 iinfo = image->image_info;
953 header = &iinfo->cli_header;
956 *status = MONO_IMAGE_IMAGE_INVALID;
958 if (care_about_pecoff == FALSE)
961 if (!mono_verifier_verify_pe_data (image, &errors))
964 if (!mono_image_load_pe_data (image))
967 if (care_about_cli == FALSE) {
971 if (!mono_verifier_verify_cli_data (image, &errors))
974 if (!mono_image_load_cli_data (image))
977 if (!mono_verifier_verify_table_data (image, &errors))
980 mono_image_load_names (image);
982 load_modules (image);
985 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
987 *status = MONO_IMAGE_OK;
993 MonoVerifyInfo *info = errors->data;
994 g_warning ("Could not load image %s due to %s", image->name, info->message);
995 mono_free_verify_list (errors);
997 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
998 mono_image_close (image);
1003 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
1004 gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
1006 MonoCLIImageInfo *iinfo;
1010 if ((filed = mono_file_map_open (fname)) == NULL){
1011 if (IS_PORTABILITY_SET) {
1012 gchar *ffname = mono_portability_find_file (fname, TRUE);
1014 filed = mono_file_map_open (ffname);
1019 if (filed == NULL) {
1021 *status = MONO_IMAGE_ERROR_ERRNO;
1026 image = g_new0 (MonoImage, 1);
1027 image->raw_buffer_used = TRUE;
1028 image->raw_data_len = mono_file_map_size (filed);
1029 image->raw_data = mono_file_map (image->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &image->raw_data_handle);
1030 #if defined(HAVE_MMAP) && !defined (HOST_WIN32)
1031 if (!image->raw_data) {
1032 image->fileio_used = TRUE;
1033 image->raw_data = mono_file_map_fileio (image->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &image->raw_data_handle);
1036 if (!image->raw_data) {
1037 mono_file_map_close (filed);
1040 *status = MONO_IMAGE_IMAGE_INVALID;
1043 iinfo = g_new0 (MonoCLIImageInfo, 1);
1044 image->image_info = iinfo;
1045 image->name = mono_path_resolve_symlinks (fname);
1046 image->ref_only = refonly;
1047 image->ref_count = 1;
1048 /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
1049 image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
1051 mono_file_map_close (filed);
1052 return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
1056 mono_image_loaded_full (const char *name, gboolean refonly)
1059 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1061 mono_images_lock ();
1062 res = g_hash_table_lookup (loaded_images, name);
1063 mono_images_unlock ();
1068 * mono_image_loaded:
1069 * @name: name of the image to load
1071 * This routine ensures that the given image is loaded.
1073 * Returns: the loaded MonoImage, or NULL on failure.
1076 mono_image_loaded (const char *name)
1078 return mono_image_loaded_full (name, FALSE);
1087 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1089 GuidData *data = user_data;
1095 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1100 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1103 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1107 mono_images_lock ();
1108 g_hash_table_foreach (loaded_images, find_by_guid, &data);
1109 mono_images_unlock ();
1114 mono_image_loaded_by_guid (const char *guid)
1116 return mono_image_loaded_by_guid_full (guid, FALSE);
1120 register_image (MonoImage *image)
1123 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1125 mono_images_lock ();
1126 image2 = g_hash_table_lookup (loaded_images, image->name);
1129 /* Somebody else beat us to it */
1130 mono_image_addref (image2);
1131 mono_images_unlock ();
1132 mono_image_close (image);
1135 g_hash_table_insert (loaded_images, image->name, image);
1136 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1137 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1138 mono_images_unlock ();
1144 mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
1146 MonoCLIImageInfo *iinfo;
1150 if (!data || !data_len) {
1152 *status = MONO_IMAGE_IMAGE_INVALID;
1157 datac = g_try_malloc (data_len);
1160 *status = MONO_IMAGE_ERROR_ERRNO;
1163 memcpy (datac, data, data_len);
1166 image = g_new0 (MonoImage, 1);
1167 image->raw_data = datac;
1168 image->raw_data_len = data_len;
1169 image->raw_data_allocated = need_copy;
1170 image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup(name);
1171 iinfo = g_new0 (MonoCLIImageInfo, 1);
1172 image->image_info = iinfo;
1173 image->ref_only = refonly;
1175 image = do_mono_image_load (image, status, TRUE, TRUE);
1179 return register_image (image);
1183 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1185 return mono_image_open_from_data_with_name (data, data_len, need_copy, status, refonly, NULL);
1189 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1191 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1195 /* fname is not duplicated. */
1197 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1200 MonoCLIImageInfo* iinfo;
1202 image = g_new0 (MonoImage, 1);
1203 image->raw_data = (char*) module_handle;
1204 image->is_module_handle = TRUE;
1205 iinfo = g_new0 (MonoCLIImageInfo, 1);
1206 image->image_info = iinfo;
1207 image->name = fname;
1208 image->ref_count = has_entry_point ? 0 : 1;
1209 image->has_entry_point = has_entry_point;
1211 image = do_mono_image_load (image, status, TRUE, TRUE);
1215 return register_image (image);
1220 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1223 GHashTable *loaded_images;
1226 g_return_val_if_fail (fname != NULL, NULL);
1229 /* Load modules using LoadLibrary. */
1230 if (!refonly && coree_module_handle) {
1231 HMODULE module_handle;
1232 guint16 *fname_utf16;
1235 absfname = mono_path_resolve_symlinks (fname);
1238 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1239 mono_images_lock ();
1240 image = g_hash_table_lookup (loaded_images_hash, absfname);
1242 g_assert (image->is_module_handle);
1243 if (image->has_entry_point && image->ref_count == 0) {
1244 /* Increment reference count on images loaded outside of the runtime. */
1245 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1246 /* The image is already loaded because _CorDllMain removes images from the hash. */
1247 module_handle = LoadLibrary (fname_utf16);
1248 g_assert (module_handle == (HMODULE) image->raw_data);
1250 mono_image_addref (image);
1251 mono_images_unlock ();
1253 g_free (fname_utf16);
1258 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1259 module_handle = MonoLoadImage (fname_utf16);
1260 if (status && module_handle == NULL)
1261 last_error = GetLastError ();
1263 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1264 image = g_hash_table_lookup (loaded_images_hash, absfname);
1266 mono_image_addref (image);
1267 mono_images_unlock ();
1269 g_free (fname_utf16);
1271 if (module_handle == NULL) {
1275 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1276 *status = MONO_IMAGE_IMAGE_INVALID;
1278 if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND)
1288 g_assert (image->is_module_handle);
1289 g_assert (image->has_entry_point);
1294 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1298 absfname = mono_path_canonicalize (fname);
1301 * The easiest solution would be to do all the loading inside the mutex,
1302 * but that would lead to scalability problems. So we let the loading
1303 * happen outside the mutex, and if multiple threads happen to load
1304 * the same image, we discard all but the first copy.
1306 mono_images_lock ();
1307 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1308 image = g_hash_table_lookup (loaded_images, absfname);
1312 mono_image_addref (image);
1313 mono_images_unlock ();
1316 mono_images_unlock ();
1318 image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1322 return register_image (image);
1327 * @fname: filename that points to the module we want to open
1328 * @status: An error condition is returned in this field
1330 * Returns: An open image of type %MonoImage or NULL on error.
1331 * The caller holds a temporary reference to the returned image which should be cleared
1332 * when no longer needed by calling mono_image_close ().
1333 * if NULL, then check the value of @status for details on the error
1336 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1338 return mono_image_open_full (fname, status, FALSE);
1342 * mono_pe_file_open:
1343 * @fname: filename that points to the module we want to open
1344 * @status: An error condition is returned in this field
1346 * Returns: An open image of type %MonoImage or NULL on error. if
1347 * NULL, then check the value of @status for details on the error.
1348 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1349 * It's just a PE file loader, used for FileVersionInfo. It also does
1350 * not use the image cache.
1353 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1355 g_return_val_if_fail (fname != NULL, NULL);
1357 return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1361 * mono_image_open_raw
1362 * @fname: filename that points to the module we want to open
1363 * @status: An error condition is returned in this field
1365 * Returns an image without loading neither pe or cli data.
1367 * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
1370 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1372 g_return_val_if_fail (fname != NULL, NULL);
1374 return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1378 mono_image_fixup_vtable (MonoImage *image)
1381 MonoCLIImageInfo *iinfo;
1383 MonoVTableFixup *vtfixup;
1389 g_assert (image->is_module_handle);
1391 iinfo = image->image_info;
1392 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1393 if (!de->rva || !de->size)
1395 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1399 count = de->size / sizeof (MonoVTableFixup);
1401 if (!vtfixup->rva || !vtfixup->count)
1404 slot = mono_image_rva_map (image, vtfixup->rva);
1406 slot_type = vtfixup->type;
1407 slot_count = vtfixup->count;
1408 if (slot_type & VTFIXUP_TYPE_32BIT)
1409 while (slot_count--) {
1410 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1411 slot = ((guint32*) slot) + 1;
1413 else if (slot_type & VTFIXUP_TYPE_64BIT)
1414 while (slot_count--) {
1415 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1416 slot = ((guint32*) slot) + 1;
1419 g_assert_not_reached();
1424 g_assert_not_reached();
1429 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1431 g_hash_table_destroy ((GHashTable*)val);
1436 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1438 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1443 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1445 g_slist_free ((GSList*)val);
1449 * mono_image_addref:
1450 * @image: The image file we wish to add a reference to
1452 * Increases the reference count of an image.
1455 mono_image_addref (MonoImage *image)
1457 InterlockedIncrement (&image->ref_count);
1461 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1463 stream->alloc_size = stream->index = stream->offset = 0;
1464 g_free (stream->data);
1465 stream->data = NULL;
1467 g_hash_table_destroy (stream->hash);
1468 stream->hash = NULL;
1473 free_hash (GHashTable *hash)
1476 g_hash_table_destroy (hash);
1480 * Returns whether mono_image_close_finish() must be called as well.
1481 * We must unload images in two steps because clearing the domain in
1482 * SGen requires the class metadata to be intact, but we need to free
1483 * the mono_g_hash_tables in case a collection occurs during domain
1484 * unloading and the roots would trip up the GC.
1487 mono_image_close_except_pools (MonoImage *image)
1490 GHashTable *loaded_images;
1493 g_return_val_if_fail (image != NULL, FALSE);
1496 * Atomically decrement the refcount and remove ourselves from the hash tables, so
1497 * register_image () can't grab an image which is being closed.
1499 mono_images_lock ();
1501 if (InterlockedDecrement (&image->ref_count) > 0) {
1502 mono_images_unlock ();
1506 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1507 image2 = g_hash_table_lookup (loaded_images, image->name);
1508 if (image == image2) {
1509 /* This is not true if we are called from mono_image_open () */
1510 g_hash_table_remove (loaded_images, image->name);
1512 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1513 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1515 mono_images_unlock ();
1518 if (image->is_module_handle && image->has_entry_point) {
1519 mono_images_lock ();
1520 if (image->ref_count == 0) {
1521 /* Image will be closed by _CorDllMain. */
1522 FreeLibrary ((HMODULE) image->raw_data);
1523 mono_images_unlock ();
1526 mono_images_unlock ();
1530 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1532 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1534 mono_image_invoke_unload_hook (image);
1536 mono_metadata_clean_for_image (image);
1539 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1540 * assemblies, so we can't release these references in mono_assembly_close () since the
1541 * MonoImage might outlive its associated MonoAssembly.
1543 if (image->references && !image_is_dynamic (image)) {
1544 for (i = 0; i < image->nreferences; i++) {
1545 if (image->references [i] && image->references [i] != REFERENCE_MISSING) {
1546 if (!mono_assembly_close_except_image_pools (image->references [i]))
1547 image->references [i] = NULL;
1551 if (image->references) {
1552 g_free (image->references);
1553 image->references = NULL;
1558 mono_images_lock ();
1559 if (image->is_module_handle && !image->has_entry_point)
1560 FreeLibrary ((HMODULE) image->raw_data);
1561 mono_images_unlock ();
1564 if (image->raw_buffer_used) {
1565 if (image->raw_data != NULL) {
1567 if (image->fileio_used)
1568 mono_file_unmap_fileio (image->raw_data, image->raw_data_handle);
1571 mono_file_unmap (image->raw_data, image->raw_data_handle);
1575 if (image->raw_data_allocated) {
1576 /* FIXME: do we need this? (image is disposed anyway) */
1577 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1578 MonoCLIImageInfo *ii = image->image_info;
1580 if ((image->raw_metadata > image->raw_data) &&
1581 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1582 image->raw_metadata = NULL;
1584 for (i = 0; i < ii->cli_section_count; i++)
1585 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1586 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1587 ii->cli_sections [i] = NULL;
1589 g_free (image->raw_data);
1592 if (debug_assembly_unload) {
1593 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1595 g_free (image->name);
1596 g_free (image->guid);
1597 g_free (image->version);
1598 g_free (image->files);
1601 if (image->method_cache)
1602 g_hash_table_destroy (image->method_cache);
1603 if (image->methodref_cache)
1604 g_hash_table_destroy (image->methodref_cache);
1605 mono_internal_hash_table_destroy (&image->class_cache);
1606 mono_conc_hashtable_destroy (image->field_cache);
1607 if (image->array_cache) {
1608 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1609 g_hash_table_destroy (image->array_cache);
1611 if (image->szarray_cache)
1612 g_hash_table_destroy (image->szarray_cache);
1613 if (image->ptr_cache)
1614 g_hash_table_destroy (image->ptr_cache);
1615 if (image->name_cache) {
1616 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1617 g_hash_table_destroy (image->name_cache);
1620 free_hash (image->native_wrapper_cache);
1621 free_hash (image->managed_wrapper_cache);
1622 free_hash (image->delegate_begin_invoke_cache);
1623 free_hash (image->delegate_end_invoke_cache);
1624 free_hash (image->delegate_invoke_cache);
1625 free_hash (image->delegate_abstract_invoke_cache);
1626 free_hash (image->delegate_bound_static_invoke_cache);
1627 free_hash (image->delegate_invoke_generic_cache);
1628 free_hash (image->delegate_begin_invoke_generic_cache);
1629 free_hash (image->delegate_end_invoke_generic_cache);
1630 free_hash (image->synchronized_generic_cache);
1631 free_hash (image->remoting_invoke_cache);
1632 free_hash (image->runtime_invoke_cache);
1633 free_hash (image->runtime_invoke_vtype_cache);
1634 free_hash (image->runtime_invoke_direct_cache);
1635 free_hash (image->runtime_invoke_vcall_cache);
1636 free_hash (image->synchronized_cache);
1637 free_hash (image->unbox_wrapper_cache);
1638 free_hash (image->cominterop_invoke_cache);
1639 free_hash (image->cominterop_wrapper_cache);
1640 free_hash (image->typespec_cache);
1641 free_hash (image->ldfld_wrapper_cache);
1642 free_hash (image->ldflda_wrapper_cache);
1643 free_hash (image->stfld_wrapper_cache);
1644 free_hash (image->isinst_cache);
1645 free_hash (image->castclass_cache);
1646 free_hash (image->proxy_isinst_cache);
1647 free_hash (image->thunk_invoke_cache);
1648 free_hash (image->var_cache_slow);
1649 free_hash (image->mvar_cache_slow);
1650 free_hash (image->wrapper_param_names);
1651 free_hash (image->native_wrapper_aot_cache);
1652 free_hash (image->pinvoke_scopes);
1653 free_hash (image->pinvoke_scope_filenames);
1654 free_hash (image->gsharedvt_types);
1656 /* The ownership of signatures is not well defined */
1657 g_hash_table_destroy (image->memberref_signatures);
1658 g_hash_table_destroy (image->helper_signatures);
1659 g_hash_table_destroy (image->method_signatures);
1661 if (image->rgctx_template_hash)
1662 g_hash_table_destroy (image->rgctx_template_hash);
1664 if (image->property_hash)
1665 mono_property_hash_destroy (image->property_hash);
1668 reflection_info_unregister_classes is only required by dynamic images, which will not be properly
1669 cleared during shutdown as we don't perform regular appdomain unload for the root one.
1671 g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ());
1672 image->reflection_info_unregister_classes = NULL;
1674 if (image->interface_bitset) {
1675 mono_unload_interface_ids (image->interface_bitset);
1676 mono_bitset_free (image->interface_bitset);
1678 if (image->image_info){
1679 MonoCLIImageInfo *ii = image->image_info;
1681 if (ii->cli_section_tables)
1682 g_free (ii->cli_section_tables);
1683 if (ii->cli_sections)
1684 g_free (ii->cli_sections);
1685 g_free (image->image_info);
1688 for (i = 0; i < image->module_count; ++i) {
1689 if (image->modules [i]) {
1690 if (!mono_image_close_except_pools (image->modules [i]))
1691 image->modules [i] = NULL;
1694 if (image->modules_loaded)
1695 g_free (image->modules_loaded);
1697 mono_mutex_destroy (&image->szarray_cache_lock);
1698 mono_mutex_destroy (&image->lock);
1700 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1701 if (image_is_dynamic (image)) {
1702 /* Dynamic images are GC_MALLOCed */
1703 g_free ((char*)image->module_name);
1704 mono_dynamic_image_free ((MonoDynamicImage*)image);
1707 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1713 mono_image_close_finish (MonoImage *image)
1717 if (image->references && !image_is_dynamic (image)) {
1718 for (i = 0; i < image->nreferences; i++) {
1719 if (image->references [i] && image->references [i] != REFERENCE_MISSING)
1720 mono_assembly_close_finish (image->references [i]);
1723 g_free (image->references);
1724 image->references = NULL;
1727 for (i = 0; i < image->module_count; ++i) {
1728 if (image->modules [i])
1729 mono_image_close_finish (image->modules [i]);
1732 g_free (image->modules);
1734 #ifndef DISABLE_PERFCOUNTERS
1735 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1738 if (!image_is_dynamic (image)) {
1739 if (debug_assembly_unload)
1740 mono_mempool_invalidate (image->mempool);
1742 mono_mempool_destroy (image->mempool);
1746 if (debug_assembly_unload)
1747 mono_mempool_invalidate (image->mempool);
1749 mono_mempool_destroy (image->mempool);
1750 mono_dynamic_image_free_image ((MonoDynamicImage*)image);
1757 * @image: The image file we wish to close
1759 * Closes an image file, deallocates all memory consumed and
1760 * unmaps all possible sections of the file
1763 mono_image_close (MonoImage *image)
1765 if (mono_image_close_except_pools (image))
1766 mono_image_close_finish (image);
1770 * mono_image_strerror:
1771 * @status: an code indicating the result from a recent operation
1773 * Returns: a string describing the error
1776 mono_image_strerror (MonoImageOpenStatus status)
1781 case MONO_IMAGE_ERROR_ERRNO:
1782 return strerror (errno);
1783 case MONO_IMAGE_IMAGE_INVALID:
1784 return "File does not contain a valid CIL image";
1785 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1786 return "An assembly was referenced, but could not be found";
1788 return "Internal error";
1792 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1793 guint32 lang_id, gunichar2 *name,
1794 MonoPEResourceDirEntry *entry,
1795 MonoPEResourceDir *root, guint32 level)
1797 gboolean is_string, is_dir;
1798 guint32 name_offset, dir_offset;
1800 /* Level 0 holds a directory entry for each type of resource
1801 * (identified by ID or name).
1803 * Level 1 holds a directory entry for each named resource
1804 * item, and each "anonymous" item of a particular type of
1807 * Level 2 holds a directory entry for each language pointing to
1810 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1811 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1813 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1814 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1819 } else if (level==1) {
1820 if (res_id != name_offset)
1824 is_string==TRUE && name!=lookup (name_offset)) {
1828 } else if (level==2) {
1829 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1832 g_assert_not_reached ();
1836 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1837 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1840 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1842 for(i=0; i<entries; i++) {
1843 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1846 ret=mono_image_walk_resource_tree (info, res_id,
1857 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1858 MonoPEResourceDataEntry *res;
1860 res = g_new0 (MonoPEResourceDataEntry, 1);
1862 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1863 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1864 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1865 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1872 * mono_image_lookup_resource:
1873 * @image: the image to look up the resource in
1874 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1875 * @lang_id: The language id.
1876 * @name: the resource name to lookup.
1878 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1879 * of the given resource. The caller should free it using g_free () when no longer
1883 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1885 MonoCLIImageInfo *info;
1886 MonoDotNetHeader *header;
1887 MonoPEDatadir *datadir;
1888 MonoPEDirEntry *rsrc;
1889 MonoPEResourceDir *resource_dir;
1890 MonoPEResourceDirEntry *res_entries;
1897 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1899 info=image->image_info;
1904 header=&info->cli_header;
1909 datadir=&header->datadir;
1914 rsrc=&datadir->pe_resource_table;
1919 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1920 if(resource_dir==NULL) {
1924 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1925 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1927 for(i=0; i<entries; i++) {
1928 MonoPEResourceDirEntry *entry=&res_entries[i];
1931 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1932 name, entry, resource_dir,
1943 * mono_image_get_entry_point:
1944 * @image: the image where the entry point will be looked up.
1946 * Use this routine to determine the metadata token for method that
1947 * has been flagged as the entry point.
1949 * Returns: the token for the entry point method in the image
1952 mono_image_get_entry_point (MonoImage *image)
1954 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1958 * mono_image_get_resource:
1959 * @image: the image where the resource will be looked up.
1960 * @offset: The offset to add to the resource
1961 * @size: a pointer to an int where the size of the resource will be stored
1963 * This is a low-level routine that fetches a resource from the
1964 * metadata that starts at a given @offset. The @size parameter is
1965 * filled with the data field as encoded in the metadata.
1967 * Returns: the pointer to the resource whose offset is @offset.
1970 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1972 MonoCLIImageInfo *iinfo = image->image_info;
1973 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1976 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1979 data = mono_image_rva_map (image, ch->ch_resources.rva);
1984 *size = read32 (data);
1990 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1992 char *base_dir, *name;
1994 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1998 if (fileidx < 1 || fileidx > t->rows)
2001 mono_loader_lock ();
2002 if (image->files && image->files [fileidx - 1]) {
2003 mono_loader_unlock ();
2004 return image->files [fileidx - 1];
2008 image->files = g_new0 (MonoImage*, t->rows);
2010 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
2011 fname = mono_metadata_string_heap (image, fname_id);
2012 base_dir = g_path_get_dirname (image->name);
2013 name = g_build_filename (base_dir, fname, NULL);
2014 res = mono_image_open (name, NULL);
2017 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
2018 res->assembly = image->assembly;
2019 for (i = 0; i < res->module_count; ++i) {
2020 if (res->modules [i] && !res->modules [i]->assembly)
2021 res->modules [i]->assembly = image->assembly;
2024 image->files [fileidx - 1] = res;
2026 if (res->is_module_handle)
2027 mono_image_fixup_vtable (res);
2030 mono_loader_unlock ();
2037 * mono_image_get_strong_name:
2038 * @image: a MonoImage
2039 * @size: a guint32 pointer, or NULL.
2041 * If the image has a strong name, and @size is not NULL, the value
2042 * pointed to by size will have the size of the strong name.
2044 * Returns: NULL if the image does not have a strong name, or a
2045 * pointer to the public key.
2048 mono_image_get_strong_name (MonoImage *image, guint32 *size)
2050 MonoCLIImageInfo *iinfo = image->image_info;
2051 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2054 if (!de->size || !de->rva)
2056 data = mono_image_rva_map (image, de->rva);
2065 * mono_image_strong_name_position:
2066 * @image: a MonoImage
2067 * @size: a guint32 pointer, or NULL.
2069 * If the image has a strong name, and @size is not NULL, the value
2070 * pointed to by size will have the size of the strong name.
2072 * Returns: the position within the image file where the strong name
2076 mono_image_strong_name_position (MonoImage *image, guint32 *size)
2078 MonoCLIImageInfo *iinfo = image->image_info;
2079 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2084 if (!de->size || !de->rva)
2086 pos = mono_cli_rva_image_map (image, de->rva);
2087 return pos == INVALID_ADDRESS ? 0 : pos;
2091 * mono_image_get_public_key:
2092 * @image: a MonoImage
2093 * @size: a guint32 pointer, or NULL.
2095 * This is used to obtain the public key in the @image.
2097 * If the image has a public key, and @size is not NULL, the value
2098 * pointed to by size will have the size of the public key.
2100 * Returns: NULL if the image does not have a public key, or a pointer
2101 * to the public key.
2104 mono_image_get_public_key (MonoImage *image, guint32 *size)
2109 if (image_is_dynamic (image)) {
2111 *size = ((MonoDynamicImage*)image)->public_key_len;
2112 return (char*)((MonoDynamicImage*)image)->public_key;
2114 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
2116 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
2119 pubkey = mono_metadata_blob_heap (image, tok);
2120 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
2127 * mono_image_get_name:
2128 * @name: a MonoImage
2130 * Returns: the name of the assembly.
2133 mono_image_get_name (MonoImage *image)
2135 return image->assembly_name;
2139 * mono_image_get_filename:
2140 * @image: a MonoImage
2142 * Used to get the filename that hold the actual MonoImage
2144 * Returns: the filename.
2147 mono_image_get_filename (MonoImage *image)
2153 mono_image_get_guid (MonoImage *image)
2158 const MonoTableInfo*
2159 mono_image_get_table_info (MonoImage *image, int table_id)
2161 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2163 return &image->tables [table_id];
2167 mono_image_get_table_rows (MonoImage *image, int table_id)
2169 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2171 return image->tables [table_id].rows;
2175 mono_table_info_get_rows (const MonoTableInfo *table)
2181 * mono_image_get_assembly:
2182 * @image: the MonoImage.
2184 * Use this routine to get the assembly that owns this image.
2186 * Returns: the assembly that holds this image.
2189 mono_image_get_assembly (MonoImage *image)
2191 return image->assembly;
2195 * mono_image_is_dynamic:
2196 * @image: the MonoImage
2198 * Determines if the given image was created dynamically through the
2199 * System.Reflection.Emit API
2201 * Returns: TRUE if the image was created dynamically, FALSE if not.
2204 mono_image_is_dynamic (MonoImage *image)
2206 return image_is_dynamic (image);
2210 * mono_image_has_authenticode_entry:
2211 * @image: the MonoImage
2213 * Use this routine to determine if the image has a Authenticode
2214 * Certificate Table.
2216 * Returns: TRUE if the image contains an authenticode entry in the PE
2220 mono_image_has_authenticode_entry (MonoImage *image)
2222 MonoCLIImageInfo *iinfo = image->image_info;
2223 MonoDotNetHeader *header = &iinfo->cli_header;
2224 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2225 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2226 return ((de->rva != 0) && (de->size > 8));
2230 mono_image_alloc (MonoImage *image, guint size)
2234 #ifndef DISABLE_PERFCOUNTERS
2235 mono_perfcounters->loader_bytes += size;
2237 mono_image_lock (image);
2238 res = mono_mempool_alloc (image->mempool, size);
2239 mono_image_unlock (image);
2245 mono_image_alloc0 (MonoImage *image, guint size)
2249 #ifndef DISABLE_PERFCOUNTERS
2250 mono_perfcounters->loader_bytes += size;
2252 mono_image_lock (image);
2253 res = mono_mempool_alloc0 (image->mempool, size);
2254 mono_image_unlock (image);
2260 mono_image_strdup (MonoImage *image, const char *s)
2264 #ifndef DISABLE_PERFCOUNTERS
2265 mono_perfcounters->loader_bytes += strlen (s);
2267 mono_image_lock (image);
2268 res = mono_mempool_strdup (image->mempool, s);
2269 mono_image_unlock (image);
2275 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2279 new_list = mono_image_alloc (image, sizeof (GList));
2280 new_list->data = data;
2281 new_list->prev = list ? list->prev : NULL;
2282 new_list->next = list;
2285 new_list->prev->next = new_list;
2287 list->prev = new_list;
2293 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2297 new_list = mono_image_alloc (image, sizeof (GSList));
2298 new_list->data = data;
2299 new_list->next = NULL;
2301 return g_slist_concat (list, new_list);
2305 mono_image_lock (MonoImage *image)
2307 mono_locks_acquire (&image->lock, ImageDataLock);
2311 mono_image_unlock (MonoImage *image)
2313 mono_locks_release (&image->lock, ImageDataLock);
2318 * mono_image_property_lookup:
2320 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2322 * LOCKING: Takes the image lock
2325 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2329 mono_image_lock (image);
2330 res = mono_property_hash_lookup (image->property_hash, subject, property);
2331 mono_image_unlock (image);
2337 * mono_image_property_insert:
2339 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2341 * LOCKING: Takes the image lock
2344 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2346 mono_image_lock (image);
2347 mono_property_hash_insert (image->property_hash, subject, property, value);
2348 mono_image_unlock (image);
2352 * mono_image_property_remove:
2354 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2356 * LOCKING: Takes the image lock
2359 mono_image_property_remove (MonoImage *image, gpointer subject)
2361 mono_image_lock (image);
2362 mono_property_hash_remove_object (image->property_hash, subject);
2363 mono_image_unlock (image);
2367 mono_image_append_class_to_reflection_info_set (MonoClass *class)
2369 MonoImage *image = class->image;
2370 g_assert (image_is_dynamic (image));
2371 mono_image_lock (image);
2372 image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, class);
2373 mono_image_unlock (image);