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;
236 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
238 if (iinfo->cli_sections [section] != NULL)
241 sect = &iinfo->cli_section_tables [section];
243 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
246 if (image->is_module_handle)
247 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
250 /* FIXME: we ignore the writable flag since we don't patch the binary */
251 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
256 * mono_image_ensure_section:
257 * @image: The image we are operating on
258 * @section: section name that we will load/map into memory
260 * This routine makes sure that we have an in-memory copy of
261 * an image section (.text, .rsrc, .data).
263 * Returns: TRUE on success
266 mono_image_ensure_section (MonoImage *image, const char *section)
268 MonoCLIImageInfo *ii = image->image_info;
271 for (i = 0; i < ii->cli_section_count; i++){
272 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
275 return mono_image_ensure_section_idx (image, i);
281 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
283 const int top = iinfo->cli_header.coff.coff_sections;
286 iinfo->cli_section_count = top;
287 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
288 iinfo->cli_sections = g_new0 (void *, top);
290 for (i = 0; i < top; i++){
291 MonoSectionTable *t = &iinfo->cli_section_tables [i];
293 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
295 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
296 offset += sizeof (MonoSectionTable);
298 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
299 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
300 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
301 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
302 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
303 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
304 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
305 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
306 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
307 t->st_flags = GUINT32_FROM_LE (t->st_flags);
309 /* consistency checks here */
316 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
320 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
321 if (offset == INVALID_ADDRESS)
324 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
326 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
328 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
329 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
330 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
331 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
332 SWAP32 (iinfo->cli_cli_header.ch_size);
333 SWAP32 (iinfo->cli_cli_header.ch_flags);
334 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
335 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
336 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
337 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
338 SWAPPDE (iinfo->cli_cli_header.ch_resources);
339 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
340 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
341 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
342 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
343 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
344 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
345 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
346 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
347 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
348 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
349 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
350 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
351 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
356 /* Catch new uses of the fields that are supposed to be zero */
358 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
359 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
360 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
361 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
362 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
363 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
364 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
365 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
366 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
369 * No need to scare people who are testing this, I am just
370 * labelling this as a LAMESPEC
372 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
380 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
382 guint32 offset, size;
388 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
389 if (offset == INVALID_ADDRESS)
392 size = iinfo->cli_cli_header.ch_metadata.size;
394 if (offset + size > image->raw_data_len)
396 image->raw_metadata = image->raw_data + offset;
398 /* 24.2.1: Metadata root starts here */
399 ptr = image->raw_metadata;
401 if (strncmp (ptr, "BSJB", 4) == 0){
402 guint32 version_string_len;
405 image->md_version_major = read16 (ptr);
407 image->md_version_minor = read16 (ptr);
410 version_string_len = read32 (ptr);
412 image->version = g_strndup (ptr, version_string_len);
413 ptr += version_string_len;
414 pad = ptr - image->raw_metadata;
416 ptr += 4 - (pad % 4);
420 /* skip over flags */
423 streams = read16 (ptr);
426 for (i = 0; i < streams; i++){
427 if (strncmp (ptr + 8, "#~", 3) == 0){
428 image->heap_tables.data = image->raw_metadata + read32 (ptr);
429 image->heap_tables.size = read32 (ptr + 4);
431 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
432 image->heap_strings.data = image->raw_metadata + read32 (ptr);
433 image->heap_strings.size = read32 (ptr + 4);
435 } else if (strncmp (ptr + 8, "#US", 4) == 0){
436 image->heap_us.data = image->raw_metadata + read32 (ptr);
437 image->heap_us.size = read32 (ptr + 4);
439 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
440 image->heap_blob.data = image->raw_metadata + read32 (ptr);
441 image->heap_blob.size = read32 (ptr + 4);
443 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
444 image->heap_guid.data = image->raw_metadata + read32 (ptr);
445 image->heap_guid.size = read32 (ptr + 4);
447 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
448 image->heap_tables.data = image->raw_metadata + read32 (ptr);
449 image->heap_tables.size = read32 (ptr + 4);
451 image->uncompressed_metadata = TRUE;
452 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);
454 g_message ("Unknown heap type: %s\n", ptr + 8);
455 ptr += 8 + strlen (ptr + 8) + 1;
457 pad = ptr - image->raw_metadata;
459 ptr += 4 - (pad % 4);
462 g_assert (image->heap_guid.data);
463 g_assert (image->heap_guid.size >= 16);
465 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
471 * Load representation of logical metadata tables, from the "#~" stream
474 load_tables (MonoImage *image)
476 const char *heap_tables = image->heap_tables.data;
479 int valid = 0, table;
482 heap_sizes = heap_tables [6];
483 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
484 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
485 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
487 valid_mask = read64 (heap_tables + 8);
488 rows = (const guint32 *) (heap_tables + 24);
490 for (table = 0; table < 64; table++){
491 if ((valid_mask & ((guint64) 1 << table)) == 0){
492 if (table > MONO_TABLE_LAST)
494 image->tables [table].rows = 0;
497 if (table > MONO_TABLE_LAST) {
498 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
500 image->tables [table].rows = read32 (rows);
506 image->tables_base = (heap_tables + 24) + (4 * valid);
508 /* They must be the same */
509 g_assert ((const void *) image->tables_base == (const void *) rows);
511 mono_metadata_compute_table_bases (image);
516 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
518 if (!load_metadata_ptrs (image, iinfo))
521 return load_tables (image);
525 mono_image_check_for_module_cctor (MonoImage *image)
527 MonoTableInfo *t, *mt;
528 t = &image->tables [MONO_TABLE_TYPEDEF];
529 mt = &image->tables [MONO_TABLE_METHOD];
530 if (image_is_dynamic (image)) {
532 image->checked_module_cctor = TRUE;
536 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
537 const char *name = mono_metadata_string_heap (image, nameidx);
538 if (strcmp (name, "<Module>") == 0) {
539 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
542 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
544 last_method = mt->rows;
545 for (; first_method < last_method; first_method++) {
546 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
547 name = mono_metadata_string_heap (image, nameidx);
548 if (strcmp (name, ".cctor") == 0) {
549 image->has_module_cctor = TRUE;
550 image->checked_module_cctor = TRUE;
556 image->has_module_cctor = FALSE;
557 image->checked_module_cctor = TRUE;
561 load_modules (MonoImage *image)
568 t = &image->tables [MONO_TABLE_MODULEREF];
569 image->modules = g_new0 (MonoImage *, t->rows);
570 image->modules_loaded = g_new0 (gboolean, t->rows);
571 image->module_count = t->rows;
575 * mono_image_load_module:
577 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
578 * it cannot be loaded.
581 mono_image_load_module (MonoImage *image, int idx)
584 MonoTableInfo *file_table;
587 gboolean refonly = image->ref_only;
588 GList *list_iter, *valid_modules = NULL;
589 MonoImageOpenStatus status;
591 if ((image->module_count == 0) || (idx > image->module_count || idx <= 0))
593 if (image->modules_loaded [idx - 1])
594 return image->modules [idx - 1];
596 file_table = &image->tables [MONO_TABLE_FILE];
597 for (i = 0; i < file_table->rows; i++) {
598 guint32 cols [MONO_FILE_SIZE];
599 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
600 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
602 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
605 t = &image->tables [MONO_TABLE_MODULEREF];
606 base_dir = g_path_get_dirname (image->name);
611 guint32 cols [MONO_MODULEREF_SIZE];
612 /* if there is no file table, we try to load the module... */
613 int valid = file_table->rows == 0;
615 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
616 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
617 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
618 /* be safe with string dups, but we could just compare string indexes */
619 if (strcmp (list_iter->data, name) == 0) {
625 module_ref = g_build_filename (base_dir, name, NULL);
626 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
627 if (image->modules [idx - 1]) {
628 mono_image_addref (image->modules [idx - 1]);
629 image->modules [idx - 1]->assembly = image->assembly;
631 if (image->modules [idx - 1]->is_module_handle)
632 mono_image_fixup_vtable (image->modules [idx - 1]);
634 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
640 image->modules_loaded [idx - 1] = TRUE;
643 g_list_free (valid_modules);
645 return image->modules [idx - 1];
649 class_key_extract (gpointer value)
651 MonoClass *class = value;
653 return GUINT_TO_POINTER (class->type_token);
657 class_next_value (gpointer value)
659 MonoClass *class = value;
661 return (gpointer*)&class->next_class_cache;
665 mono_image_init (MonoImage *image)
667 mono_mutex_init_recursive (&image->lock);
668 mono_mutex_init_recursive (&image->szarray_cache_lock);
670 image->mempool = mono_mempool_new_size (512);
671 mono_internal_hash_table_init (&image->class_cache,
675 image->field_cache = mono_conc_hashtable_new (&image->lock, NULL, NULL);
677 image->typespec_cache = g_hash_table_new (NULL, NULL);
678 image->memberref_signatures = g_hash_table_new (NULL, NULL);
679 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
680 image->method_signatures = g_hash_table_new (NULL, NULL);
682 image->property_hash = mono_property_hash_new ();
685 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
686 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
687 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
688 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
689 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
698 * Returns < 0 to indicate an error.
701 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
703 MonoDotNetHeader64 header64;
706 if (!image->is_module_handle)
708 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
711 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
713 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
716 /* endian swap the fields common between PE and PE+ */
717 SWAP32 (header->coff.coff_time);
718 SWAP32 (header->coff.coff_symptr);
719 SWAP32 (header->coff.coff_symcount);
720 SWAP16 (header->coff.coff_machine);
721 SWAP16 (header->coff.coff_sections);
722 SWAP16 (header->coff.coff_opt_header_size);
723 SWAP16 (header->coff.coff_attributes);
725 SWAP32 (header->pe.pe_code_size);
726 SWAP32 (header->pe.pe_uninit_data_size);
727 SWAP32 (header->pe.pe_rva_entry_point);
728 SWAP32 (header->pe.pe_rva_code_base);
729 SWAP32 (header->pe.pe_rva_data_base);
730 SWAP16 (header->pe.pe_magic);
732 /* now we are ready for the basic tests */
734 if (header->pe.pe_magic == 0x10B) {
735 offset += sizeof (MonoDotNetHeader);
736 SWAP32 (header->pe.pe_data_size);
737 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
740 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
741 SWAP32 (header->nt.pe_stack_reserve);
742 SWAP32 (header->nt.pe_stack_commit);
743 SWAP32 (header->nt.pe_heap_reserve);
744 SWAP32 (header->nt.pe_heap_commit);
745 } else if (header->pe.pe_magic == 0x20B) {
746 /* PE32+ file format */
747 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
749 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
750 offset += sizeof (MonoDotNetHeader64);
751 /* copy the fields already swapped. the last field, pe_data_size, is missing */
752 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
753 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
754 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
756 SWAP64 (header64.nt.pe_image_base);
757 header->nt.pe_image_base = header64.nt.pe_image_base;
758 SWAP64 (header64.nt.pe_stack_reserve);
759 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
760 SWAP64 (header64.nt.pe_stack_commit);
761 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
762 SWAP64 (header64.nt.pe_heap_reserve);
763 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
764 SWAP64 (header64.nt.pe_heap_commit);
765 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
767 header->nt.pe_section_align = header64.nt.pe_section_align;
768 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
769 header->nt.pe_os_major = header64.nt.pe_os_major;
770 header->nt.pe_os_minor = header64.nt.pe_os_minor;
771 header->nt.pe_user_major = header64.nt.pe_user_major;
772 header->nt.pe_user_minor = header64.nt.pe_user_minor;
773 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
774 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
775 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
776 header->nt.pe_image_size = header64.nt.pe_image_size;
777 header->nt.pe_header_size = header64.nt.pe_header_size;
778 header->nt.pe_checksum = header64.nt.pe_checksum;
779 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
780 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
781 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
782 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
784 /* copy the datadir */
785 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
790 /* MonoPEHeaderNT: not used yet */
791 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
792 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
793 SWAP16 (header->nt.pe_os_major); /* must be 4 */
794 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
795 SWAP16 (header->nt.pe_user_major);
796 SWAP16 (header->nt.pe_user_minor);
797 SWAP16 (header->nt.pe_subsys_major);
798 SWAP16 (header->nt.pe_subsys_minor);
799 SWAP32 (header->nt.pe_reserved_1);
800 SWAP32 (header->nt.pe_image_size);
801 SWAP32 (header->nt.pe_header_size);
802 SWAP32 (header->nt.pe_checksum);
803 SWAP16 (header->nt.pe_subsys_required);
804 SWAP16 (header->nt.pe_dll_flags);
805 SWAP32 (header->nt.pe_loader_flags);
806 SWAP32 (header->nt.pe_data_dir_count);
808 /* MonoDotNetHeader: mostly unused */
809 SWAPPDE (header->datadir.pe_export_table);
810 SWAPPDE (header->datadir.pe_import_table);
811 SWAPPDE (header->datadir.pe_resource_table);
812 SWAPPDE (header->datadir.pe_exception_table);
813 SWAPPDE (header->datadir.pe_certificate_table);
814 SWAPPDE (header->datadir.pe_reloc_table);
815 SWAPPDE (header->datadir.pe_debug);
816 SWAPPDE (header->datadir.pe_copyright);
817 SWAPPDE (header->datadir.pe_global_ptr);
818 SWAPPDE (header->datadir.pe_tls_table);
819 SWAPPDE (header->datadir.pe_load_config_table);
820 SWAPPDE (header->datadir.pe_bound_import);
821 SWAPPDE (header->datadir.pe_iat);
822 SWAPPDE (header->datadir.pe_delay_import_desc);
823 SWAPPDE (header->datadir.pe_cli_header);
824 SWAPPDE (header->datadir.pe_reserved);
827 if (image->is_module_handle)
828 image->raw_data_len = header->nt.pe_image_size;
835 mono_image_load_pe_data (MonoImage *image)
837 MonoCLIImageInfo *iinfo;
838 MonoDotNetHeader *header;
839 MonoMSDOSHeader msdos;
842 iinfo = image->image_info;
843 header = &iinfo->cli_header;
846 if (!image->is_module_handle)
848 if (offset + sizeof (msdos) > image->raw_data_len)
850 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
852 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
855 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
857 offset = msdos.pe_offset;
859 offset = do_load_header (image, header, offset);
864 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
866 if (header->coff.coff_machine != 0x14c)
872 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
873 * which produces binaries with 7.0. From Sergey:
875 * The reason is that MSVC7 uses traditional compile/link
876 * sequence for CIL executables, and VS.NET (and Framework
877 * SDK) includes linker version 7, that puts 7.0 in this
878 * field. That's why it's currently not possible to load VC
879 * binaries with Mono. This field is pretty much meaningless
880 * anyway (what linker?).
882 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
887 * FIXME: byte swap all addresses here for header.
890 if (!load_section_tables (image, iinfo, offset))
900 mono_image_load_cli_data (MonoImage *image)
902 MonoCLIImageInfo *iinfo;
904 iinfo = image->image_info;
906 /* Load the CLI header */
907 if (!load_cli_header (image, iinfo))
910 if (!load_metadata (image, iinfo))
917 mono_image_load_names (MonoImage *image)
919 /* modules don't have an assembly table row */
920 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
921 image->assembly_name = mono_metadata_string_heap (image,
922 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
923 0, MONO_ASSEMBLY_NAME));
926 image->module_name = mono_metadata_string_heap (image,
927 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
928 0, MONO_MODULE_NAME));
932 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
933 gboolean care_about_cli, gboolean care_about_pecoff)
935 MonoCLIImageInfo *iinfo;
936 MonoDotNetHeader *header;
937 GSList *errors = NULL;
939 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
941 mono_image_init (image);
943 iinfo = image->image_info;
944 header = &iinfo->cli_header;
947 *status = MONO_IMAGE_IMAGE_INVALID;
949 if (care_about_pecoff == FALSE)
952 if (!mono_verifier_verify_pe_data (image, &errors))
955 if (!mono_image_load_pe_data (image))
958 if (care_about_cli == FALSE) {
962 if (!mono_verifier_verify_cli_data (image, &errors))
965 if (!mono_image_load_cli_data (image))
968 if (!mono_verifier_verify_table_data (image, &errors))
971 mono_image_load_names (image);
973 load_modules (image);
976 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
978 *status = MONO_IMAGE_OK;
984 MonoVerifyInfo *info = errors->data;
985 g_warning ("Could not load image %s due to %s", image->name, info->message);
986 mono_free_verify_list (errors);
988 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
989 mono_image_close (image);
994 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
995 gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
997 MonoCLIImageInfo *iinfo;
1001 if ((filed = mono_file_map_open (fname)) == NULL){
1002 if (IS_PORTABILITY_SET) {
1003 gchar *ffname = mono_portability_find_file (fname, TRUE);
1005 filed = mono_file_map_open (ffname);
1010 if (filed == NULL) {
1012 *status = MONO_IMAGE_ERROR_ERRNO;
1017 image = g_new0 (MonoImage, 1);
1018 image->raw_buffer_used = TRUE;
1019 image->raw_data_len = mono_file_map_size (filed);
1020 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);
1021 #if defined(HAVE_MMAP) && !defined (HOST_WIN32)
1022 if (!image->raw_data) {
1023 image->fileio_used = TRUE;
1024 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);
1027 if (!image->raw_data) {
1028 mono_file_map_close (filed);
1031 *status = MONO_IMAGE_IMAGE_INVALID;
1034 iinfo = g_new0 (MonoCLIImageInfo, 1);
1035 image->image_info = iinfo;
1036 image->name = mono_path_resolve_symlinks (fname);
1037 image->ref_only = refonly;
1038 image->ref_count = 1;
1039 /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
1040 image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
1042 mono_file_map_close (filed);
1043 return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
1047 mono_image_loaded_full (const char *name, gboolean refonly)
1050 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1052 mono_images_lock ();
1053 res = g_hash_table_lookup (loaded_images, name);
1054 mono_images_unlock ();
1059 * mono_image_loaded:
1060 * @name: name of the image to load
1062 * This routine ensures that the given image is loaded.
1064 * Returns: the loaded MonoImage, or NULL on failure.
1067 mono_image_loaded (const char *name)
1069 return mono_image_loaded_full (name, FALSE);
1078 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1080 GuidData *data = user_data;
1086 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1091 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1094 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1098 mono_images_lock ();
1099 g_hash_table_foreach (loaded_images, find_by_guid, &data);
1100 mono_images_unlock ();
1105 mono_image_loaded_by_guid (const char *guid)
1107 return mono_image_loaded_by_guid_full (guid, FALSE);
1111 register_image (MonoImage *image)
1114 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1116 mono_images_lock ();
1117 image2 = g_hash_table_lookup (loaded_images, image->name);
1120 /* Somebody else beat us to it */
1121 mono_image_addref (image2);
1122 mono_images_unlock ();
1123 mono_image_close (image);
1126 g_hash_table_insert (loaded_images, image->name, image);
1127 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1128 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1129 mono_images_unlock ();
1135 mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
1137 MonoCLIImageInfo *iinfo;
1141 if (!data || !data_len) {
1143 *status = MONO_IMAGE_IMAGE_INVALID;
1148 datac = g_try_malloc (data_len);
1151 *status = MONO_IMAGE_ERROR_ERRNO;
1154 memcpy (datac, data, data_len);
1157 image = g_new0 (MonoImage, 1);
1158 image->raw_data = datac;
1159 image->raw_data_len = data_len;
1160 image->raw_data_allocated = need_copy;
1161 image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup(name);
1162 iinfo = g_new0 (MonoCLIImageInfo, 1);
1163 image->image_info = iinfo;
1164 image->ref_only = refonly;
1166 image = do_mono_image_load (image, status, TRUE, TRUE);
1170 return register_image (image);
1174 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1176 return mono_image_open_from_data_with_name (data, data_len, need_copy, status, refonly, NULL);
1180 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1182 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1186 /* fname is not duplicated. */
1188 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1191 MonoCLIImageInfo* iinfo;
1193 image = g_new0 (MonoImage, 1);
1194 image->raw_data = (char*) module_handle;
1195 image->is_module_handle = TRUE;
1196 iinfo = g_new0 (MonoCLIImageInfo, 1);
1197 image->image_info = iinfo;
1198 image->name = fname;
1199 image->ref_count = has_entry_point ? 0 : 1;
1200 image->has_entry_point = has_entry_point;
1202 image = do_mono_image_load (image, status, TRUE, TRUE);
1206 return register_image (image);
1211 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1214 GHashTable *loaded_images;
1217 g_return_val_if_fail (fname != NULL, NULL);
1220 /* Load modules using LoadLibrary. */
1221 if (!refonly && coree_module_handle) {
1222 HMODULE module_handle;
1223 guint16 *fname_utf16;
1226 absfname = mono_path_resolve_symlinks (fname);
1229 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1230 mono_images_lock ();
1231 image = g_hash_table_lookup (loaded_images_hash, absfname);
1233 g_assert (image->is_module_handle);
1234 if (image->has_entry_point && image->ref_count == 0) {
1235 /* Increment reference count on images loaded outside of the runtime. */
1236 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1237 /* The image is already loaded because _CorDllMain removes images from the hash. */
1238 module_handle = LoadLibrary (fname_utf16);
1239 g_assert (module_handle == (HMODULE) image->raw_data);
1241 mono_image_addref (image);
1242 mono_images_unlock ();
1244 g_free (fname_utf16);
1249 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1250 module_handle = MonoLoadImage (fname_utf16);
1251 if (status && module_handle == NULL)
1252 last_error = GetLastError ();
1254 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1255 image = g_hash_table_lookup (loaded_images_hash, absfname);
1257 mono_image_addref (image);
1258 mono_images_unlock ();
1260 g_free (fname_utf16);
1262 if (module_handle == NULL) {
1266 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1267 *status = MONO_IMAGE_IMAGE_INVALID;
1269 if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND)
1279 g_assert (image->is_module_handle);
1280 g_assert (image->has_entry_point);
1285 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1289 absfname = mono_path_canonicalize (fname);
1292 * The easiest solution would be to do all the loading inside the mutex,
1293 * but that would lead to scalability problems. So we let the loading
1294 * happen outside the mutex, and if multiple threads happen to load
1295 * the same image, we discard all but the first copy.
1297 mono_images_lock ();
1298 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1299 image = g_hash_table_lookup (loaded_images, absfname);
1303 mono_image_addref (image);
1304 mono_images_unlock ();
1307 mono_images_unlock ();
1309 image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1313 return register_image (image);
1318 * @fname: filename that points to the module we want to open
1319 * @status: An error condition is returned in this field
1321 * Returns: An open image of type %MonoImage or NULL on error.
1322 * The caller holds a temporary reference to the returned image which should be cleared
1323 * when no longer needed by calling mono_image_close ().
1324 * if NULL, then check the value of @status for details on the error
1327 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1329 return mono_image_open_full (fname, status, FALSE);
1333 * mono_pe_file_open:
1334 * @fname: filename that points to the module we want to open
1335 * @status: An error condition is returned in this field
1337 * Returns: An open image of type %MonoImage or NULL on error. if
1338 * NULL, then check the value of @status for details on the error.
1339 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1340 * It's just a PE file loader, used for FileVersionInfo. It also does
1341 * not use the image cache.
1344 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1346 g_return_val_if_fail (fname != NULL, NULL);
1348 return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1352 * mono_image_open_raw
1353 * @fname: filename that points to the module we want to open
1354 * @status: An error condition is returned in this field
1356 * Returns an image without loading neither pe or cli data.
1358 * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
1361 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1363 g_return_val_if_fail (fname != NULL, NULL);
1365 return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1369 mono_image_fixup_vtable (MonoImage *image)
1372 MonoCLIImageInfo *iinfo;
1374 MonoVTableFixup *vtfixup;
1380 g_assert (image->is_module_handle);
1382 iinfo = image->image_info;
1383 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1384 if (!de->rva || !de->size)
1386 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1390 count = de->size / sizeof (MonoVTableFixup);
1392 if (!vtfixup->rva || !vtfixup->count)
1395 slot = mono_image_rva_map (image, vtfixup->rva);
1397 slot_type = vtfixup->type;
1398 slot_count = vtfixup->count;
1399 if (slot_type & VTFIXUP_TYPE_32BIT)
1400 while (slot_count--) {
1401 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1402 slot = ((guint32*) slot) + 1;
1404 else if (slot_type & VTFIXUP_TYPE_64BIT)
1405 while (slot_count--) {
1406 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1407 slot = ((guint32*) slot) + 1;
1410 g_assert_not_reached();
1415 g_assert_not_reached();
1420 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1422 g_hash_table_destroy ((GHashTable*)val);
1427 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1429 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1434 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1436 g_slist_free ((GSList*)val);
1440 * mono_image_addref:
1441 * @image: The image file we wish to add a reference to
1443 * Increases the reference count of an image.
1446 mono_image_addref (MonoImage *image)
1448 InterlockedIncrement (&image->ref_count);
1452 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1454 stream->alloc_size = stream->index = stream->offset = 0;
1455 g_free (stream->data);
1456 stream->data = NULL;
1458 g_hash_table_destroy (stream->hash);
1459 stream->hash = NULL;
1464 free_hash (GHashTable *hash)
1467 g_hash_table_destroy (hash);
1471 * Returns whether mono_image_close_finish() must be called as well.
1472 * We must unload images in two steps because clearing the domain in
1473 * SGen requires the class metadata to be intact, but we need to free
1474 * the mono_g_hash_tables in case a collection occurs during domain
1475 * unloading and the roots would trip up the GC.
1478 mono_image_close_except_pools (MonoImage *image)
1481 GHashTable *loaded_images;
1484 g_return_val_if_fail (image != NULL, FALSE);
1487 * Atomically decrement the refcount and remove ourselves from the hash tables, so
1488 * register_image () can't grab an image which is being closed.
1490 mono_images_lock ();
1492 if (InterlockedDecrement (&image->ref_count) > 0) {
1493 mono_images_unlock ();
1497 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1498 image2 = g_hash_table_lookup (loaded_images, image->name);
1499 if (image == image2) {
1500 /* This is not true if we are called from mono_image_open () */
1501 g_hash_table_remove (loaded_images, image->name);
1503 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1504 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1506 mono_images_unlock ();
1509 if (image->is_module_handle && image->has_entry_point) {
1510 mono_images_lock ();
1511 if (image->ref_count == 0) {
1512 /* Image will be closed by _CorDllMain. */
1513 FreeLibrary ((HMODULE) image->raw_data);
1514 mono_images_unlock ();
1517 mono_images_unlock ();
1521 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1523 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1525 mono_image_invoke_unload_hook (image);
1527 mono_metadata_clean_for_image (image);
1530 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1531 * assemblies, so we can't release these references in mono_assembly_close () since the
1532 * MonoImage might outlive its associated MonoAssembly.
1534 if (image->references && !image_is_dynamic (image)) {
1535 for (i = 0; i < image->nreferences; i++) {
1536 if (image->references [i] && image->references [i] != REFERENCE_MISSING) {
1537 if (!mono_assembly_close_except_image_pools (image->references [i]))
1538 image->references [i] = NULL;
1542 if (image->references) {
1543 g_free (image->references);
1544 image->references = NULL;
1549 mono_images_lock ();
1550 if (image->is_module_handle && !image->has_entry_point)
1551 FreeLibrary ((HMODULE) image->raw_data);
1552 mono_images_unlock ();
1555 if (image->raw_buffer_used) {
1556 if (image->raw_data != NULL) {
1558 if (image->fileio_used)
1559 mono_file_unmap_fileio (image->raw_data, image->raw_data_handle);
1562 mono_file_unmap (image->raw_data, image->raw_data_handle);
1566 if (image->raw_data_allocated) {
1567 /* FIXME: do we need this? (image is disposed anyway) */
1568 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1569 MonoCLIImageInfo *ii = image->image_info;
1571 if ((image->raw_metadata > image->raw_data) &&
1572 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1573 image->raw_metadata = NULL;
1575 for (i = 0; i < ii->cli_section_count; i++)
1576 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1577 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1578 ii->cli_sections [i] = NULL;
1580 g_free (image->raw_data);
1583 if (debug_assembly_unload) {
1584 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1586 g_free (image->name);
1587 g_free (image->guid);
1588 g_free (image->version);
1589 g_free (image->files);
1592 if (image->method_cache)
1593 g_hash_table_destroy (image->method_cache);
1594 if (image->methodref_cache)
1595 g_hash_table_destroy (image->methodref_cache);
1596 mono_internal_hash_table_destroy (&image->class_cache);
1597 mono_conc_hashtable_destroy (image->field_cache);
1598 if (image->array_cache) {
1599 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1600 g_hash_table_destroy (image->array_cache);
1602 if (image->szarray_cache)
1603 g_hash_table_destroy (image->szarray_cache);
1604 if (image->ptr_cache)
1605 g_hash_table_destroy (image->ptr_cache);
1606 if (image->name_cache) {
1607 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1608 g_hash_table_destroy (image->name_cache);
1611 free_hash (image->native_wrapper_cache);
1612 free_hash (image->native_func_wrapper_cache);
1613 free_hash (image->managed_wrapper_cache);
1614 free_hash (image->delegate_begin_invoke_cache);
1615 free_hash (image->delegate_end_invoke_cache);
1616 free_hash (image->delegate_invoke_cache);
1617 free_hash (image->delegate_abstract_invoke_cache);
1618 free_hash (image->delegate_bound_static_invoke_cache);
1619 free_hash (image->delegate_invoke_generic_cache);
1620 free_hash (image->delegate_begin_invoke_generic_cache);
1621 free_hash (image->delegate_end_invoke_generic_cache);
1622 free_hash (image->synchronized_generic_cache);
1623 free_hash (image->remoting_invoke_cache);
1624 free_hash (image->runtime_invoke_cache);
1625 free_hash (image->runtime_invoke_vtype_cache);
1626 free_hash (image->runtime_invoke_direct_cache);
1627 free_hash (image->runtime_invoke_vcall_cache);
1628 free_hash (image->synchronized_cache);
1629 free_hash (image->unbox_wrapper_cache);
1630 free_hash (image->cominterop_invoke_cache);
1631 free_hash (image->cominterop_wrapper_cache);
1632 free_hash (image->typespec_cache);
1633 free_hash (image->ldfld_wrapper_cache);
1634 free_hash (image->ldflda_wrapper_cache);
1635 free_hash (image->stfld_wrapper_cache);
1636 free_hash (image->isinst_cache);
1637 free_hash (image->castclass_cache);
1638 free_hash (image->proxy_isinst_cache);
1639 free_hash (image->thunk_invoke_cache);
1640 free_hash (image->var_cache_slow);
1641 free_hash (image->mvar_cache_slow);
1642 free_hash (image->wrapper_param_names);
1643 free_hash (image->native_wrapper_aot_cache);
1644 free_hash (image->pinvoke_scopes);
1645 free_hash (image->pinvoke_scope_filenames);
1646 for (i = 0; i < image->gshared_types_len; ++i)
1647 free_hash (image->gshared_types [i]);
1648 g_free (image->gshared_types);
1650 /* The ownership of signatures is not well defined */
1651 g_hash_table_destroy (image->memberref_signatures);
1652 g_hash_table_destroy (image->helper_signatures);
1653 g_hash_table_destroy (image->method_signatures);
1655 if (image->rgctx_template_hash)
1656 g_hash_table_destroy (image->rgctx_template_hash);
1658 if (image->property_hash)
1659 mono_property_hash_destroy (image->property_hash);
1662 reflection_info_unregister_classes is only required by dynamic images, which will not be properly
1663 cleared during shutdown as we don't perform regular appdomain unload for the root one.
1665 g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ());
1666 image->reflection_info_unregister_classes = NULL;
1668 if (image->interface_bitset) {
1669 mono_unload_interface_ids (image->interface_bitset);
1670 mono_bitset_free (image->interface_bitset);
1672 if (image->image_info){
1673 MonoCLIImageInfo *ii = image->image_info;
1675 if (ii->cli_section_tables)
1676 g_free (ii->cli_section_tables);
1677 if (ii->cli_sections)
1678 g_free (ii->cli_sections);
1679 g_free (image->image_info);
1682 for (i = 0; i < image->module_count; ++i) {
1683 if (image->modules [i]) {
1684 if (!mono_image_close_except_pools (image->modules [i]))
1685 image->modules [i] = NULL;
1688 if (image->modules_loaded)
1689 g_free (image->modules_loaded);
1691 mono_mutex_destroy (&image->szarray_cache_lock);
1692 mono_mutex_destroy (&image->lock);
1694 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1695 if (image_is_dynamic (image)) {
1696 /* Dynamic images are GC_MALLOCed */
1697 g_free ((char*)image->module_name);
1698 mono_dynamic_image_free ((MonoDynamicImage*)image);
1701 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1707 mono_image_close_finish (MonoImage *image)
1711 if (image->references && !image_is_dynamic (image)) {
1712 for (i = 0; i < image->nreferences; i++) {
1713 if (image->references [i] && image->references [i] != REFERENCE_MISSING)
1714 mono_assembly_close_finish (image->references [i]);
1717 g_free (image->references);
1718 image->references = NULL;
1721 for (i = 0; i < image->module_count; ++i) {
1722 if (image->modules [i])
1723 mono_image_close_finish (image->modules [i]);
1726 g_free (image->modules);
1728 #ifndef DISABLE_PERFCOUNTERS
1729 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1732 if (!image_is_dynamic (image)) {
1733 if (debug_assembly_unload)
1734 mono_mempool_invalidate (image->mempool);
1736 mono_mempool_destroy (image->mempool);
1740 if (debug_assembly_unload)
1741 mono_mempool_invalidate (image->mempool);
1743 mono_mempool_destroy (image->mempool);
1744 mono_dynamic_image_free_image ((MonoDynamicImage*)image);
1751 * @image: The image file we wish to close
1753 * Closes an image file, deallocates all memory consumed and
1754 * unmaps all possible sections of the file
1757 mono_image_close (MonoImage *image)
1759 if (mono_image_close_except_pools (image))
1760 mono_image_close_finish (image);
1764 * mono_image_strerror:
1765 * @status: an code indicating the result from a recent operation
1767 * Returns: a string describing the error
1770 mono_image_strerror (MonoImageOpenStatus status)
1775 case MONO_IMAGE_ERROR_ERRNO:
1776 return strerror (errno);
1777 case MONO_IMAGE_IMAGE_INVALID:
1778 return "File does not contain a valid CIL image";
1779 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1780 return "An assembly was referenced, but could not be found";
1782 return "Internal error";
1786 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1787 guint32 lang_id, gunichar2 *name,
1788 MonoPEResourceDirEntry *entry,
1789 MonoPEResourceDir *root, guint32 level)
1791 gboolean is_string, is_dir;
1792 guint32 name_offset, dir_offset;
1794 /* Level 0 holds a directory entry for each type of resource
1795 * (identified by ID or name).
1797 * Level 1 holds a directory entry for each named resource
1798 * item, and each "anonymous" item of a particular type of
1801 * Level 2 holds a directory entry for each language pointing to
1804 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1805 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1807 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1808 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1813 } else if (level==1) {
1814 if (res_id != name_offset)
1818 is_string==TRUE && name!=lookup (name_offset)) {
1822 } else if (level==2) {
1823 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1826 g_assert_not_reached ();
1830 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1831 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1834 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1836 for(i=0; i<entries; i++) {
1837 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1840 ret=mono_image_walk_resource_tree (info, res_id,
1851 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1852 MonoPEResourceDataEntry *res;
1854 res = g_new0 (MonoPEResourceDataEntry, 1);
1856 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1857 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1858 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1859 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1866 * mono_image_lookup_resource:
1867 * @image: the image to look up the resource in
1868 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1869 * @lang_id: The language id.
1870 * @name: the resource name to lookup.
1872 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1873 * of the given resource. The caller should free it using g_free () when no longer
1877 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1879 MonoCLIImageInfo *info;
1880 MonoDotNetHeader *header;
1881 MonoPEDatadir *datadir;
1882 MonoPEDirEntry *rsrc;
1883 MonoPEResourceDir *resource_dir;
1884 MonoPEResourceDirEntry *res_entries;
1891 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1893 info=image->image_info;
1898 header=&info->cli_header;
1903 datadir=&header->datadir;
1908 rsrc=&datadir->pe_resource_table;
1913 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1914 if(resource_dir==NULL) {
1918 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1919 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1921 for(i=0; i<entries; i++) {
1922 MonoPEResourceDirEntry *entry=&res_entries[i];
1925 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1926 name, entry, resource_dir,
1937 * mono_image_get_entry_point:
1938 * @image: the image where the entry point will be looked up.
1940 * Use this routine to determine the metadata token for method that
1941 * has been flagged as the entry point.
1943 * Returns: the token for the entry point method in the image
1946 mono_image_get_entry_point (MonoImage *image)
1948 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1952 * mono_image_get_resource:
1953 * @image: the image where the resource will be looked up.
1954 * @offset: The offset to add to the resource
1955 * @size: a pointer to an int where the size of the resource will be stored
1957 * This is a low-level routine that fetches a resource from the
1958 * metadata that starts at a given @offset. The @size parameter is
1959 * filled with the data field as encoded in the metadata.
1961 * Returns: the pointer to the resource whose offset is @offset.
1964 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1966 MonoCLIImageInfo *iinfo = image->image_info;
1967 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1970 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1973 data = mono_image_rva_map (image, ch->ch_resources.rva);
1978 *size = read32 (data);
1984 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1986 char *base_dir, *name;
1988 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1992 if (fileidx < 1 || fileidx > t->rows)
1995 mono_image_lock (image);
1996 if (image->files && image->files [fileidx - 1]) {
1997 mono_image_unlock (image);
1998 return image->files [fileidx - 1];
2001 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
2002 fname = mono_metadata_string_heap (image, fname_id);
2003 base_dir = g_path_get_dirname (image->name);
2004 name = g_build_filename (base_dir, fname, NULL);
2005 res = mono_image_open (name, NULL);
2009 mono_image_lock (image);
2010 if (image->files && image->files [fileidx - 1]) {
2011 MonoImage *old = res;
2012 res = image->files [fileidx - 1];
2013 mono_loader_unlock ();
2014 mono_image_close (old);
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;
2025 image->files = g_new0 (MonoImage*, t->rows);
2026 image->files [fileidx - 1] = res;
2027 mono_loader_unlock ();
2028 /* vtable fixup can't happen with the image lock held */
2030 if (res->is_module_handle)
2031 mono_image_fixup_vtable (res);
2042 * mono_image_get_strong_name:
2043 * @image: a MonoImage
2044 * @size: a guint32 pointer, or NULL.
2046 * If the image has a strong name, and @size is not NULL, the value
2047 * pointed to by size will have the size of the strong name.
2049 * Returns: NULL if the image does not have a strong name, or a
2050 * pointer to the public key.
2053 mono_image_get_strong_name (MonoImage *image, guint32 *size)
2055 MonoCLIImageInfo *iinfo = image->image_info;
2056 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2059 if (!de->size || !de->rva)
2061 data = mono_image_rva_map (image, de->rva);
2070 * mono_image_strong_name_position:
2071 * @image: a MonoImage
2072 * @size: a guint32 pointer, or NULL.
2074 * If the image has a strong name, and @size is not NULL, the value
2075 * pointed to by size will have the size of the strong name.
2077 * Returns: the position within the image file where the strong name
2081 mono_image_strong_name_position (MonoImage *image, guint32 *size)
2083 MonoCLIImageInfo *iinfo = image->image_info;
2084 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2089 if (!de->size || !de->rva)
2091 pos = mono_cli_rva_image_map (image, de->rva);
2092 return pos == INVALID_ADDRESS ? 0 : pos;
2096 * mono_image_get_public_key:
2097 * @image: a MonoImage
2098 * @size: a guint32 pointer, or NULL.
2100 * This is used to obtain the public key in the @image.
2102 * If the image has a public key, and @size is not NULL, the value
2103 * pointed to by size will have the size of the public key.
2105 * Returns: NULL if the image does not have a public key, or a pointer
2106 * to the public key.
2109 mono_image_get_public_key (MonoImage *image, guint32 *size)
2114 if (image_is_dynamic (image)) {
2116 *size = ((MonoDynamicImage*)image)->public_key_len;
2117 return (char*)((MonoDynamicImage*)image)->public_key;
2119 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
2121 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
2124 pubkey = mono_metadata_blob_heap (image, tok);
2125 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
2132 * mono_image_get_name:
2133 * @name: a MonoImage
2135 * Returns: the name of the assembly.
2138 mono_image_get_name (MonoImage *image)
2140 return image->assembly_name;
2144 * mono_image_get_filename:
2145 * @image: a MonoImage
2147 * Used to get the filename that hold the actual MonoImage
2149 * Returns: the filename.
2152 mono_image_get_filename (MonoImage *image)
2158 mono_image_get_guid (MonoImage *image)
2163 const MonoTableInfo*
2164 mono_image_get_table_info (MonoImage *image, int table_id)
2166 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2168 return &image->tables [table_id];
2172 mono_image_get_table_rows (MonoImage *image, int table_id)
2174 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2176 return image->tables [table_id].rows;
2180 mono_table_info_get_rows (const MonoTableInfo *table)
2186 * mono_image_get_assembly:
2187 * @image: the MonoImage.
2189 * Use this routine to get the assembly that owns this image.
2191 * Returns: the assembly that holds this image.
2194 mono_image_get_assembly (MonoImage *image)
2196 return image->assembly;
2200 * mono_image_is_dynamic:
2201 * @image: the MonoImage
2203 * Determines if the given image was created dynamically through the
2204 * System.Reflection.Emit API
2206 * Returns: TRUE if the image was created dynamically, FALSE if not.
2209 mono_image_is_dynamic (MonoImage *image)
2211 return image_is_dynamic (image);
2215 * mono_image_has_authenticode_entry:
2216 * @image: the MonoImage
2218 * Use this routine to determine if the image has a Authenticode
2219 * Certificate Table.
2221 * Returns: TRUE if the image contains an authenticode entry in the PE
2225 mono_image_has_authenticode_entry (MonoImage *image)
2227 MonoCLIImageInfo *iinfo = image->image_info;
2228 MonoDotNetHeader *header = &iinfo->cli_header;
2229 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2230 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2231 return ((de->rva != 0) && (de->size > 8));
2235 mono_image_alloc (MonoImage *image, guint size)
2239 #ifndef DISABLE_PERFCOUNTERS
2240 mono_perfcounters->loader_bytes += size;
2242 mono_image_lock (image);
2243 res = mono_mempool_alloc (image->mempool, size);
2244 mono_image_unlock (image);
2250 mono_image_alloc0 (MonoImage *image, guint size)
2254 #ifndef DISABLE_PERFCOUNTERS
2255 mono_perfcounters->loader_bytes += size;
2257 mono_image_lock (image);
2258 res = mono_mempool_alloc0 (image->mempool, size);
2259 mono_image_unlock (image);
2265 mono_image_strdup (MonoImage *image, const char *s)
2269 #ifndef DISABLE_PERFCOUNTERS
2270 mono_perfcounters->loader_bytes += strlen (s);
2272 mono_image_lock (image);
2273 res = mono_mempool_strdup (image->mempool, s);
2274 mono_image_unlock (image);
2280 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2284 new_list = mono_image_alloc (image, sizeof (GList));
2285 new_list->data = data;
2286 new_list->prev = list ? list->prev : NULL;
2287 new_list->next = list;
2290 new_list->prev->next = new_list;
2292 list->prev = new_list;
2298 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2302 new_list = mono_image_alloc (image, sizeof (GSList));
2303 new_list->data = data;
2304 new_list->next = NULL;
2306 return g_slist_concat (list, new_list);
2310 mono_image_lock (MonoImage *image)
2312 mono_locks_acquire (&image->lock, ImageDataLock);
2316 mono_image_unlock (MonoImage *image)
2318 mono_locks_release (&image->lock, ImageDataLock);
2323 * mono_image_property_lookup:
2325 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2327 * LOCKING: Takes the image lock
2330 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2334 mono_image_lock (image);
2335 res = mono_property_hash_lookup (image->property_hash, subject, property);
2336 mono_image_unlock (image);
2342 * mono_image_property_insert:
2344 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2346 * LOCKING: Takes the image lock
2349 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2351 mono_image_lock (image);
2352 mono_property_hash_insert (image->property_hash, subject, property, value);
2353 mono_image_unlock (image);
2357 * mono_image_property_remove:
2359 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2361 * LOCKING: Takes the image lock
2364 mono_image_property_remove (MonoImage *image, gpointer subject)
2366 mono_image_lock (image);
2367 mono_property_hash_remove_object (image->property_hash, subject);
2368 mono_image_unlock (image);
2372 mono_image_append_class_to_reflection_info_set (MonoClass *class)
2374 MonoImage *image = class->image;
2375 g_assert (image_is_dynamic (image));
2376 mono_image_lock (image);
2377 image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, class);
2378 mono_image_unlock (image);