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/metadata/class-internals.h>
35 #include <mono/metadata/assembly.h>
36 #include <mono/metadata/object-internals.h>
37 #include <mono/metadata/security-core-clr.h>
38 #include <mono/metadata/verify-internals.h>
39 #include <sys/types.h>
45 #define INVALID_ADDRESS 0xffffffff
48 * Keeps track of the various assemblies loaded
50 static GHashTable *loaded_images_hash;
51 static GHashTable *loaded_images_refonly_hash;
53 static gboolean debug_assembly_unload = FALSE;
55 #define mono_images_lock() if (mutex_inited) EnterCriticalSection (&images_mutex)
56 #define mono_images_unlock() if (mutex_inited) LeaveCriticalSection (&images_mutex)
57 static gboolean mutex_inited;
58 static CRITICAL_SECTION images_mutex;
60 typedef struct ImageUnloadHook ImageUnloadHook;
61 struct ImageUnloadHook {
62 ImageUnloadHook *next;
63 MonoImageUnloadFunc func;
67 ImageUnloadHook *image_unload_hook = NULL;
70 mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
72 ImageUnloadHook *hook;
74 g_return_if_fail (func != NULL);
76 hook = g_new0 (ImageUnloadHook, 1);
78 hook->user_data = user_data;
79 hook->next = image_unload_hook;
80 image_unload_hook = hook;
84 mono_image_invoke_unload_hook (MonoImage *image)
86 ImageUnloadHook *hook;
88 for (hook = image_unload_hook; hook; hook = hook->next) {
89 hook->func (image, hook->user_data);
93 /* returns offset relative to image->raw_data */
95 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
97 MonoCLIImageInfo *iinfo = image->image_info;
98 const int top = iinfo->cli_section_count;
99 MonoSectionTable *tables = iinfo->cli_section_tables;
102 for (i = 0; i < top; i++){
103 if ((addr >= tables->st_virtual_address) &&
104 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
106 if (image->is_module_handle)
109 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
113 return INVALID_ADDRESS;
117 * mono_images_rva_map:
118 * @image: a MonoImage
119 * @addr: relative virtual address (RVA)
121 * This is a low-level routine used by the runtime to map relative
122 * virtual address (RVA) into their location in memory.
124 * Returns: the address in memory for the given RVA, or NULL if the
125 * RVA is not valid for this image.
128 mono_image_rva_map (MonoImage *image, guint32 addr)
130 MonoCLIImageInfo *iinfo = image->image_info;
131 const int top = iinfo->cli_section_count;
132 MonoSectionTable *tables = iinfo->cli_section_tables;
135 for (i = 0; i < top; i++){
136 if ((addr >= tables->st_virtual_address) &&
137 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
138 if (!iinfo->cli_sections [i]) {
139 if (!mono_image_ensure_section_idx (image, i))
143 if (image->is_module_handle)
144 return image->raw_data + addr;
146 return (char*)iinfo->cli_sections [i] +
147 (addr - tables->st_virtual_address);
157 * Initialize the global variables used by this module.
160 mono_images_init (void)
162 InitializeCriticalSection (&images_mutex);
164 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
165 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
167 debug_assembly_unload = g_getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
173 * mono_images_cleanup:
175 * Free all resources used by this module.
178 mono_images_cleanup (void)
180 DeleteCriticalSection (&images_mutex);
182 g_hash_table_destroy (loaded_images_hash);
183 g_hash_table_destroy (loaded_images_refonly_hash);
185 mutex_inited = FALSE;
189 * mono_image_ensure_section_idx:
190 * @image: The image we are operating on
191 * @section: section number that we will load/map into memory
193 * This routine makes sure that we have an in-memory copy of
194 * an image section (.text, .rsrc, .data).
196 * Returns: TRUE on success
199 mono_image_ensure_section_idx (MonoImage *image, int section)
201 MonoCLIImageInfo *iinfo = image->image_info;
202 MonoSectionTable *sect;
205 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
207 if (iinfo->cli_sections [section] != NULL)
210 sect = &iinfo->cli_section_tables [section];
212 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
214 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
217 if (image->is_module_handle)
218 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
221 /* FIXME: we ignore the writable flag since we don't patch the binary */
222 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
227 * mono_image_ensure_section:
228 * @image: The image we are operating on
229 * @section: section name that we will load/map into memory
231 * This routine makes sure that we have an in-memory copy of
232 * an image section (.text, .rsrc, .data).
234 * Returns: TRUE on success
237 mono_image_ensure_section (MonoImage *image, const char *section)
239 MonoCLIImageInfo *ii = image->image_info;
242 for (i = 0; i < ii->cli_section_count; i++){
243 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
246 return mono_image_ensure_section_idx (image, i);
252 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
254 const int top = iinfo->cli_header.coff.coff_sections;
257 iinfo->cli_section_count = top;
258 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
259 iinfo->cli_sections = g_new0 (void *, top);
261 for (i = 0; i < top; i++){
262 MonoSectionTable *t = &iinfo->cli_section_tables [i];
264 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
266 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
267 offset += sizeof (MonoSectionTable);
269 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
270 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
271 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
272 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
273 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
274 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
275 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
276 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
277 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
278 t->st_flags = GUINT32_FROM_LE (t->st_flags);
280 /* consistency checks here */
287 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
291 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
292 if (offset == INVALID_ADDRESS)
295 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
297 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
299 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
300 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
301 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
302 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
303 SWAP32 (iinfo->cli_cli_header.ch_size);
304 SWAP32 (iinfo->cli_cli_header.ch_flags);
305 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
306 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
307 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
308 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
309 SWAPPDE (iinfo->cli_cli_header.ch_resources);
310 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
311 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
312 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
313 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
314 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
315 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
316 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
317 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
318 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
319 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
320 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
321 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
322 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
327 /* Catch new uses of the fields that are supposed to be zero */
329 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
330 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
331 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
332 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
333 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
334 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
335 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
336 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
337 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
340 * No need to scare people who are testing this, I am just
341 * labelling this as a LAMESPEC
343 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
351 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
353 guint32 offset, size;
359 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
360 if (offset == INVALID_ADDRESS)
363 size = iinfo->cli_cli_header.ch_metadata.size;
365 if (offset + size > image->raw_data_len)
367 image->raw_metadata = image->raw_data + offset;
369 /* 24.2.1: Metadata root starts here */
370 ptr = image->raw_metadata;
372 if (strncmp (ptr, "BSJB", 4) == 0){
373 guint32 version_string_len;
376 image->md_version_major = read16 (ptr);
378 image->md_version_minor = read16 (ptr);
381 version_string_len = read32 (ptr);
383 image->version = g_strndup (ptr, version_string_len);
384 ptr += version_string_len;
385 pad = ptr - image->raw_metadata;
387 ptr += 4 - (pad % 4);
391 /* skip over flags */
394 streams = read16 (ptr);
397 for (i = 0; i < streams; i++){
398 if (strncmp (ptr + 8, "#~", 3) == 0){
399 image->heap_tables.data = image->raw_metadata + read32 (ptr);
400 image->heap_tables.size = read32 (ptr + 4);
402 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
403 image->heap_strings.data = image->raw_metadata + read32 (ptr);
404 image->heap_strings.size = read32 (ptr + 4);
406 } else if (strncmp (ptr + 8, "#US", 4) == 0){
407 image->heap_us.data = image->raw_metadata + read32 (ptr);
408 image->heap_us.size = read32 (ptr + 4);
410 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
411 image->heap_blob.data = image->raw_metadata + read32 (ptr);
412 image->heap_blob.size = read32 (ptr + 4);
414 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
415 image->heap_guid.data = image->raw_metadata + read32 (ptr);
416 image->heap_guid.size = read32 (ptr + 4);
418 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
419 image->heap_tables.data = image->raw_metadata + read32 (ptr);
420 image->heap_tables.size = read32 (ptr + 4);
422 image->uncompressed_metadata = TRUE;
423 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);
425 g_message ("Unknown heap type: %s\n", ptr + 8);
426 ptr += 8 + strlen (ptr + 8) + 1;
428 pad = ptr - image->raw_metadata;
430 ptr += 4 - (pad % 4);
433 g_assert (image->heap_guid.data);
434 g_assert (image->heap_guid.size >= 16);
436 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
442 * Load representation of logical metadata tables, from the "#~" stream
445 load_tables (MonoImage *image)
447 const char *heap_tables = image->heap_tables.data;
449 guint64 valid_mask, sorted_mask;
450 int valid = 0, table;
453 heap_sizes = heap_tables [6];
454 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
455 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
456 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
458 valid_mask = read64 (heap_tables + 8);
459 sorted_mask = read64 (heap_tables + 16);
460 rows = (const guint32 *) (heap_tables + 24);
462 for (table = 0; table < 64; table++){
463 if ((valid_mask & ((guint64) 1 << table)) == 0){
464 if (table > MONO_TABLE_LAST)
466 image->tables [table].rows = 0;
469 if (table > MONO_TABLE_LAST) {
470 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
472 image->tables [table].rows = read32 (rows);
474 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
475 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
481 image->tables_base = (heap_tables + 24) + (4 * valid);
483 /* They must be the same */
484 g_assert ((const void *) image->tables_base == (const void *) rows);
486 mono_metadata_compute_table_bases (image);
491 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
493 if (!load_metadata_ptrs (image, iinfo))
496 return load_tables (image);
500 mono_image_check_for_module_cctor (MonoImage *image)
502 MonoTableInfo *t, *mt;
503 t = &image->tables [MONO_TABLE_TYPEDEF];
504 mt = &image->tables [MONO_TABLE_METHOD];
505 if (image->dynamic) {
507 image->checked_module_cctor = TRUE;
511 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
512 const char *name = mono_metadata_string_heap (image, nameidx);
513 if (strcmp (name, "<Module>") == 0) {
514 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
517 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
519 last_method = mt->rows;
520 for (; first_method < last_method; first_method++) {
521 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
522 name = mono_metadata_string_heap (image, nameidx);
523 if (strcmp (name, ".cctor") == 0) {
524 image->has_module_cctor = TRUE;
525 image->checked_module_cctor = TRUE;
531 image->has_module_cctor = FALSE;
532 image->checked_module_cctor = TRUE;
536 load_modules (MonoImage *image)
543 t = &image->tables [MONO_TABLE_MODULEREF];
544 image->modules = g_new0 (MonoImage *, t->rows);
545 image->modules_loaded = g_new0 (gboolean, t->rows);
546 image->module_count = t->rows;
550 * mono_image_load_module:
552 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
553 * it cannot be loaded.
556 mono_image_load_module (MonoImage *image, int idx)
559 MonoTableInfo *file_table;
562 gboolean refonly = image->ref_only;
563 GList *list_iter, *valid_modules = NULL;
564 MonoImageOpenStatus status;
566 if ((image->module_count == 0) || (idx > image->module_count))
568 if (image->modules_loaded [idx - 1])
569 return image->modules [idx - 1];
571 file_table = &image->tables [MONO_TABLE_FILE];
572 for (i = 0; i < file_table->rows; i++) {
573 guint32 cols [MONO_FILE_SIZE];
574 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
575 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
577 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
580 t = &image->tables [MONO_TABLE_MODULEREF];
581 base_dir = g_path_get_dirname (image->name);
586 guint32 cols [MONO_MODULEREF_SIZE];
587 /* if there is no file table, we try to load the module... */
588 int valid = file_table->rows == 0;
590 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
591 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
592 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
593 /* be safe with string dups, but we could just compare string indexes */
594 if (strcmp (list_iter->data, name) == 0) {
600 module_ref = g_build_filename (base_dir, name, NULL);
601 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
602 if (image->modules [idx - 1]) {
603 mono_image_addref (image->modules [idx - 1]);
604 image->modules [idx - 1]->assembly = image->assembly;
606 if (image->modules [idx - 1]->is_module_handle)
607 mono_image_fixup_vtable (image->modules [idx - 1]);
609 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
615 image->modules_loaded [idx - 1] = TRUE;
618 g_list_free (valid_modules);
620 return image->modules [idx - 1];
624 class_key_extract (gpointer value)
626 MonoClass *class = value;
628 return GUINT_TO_POINTER (class->type_token);
632 class_next_value (gpointer value)
634 MonoClass *class = value;
636 return (gpointer*)&class->next_class_cache;
640 mono_image_init (MonoImage *image)
642 image->mempool = mono_mempool_new_size (512);
643 mono_internal_hash_table_init (&image->class_cache,
647 image->field_cache = g_hash_table_new (NULL, NULL);
649 image->typespec_cache = g_hash_table_new (NULL, NULL);
650 image->memberref_signatures = g_hash_table_new (NULL, NULL);
651 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
652 image->method_signatures = g_hash_table_new (NULL, NULL);
654 image->property_hash = mono_property_hash_new ();
655 InitializeCriticalSection (&image->lock);
656 InitializeCriticalSection (&image->szarray_cache_lock);
659 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
660 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
661 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
662 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
663 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
672 * Returns < 0 to indicate an error.
675 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
677 MonoDotNetHeader64 header64;
680 if (!image->is_module_handle)
682 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
685 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
687 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
690 /* endian swap the fields common between PE and PE+ */
691 SWAP32 (header->coff.coff_time);
692 SWAP32 (header->coff.coff_symptr);
693 SWAP32 (header->coff.coff_symcount);
694 SWAP16 (header->coff.coff_machine);
695 SWAP16 (header->coff.coff_sections);
696 SWAP16 (header->coff.coff_opt_header_size);
697 SWAP16 (header->coff.coff_attributes);
699 SWAP32 (header->pe.pe_code_size);
700 SWAP32 (header->pe.pe_uninit_data_size);
701 SWAP32 (header->pe.pe_rva_entry_point);
702 SWAP32 (header->pe.pe_rva_code_base);
703 SWAP32 (header->pe.pe_rva_data_base);
704 SWAP16 (header->pe.pe_magic);
706 /* now we are ready for the basic tests */
708 if (header->pe.pe_magic == 0x10B) {
709 offset += sizeof (MonoDotNetHeader);
710 SWAP32 (header->pe.pe_data_size);
711 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
714 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
715 SWAP32 (header->nt.pe_stack_reserve);
716 SWAP32 (header->nt.pe_stack_commit);
717 SWAP32 (header->nt.pe_heap_reserve);
718 SWAP32 (header->nt.pe_heap_commit);
719 } else if (header->pe.pe_magic == 0x20B) {
720 /* PE32+ file format */
721 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
723 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
724 offset += sizeof (MonoDotNetHeader64);
725 /* copy the fields already swapped. the last field, pe_data_size, is missing */
726 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
727 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
728 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
730 SWAP64 (header64.nt.pe_image_base);
731 header->nt.pe_image_base = header64.nt.pe_image_base;
732 SWAP64 (header64.nt.pe_stack_reserve);
733 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
734 SWAP64 (header64.nt.pe_stack_commit);
735 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
736 SWAP64 (header64.nt.pe_heap_reserve);
737 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
738 SWAP64 (header64.nt.pe_heap_commit);
739 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
741 header->nt.pe_section_align = header64.nt.pe_section_align;
742 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
743 header->nt.pe_os_major = header64.nt.pe_os_major;
744 header->nt.pe_os_minor = header64.nt.pe_os_minor;
745 header->nt.pe_user_major = header64.nt.pe_user_major;
746 header->nt.pe_user_minor = header64.nt.pe_user_minor;
747 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
748 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
749 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
750 header->nt.pe_image_size = header64.nt.pe_image_size;
751 header->nt.pe_header_size = header64.nt.pe_header_size;
752 header->nt.pe_checksum = header64.nt.pe_checksum;
753 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
754 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
755 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
756 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
758 /* copy the datadir */
759 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
764 /* MonoPEHeaderNT: not used yet */
765 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
766 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
767 SWAP16 (header->nt.pe_os_major); /* must be 4 */
768 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
769 SWAP16 (header->nt.pe_user_major);
770 SWAP16 (header->nt.pe_user_minor);
771 SWAP16 (header->nt.pe_subsys_major);
772 SWAP16 (header->nt.pe_subsys_minor);
773 SWAP32 (header->nt.pe_reserved_1);
774 SWAP32 (header->nt.pe_image_size);
775 SWAP32 (header->nt.pe_header_size);
776 SWAP32 (header->nt.pe_checksum);
777 SWAP16 (header->nt.pe_subsys_required);
778 SWAP16 (header->nt.pe_dll_flags);
779 SWAP32 (header->nt.pe_loader_flags);
780 SWAP32 (header->nt.pe_data_dir_count);
782 /* MonoDotNetHeader: mostly unused */
783 SWAPPDE (header->datadir.pe_export_table);
784 SWAPPDE (header->datadir.pe_import_table);
785 SWAPPDE (header->datadir.pe_resource_table);
786 SWAPPDE (header->datadir.pe_exception_table);
787 SWAPPDE (header->datadir.pe_certificate_table);
788 SWAPPDE (header->datadir.pe_reloc_table);
789 SWAPPDE (header->datadir.pe_debug);
790 SWAPPDE (header->datadir.pe_copyright);
791 SWAPPDE (header->datadir.pe_global_ptr);
792 SWAPPDE (header->datadir.pe_tls_table);
793 SWAPPDE (header->datadir.pe_load_config_table);
794 SWAPPDE (header->datadir.pe_bound_import);
795 SWAPPDE (header->datadir.pe_iat);
796 SWAPPDE (header->datadir.pe_delay_import_desc);
797 SWAPPDE (header->datadir.pe_cli_header);
798 SWAPPDE (header->datadir.pe_reserved);
801 if (image->is_module_handle)
802 image->raw_data_len = header->nt.pe_image_size;
809 mono_image_load_pe_data (MonoImage *image)
811 MonoCLIImageInfo *iinfo;
812 MonoDotNetHeader *header;
813 MonoMSDOSHeader msdos;
816 iinfo = image->image_info;
817 header = &iinfo->cli_header;
820 if (!image->is_module_handle)
822 if (offset + sizeof (msdos) > image->raw_data_len)
824 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
826 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
829 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
831 offset = msdos.pe_offset;
833 offset = do_load_header (image, header, offset);
838 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
840 if (header->coff.coff_machine != 0x14c)
846 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
847 * which produces binaries with 7.0. From Sergey:
849 * The reason is that MSVC7 uses traditional compile/link
850 * sequence for CIL executables, and VS.NET (and Framework
851 * SDK) includes linker version 7, that puts 7.0 in this
852 * field. That's why it's currently not possible to load VC
853 * binaries with Mono. This field is pretty much meaningless
854 * anyway (what linker?).
856 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
861 * FIXME: byte swap all addresses here for header.
864 if (!load_section_tables (image, iinfo, offset))
874 mono_image_load_cli_data (MonoImage *image)
876 MonoCLIImageInfo *iinfo;
877 MonoDotNetHeader *header;
879 iinfo = image->image_info;
880 header = &iinfo->cli_header;
882 /* Load the CLI header */
883 if (!load_cli_header (image, iinfo))
886 if (!load_metadata (image, iinfo))
893 mono_image_load_names (MonoImage *image)
895 /* modules don't have an assembly table row */
896 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
897 image->assembly_name = mono_metadata_string_heap (image,
898 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
899 0, MONO_ASSEMBLY_NAME));
902 image->module_name = mono_metadata_string_heap (image,
903 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
904 0, MONO_MODULE_NAME));
908 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
909 gboolean care_about_cli, gboolean care_about_pecoff)
911 MonoCLIImageInfo *iinfo;
912 MonoDotNetHeader *header;
914 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
916 mono_image_init (image);
918 iinfo = image->image_info;
919 header = &iinfo->cli_header;
922 *status = MONO_IMAGE_IMAGE_INVALID;
924 if (care_about_pecoff == FALSE)
927 if (!mono_verifier_verify_pe_data (image, NULL))
930 if (!mono_image_load_pe_data (image))
933 if (care_about_cli == FALSE) {
937 if (!mono_verifier_verify_cli_data (image, NULL))
940 if (!mono_image_load_cli_data (image))
943 if (!mono_verifier_verify_table_data (image, NULL))
946 mono_image_load_names (image);
948 load_modules (image);
951 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
953 *status = MONO_IMAGE_OK;
958 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
959 mono_image_close (image);
964 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
965 gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
967 MonoCLIImageInfo *iinfo;
971 if ((filed = mono_file_map_open (fname)) == NULL){
972 if (IS_PORTABILITY_SET) {
973 gchar *ffname = mono_portability_find_file (fname, TRUE);
975 filed = mono_file_map_open (ffname);
982 *status = MONO_IMAGE_ERROR_ERRNO;
987 image = g_new0 (MonoImage, 1);
988 image->raw_buffer_used = TRUE;
989 image->raw_data_len = mono_file_map_size (filed);
990 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);
991 if (!image->raw_data) {
992 mono_file_map_close (filed);
995 *status = MONO_IMAGE_IMAGE_INVALID;
998 iinfo = g_new0 (MonoCLIImageInfo, 1);
999 image->image_info = iinfo;
1000 image->name = mono_path_resolve_symlinks (fname);
1001 image->ref_only = refonly;
1002 image->ref_count = 1;
1003 /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
1004 image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
1006 mono_file_map_close (filed);
1007 return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
1011 mono_image_loaded_full (const char *name, gboolean refonly)
1014 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1016 mono_images_lock ();
1017 res = g_hash_table_lookup (loaded_images, name);
1018 mono_images_unlock ();
1023 * mono_image_loaded:
1024 * @name: name of the image to load
1026 * This routine ensures that the given image is loaded.
1028 * Returns: the loaded MonoImage, or NULL on failure.
1031 mono_image_loaded (const char *name)
1033 return mono_image_loaded_full (name, FALSE);
1042 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1044 GuidData *data = user_data;
1050 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1055 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1058 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1062 mono_images_lock ();
1063 g_hash_table_foreach (loaded_images, find_by_guid, &data);
1064 mono_images_unlock ();
1069 mono_image_loaded_by_guid (const char *guid)
1071 return mono_image_loaded_by_guid_full (guid, FALSE);
1075 register_image (MonoImage *image)
1078 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1080 mono_images_lock ();
1081 image2 = g_hash_table_lookup (loaded_images, image->name);
1084 /* Somebody else beat us to it */
1085 mono_image_addref (image2);
1086 mono_images_unlock ();
1087 mono_image_close (image);
1090 g_hash_table_insert (loaded_images, image->name, image);
1091 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1092 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1093 mono_images_unlock ();
1099 mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
1101 MonoCLIImageInfo *iinfo;
1105 if (!data || !data_len) {
1107 *status = MONO_IMAGE_IMAGE_INVALID;
1112 datac = g_try_malloc (data_len);
1115 *status = MONO_IMAGE_ERROR_ERRNO;
1118 memcpy (datac, data, data_len);
1121 image = g_new0 (MonoImage, 1);
1122 image->raw_data = datac;
1123 image->raw_data_len = data_len;
1124 image->raw_data_allocated = need_copy;
1125 image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup(name);
1126 iinfo = g_new0 (MonoCLIImageInfo, 1);
1127 image->image_info = iinfo;
1128 image->ref_only = refonly;
1130 image = do_mono_image_load (image, status, TRUE, TRUE);
1134 return register_image (image);
1138 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1140 return mono_image_open_from_data_with_name (data, data_len, need_copy, status, refonly, NULL);
1144 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1146 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1150 /* fname is not duplicated. */
1152 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1155 MonoCLIImageInfo* iinfo;
1157 image = g_new0 (MonoImage, 1);
1158 image->raw_data = (char*) module_handle;
1159 image->is_module_handle = TRUE;
1160 iinfo = g_new0 (MonoCLIImageInfo, 1);
1161 image->image_info = iinfo;
1162 image->name = fname;
1163 image->ref_count = has_entry_point ? 0 : 1;
1164 image->has_entry_point = has_entry_point;
1166 image = do_mono_image_load (image, status, TRUE, TRUE);
1170 return register_image (image);
1175 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1178 GHashTable *loaded_images;
1181 g_return_val_if_fail (fname != NULL, NULL);
1184 /* Load modules using LoadLibrary. */
1185 if (!refonly && coree_module_handle) {
1186 HMODULE module_handle;
1187 guint16 *fname_utf16;
1190 absfname = mono_path_resolve_symlinks (fname);
1193 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1194 mono_images_lock ();
1195 image = g_hash_table_lookup (loaded_images_hash, absfname);
1197 g_assert (image->is_module_handle);
1198 if (image->has_entry_point && image->ref_count == 0) {
1199 /* Increment reference count on images loaded outside of the runtime. */
1200 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1201 /* The image is already loaded because _CorDllMain removes images from the hash. */
1202 module_handle = LoadLibrary (fname_utf16);
1203 g_assert (module_handle == (HMODULE) image->raw_data);
1205 mono_image_addref (image);
1206 mono_images_unlock ();
1208 g_free (fname_utf16);
1213 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1214 module_handle = MonoLoadImage (fname_utf16);
1215 if (status && module_handle == NULL)
1216 last_error = GetLastError ();
1218 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1219 image = g_hash_table_lookup (loaded_images_hash, absfname);
1221 mono_image_addref (image);
1222 mono_images_unlock ();
1224 g_free (fname_utf16);
1226 if (module_handle == NULL) {
1230 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1231 *status = MONO_IMAGE_IMAGE_INVALID;
1233 *status = MONO_IMAGE_ERROR_ERRNO;
1239 g_assert (image->is_module_handle);
1240 g_assert (image->has_entry_point);
1245 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1249 absfname = mono_path_canonicalize (fname);
1252 * The easiest solution would be to do all the loading inside the mutex,
1253 * but that would lead to scalability problems. So we let the loading
1254 * happen outside the mutex, and if multiple threads happen to load
1255 * the same image, we discard all but the first copy.
1257 mono_images_lock ();
1258 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1259 image = g_hash_table_lookup (loaded_images, absfname);
1263 mono_image_addref (image);
1264 mono_images_unlock ();
1267 mono_images_unlock ();
1269 image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1273 return register_image (image);
1278 * @fname: filename that points to the module we want to open
1279 * @status: An error condition is returned in this field
1281 * Returns: An open image of type %MonoImage or NULL on error.
1282 * The caller holds a temporary reference to the returned image which should be cleared
1283 * when no longer needed by calling mono_image_close ().
1284 * if NULL, then check the value of @status for details on the error
1287 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1289 return mono_image_open_full (fname, status, FALSE);
1293 * mono_pe_file_open:
1294 * @fname: filename that points to the module we want to open
1295 * @status: An error condition is returned in this field
1297 * Returns: An open image of type %MonoImage or NULL on error. if
1298 * NULL, then check the value of @status for details on the error.
1299 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1300 * It's just a PE file loader, used for FileVersionInfo. It also does
1301 * not use the image cache.
1304 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1306 g_return_val_if_fail (fname != NULL, NULL);
1308 return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1312 * mono_image_open_raw
1313 * @fname: filename that points to the module we want to open
1314 * @status: An error condition is returned in this field
1316 * Returns an image without loading neither pe or cli data.
1318 * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
1321 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1323 g_return_val_if_fail (fname != NULL, NULL);
1325 return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1329 mono_image_fixup_vtable (MonoImage *image)
1332 MonoCLIImageInfo *iinfo;
1334 MonoVTableFixup *vtfixup;
1340 g_assert (image->is_module_handle);
1342 iinfo = image->image_info;
1343 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1344 if (!de->rva || !de->size)
1346 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1350 count = de->size / sizeof (MonoVTableFixup);
1352 if (!vtfixup->rva || !vtfixup->count)
1355 slot = mono_image_rva_map (image, vtfixup->rva);
1357 slot_type = vtfixup->type;
1358 slot_count = vtfixup->count;
1359 if (slot_type & VTFIXUP_TYPE_32BIT)
1360 while (slot_count--) {
1361 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1362 slot = ((guint32*) slot) + 1;
1364 else if (slot_type & VTFIXUP_TYPE_64BIT)
1365 while (slot_count--) {
1366 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1367 slot = ((guint32*) slot) + 1;
1370 g_assert_not_reached();
1375 g_assert_not_reached();
1380 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1382 g_hash_table_destroy ((GHashTable*)val);
1387 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1389 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1394 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1400 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1402 g_slist_free ((GSList*)val);
1406 * mono_image_addref:
1407 * @image: The image file we wish to add a reference to
1409 * Increases the reference count of an image.
1412 mono_image_addref (MonoImage *image)
1414 InterlockedIncrement (&image->ref_count);
1418 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1420 stream->alloc_size = stream->index = stream->offset = 0;
1421 g_free (stream->data);
1422 stream->data = NULL;
1424 g_hash_table_destroy (stream->hash);
1425 stream->hash = NULL;
1430 free_hash (GHashTable *hash)
1433 g_hash_table_destroy (hash);
1437 * Returns whether mono_image_close_finish() must be called as well.
1438 * We must unload images in two steps because clearing the domain in
1439 * SGen requires the class metadata to be intact, but we need to free
1440 * the mono_g_hash_tables in case a collection occurs during domain
1441 * unloading and the roots would trip up the GC.
1444 mono_image_close_except_pools (MonoImage *image)
1447 GHashTable *loaded_images;
1451 g_return_val_if_fail (image != NULL, FALSE);
1454 * Atomically decrement the refcount and remove ourselves from the hash tables, so
1455 * register_image () can't grab an image which is being closed.
1457 mono_images_lock ();
1459 if (InterlockedDecrement (&image->ref_count) > 0) {
1460 mono_images_unlock ();
1464 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1465 image2 = g_hash_table_lookup (loaded_images, image->name);
1466 if (image == image2) {
1467 /* This is not true if we are called from mono_image_open () */
1468 g_hash_table_remove (loaded_images, image->name);
1470 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1471 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1473 mono_images_unlock ();
1476 if (image->is_module_handle && image->has_entry_point) {
1477 mono_images_lock ();
1478 if (image->ref_count == 0) {
1479 /* Image will be closed by _CorDllMain. */
1480 FreeLibrary ((HMODULE) image->raw_data);
1481 mono_images_unlock ();
1484 mono_images_unlock ();
1488 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1490 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1492 mono_image_invoke_unload_hook (image);
1494 free_list = mono_metadata_clean_for_image (image);
1497 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1498 * assemblies, so we can't release these references in mono_assembly_close () since the
1499 * MonoImage might outlive its associated MonoAssembly.
1501 if (image->references && !image->dynamic) {
1502 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1505 for (i = 0; i < t->rows; i++) {
1506 if (image->references [i]) {
1507 if (!mono_assembly_close_except_image_pools (image->references [i]))
1508 image->references [i] = NULL;
1512 if (image->references) {
1513 g_free (image->references);
1514 image->references = NULL;
1519 mono_images_lock ();
1520 if (image->is_module_handle && !image->has_entry_point)
1521 FreeLibrary ((HMODULE) image->raw_data);
1522 mono_images_unlock ();
1525 if (image->raw_buffer_used) {
1526 if (image->raw_data != NULL)
1527 mono_file_unmap (image->raw_data, image->raw_data_handle);
1530 if (image->raw_data_allocated) {
1531 /* FIXME: do we need this? (image is disposed anyway) */
1532 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1533 MonoCLIImageInfo *ii = image->image_info;
1535 if ((image->raw_metadata > image->raw_data) &&
1536 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1537 image->raw_metadata = NULL;
1539 for (i = 0; i < ii->cli_section_count; i++)
1540 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1541 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1542 ii->cli_sections [i] = NULL;
1544 g_free (image->raw_data);
1547 if (debug_assembly_unload) {
1548 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1550 g_free (image->name);
1551 g_free (image->guid);
1552 g_free (image->version);
1553 g_free (image->files);
1556 if (image->method_cache)
1557 g_hash_table_destroy (image->method_cache);
1558 if (image->methodref_cache)
1559 g_hash_table_destroy (image->methodref_cache);
1560 mono_internal_hash_table_destroy (&image->class_cache);
1561 g_hash_table_destroy (image->field_cache);
1562 if (image->array_cache) {
1563 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1564 g_hash_table_destroy (image->array_cache);
1566 if (image->szarray_cache)
1567 g_hash_table_destroy (image->szarray_cache);
1568 if (image->ptr_cache)
1569 g_hash_table_destroy (image->ptr_cache);
1570 if (image->name_cache) {
1571 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1572 g_hash_table_destroy (image->name_cache);
1575 free_hash (image->native_wrapper_cache);
1576 free_hash (image->managed_wrapper_cache);
1577 free_hash (image->delegate_begin_invoke_cache);
1578 free_hash (image->delegate_end_invoke_cache);
1579 free_hash (image->delegate_invoke_cache);
1580 free_hash (image->delegate_abstract_invoke_cache);
1581 if (image->remoting_invoke_cache)
1582 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1583 free_hash (image->remoting_invoke_cache);
1584 free_hash (image->runtime_invoke_cache);
1585 free_hash (image->runtime_invoke_direct_cache);
1586 free_hash (image->runtime_invoke_vcall_cache);
1587 free_hash (image->synchronized_cache);
1588 free_hash (image->unbox_wrapper_cache);
1589 free_hash (image->cominterop_invoke_cache);
1590 free_hash (image->cominterop_wrapper_cache);
1591 free_hash (image->typespec_cache);
1592 free_hash (image->ldfld_wrapper_cache);
1593 free_hash (image->ldflda_wrapper_cache);
1594 free_hash (image->stfld_wrapper_cache);
1595 free_hash (image->isinst_cache);
1596 free_hash (image->castclass_cache);
1597 free_hash (image->proxy_isinst_cache);
1598 free_hash (image->thunk_invoke_cache);
1600 /* The ownership of signatures is not well defined */
1601 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1602 g_hash_table_destroy (image->memberref_signatures);
1603 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1604 g_hash_table_destroy (image->helper_signatures);
1605 g_hash_table_destroy (image->method_signatures);
1607 if (image->rgctx_template_hash)
1608 g_hash_table_destroy (image->rgctx_template_hash);
1610 if (image->property_hash)
1611 mono_property_hash_destroy (image->property_hash);
1613 g_slist_free (image->reflection_info_unregister_classes);
1614 image->reflection_info_unregister_classes = free_list;
1616 if (image->interface_bitset) {
1617 mono_unload_interface_ids (image->interface_bitset);
1618 mono_bitset_free (image->interface_bitset);
1620 if (image->image_info){
1621 MonoCLIImageInfo *ii = image->image_info;
1623 if (ii->cli_section_tables)
1624 g_free (ii->cli_section_tables);
1625 if (ii->cli_sections)
1626 g_free (ii->cli_sections);
1627 g_free (image->image_info);
1630 for (i = 0; i < image->module_count; ++i) {
1631 if (image->modules [i]) {
1632 if (!mono_image_close_except_pools (image->modules [i]))
1633 image->modules [i] = NULL;
1636 if (image->modules_loaded)
1637 g_free (image->modules_loaded);
1639 DeleteCriticalSection (&image->szarray_cache_lock);
1640 DeleteCriticalSection (&image->lock);
1642 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1643 if (image->dynamic) {
1644 /* Dynamic images are GC_MALLOCed */
1645 g_free ((char*)image->module_name);
1646 mono_dynamic_image_free ((MonoDynamicImage*)image);
1649 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1655 mono_image_close_finish (MonoImage *image)
1660 for (l = image->reflection_info_unregister_classes; l; l = l->next)
1662 g_slist_free (image->reflection_info_unregister_classes);
1663 image->reflection_info_unregister_classes = NULL;
1665 if (image->references && !image->dynamic) {
1666 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1669 for (i = 0; i < t->rows; i++) {
1670 if (image->references [i])
1671 mono_assembly_close_finish (image->references [i]);
1674 g_free (image->references);
1675 image->references = NULL;
1678 for (i = 0; i < image->module_count; ++i) {
1679 if (image->modules [i])
1680 mono_image_close_finish (image->modules [i]);
1683 g_free (image->modules);
1685 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1687 if (!image->dynamic) {
1688 if (debug_assembly_unload)
1689 mono_mempool_invalidate (image->mempool);
1691 mono_mempool_destroy (image->mempool);
1695 if (debug_assembly_unload)
1696 mono_mempool_invalidate (image->mempool);
1698 mono_mempool_destroy (image->mempool);
1704 * @image: The image file we wish to close
1706 * Closes an image file, deallocates all memory consumed and
1707 * unmaps all possible sections of the file
1710 mono_image_close (MonoImage *image)
1712 if (mono_image_close_except_pools (image))
1713 mono_image_close_finish (image);
1717 * mono_image_strerror:
1718 * @status: an code indicating the result from a recent operation
1720 * Returns: a string describing the error
1723 mono_image_strerror (MonoImageOpenStatus status)
1728 case MONO_IMAGE_ERROR_ERRNO:
1729 return strerror (errno);
1730 case MONO_IMAGE_IMAGE_INVALID:
1731 return "File does not contain a valid CIL image";
1732 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1733 return "An assembly was referenced, but could not be found";
1735 return "Internal error";
1739 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1740 guint32 lang_id, gunichar2 *name,
1741 MonoPEResourceDirEntry *entry,
1742 MonoPEResourceDir *root, guint32 level)
1744 gboolean is_string, is_dir;
1745 guint32 name_offset, dir_offset;
1747 /* Level 0 holds a directory entry for each type of resource
1748 * (identified by ID or name).
1750 * Level 1 holds a directory entry for each named resource
1751 * item, and each "anonymous" item of a particular type of
1754 * Level 2 holds a directory entry for each language pointing to
1757 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1758 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1760 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1761 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1766 } else if (level==1) {
1767 if (res_id != name_offset)
1771 is_string==TRUE && name!=lookup (name_offset)) {
1775 } else if (level==2) {
1776 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1779 g_assert_not_reached ();
1783 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1784 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1787 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1789 for(i=0; i<entries; i++) {
1790 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1793 ret=mono_image_walk_resource_tree (info, res_id,
1804 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1805 MonoPEResourceDataEntry *res;
1807 res = g_new0 (MonoPEResourceDataEntry, 1);
1809 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1810 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1811 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1812 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1819 * mono_image_lookup_resource:
1820 * @image: the image to look up the resource in
1821 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1822 * @lang_id: The language id.
1823 * @name: the resource name to lookup.
1825 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1826 * of the given resource. The caller should free it using g_free () when no longer
1830 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1832 MonoCLIImageInfo *info;
1833 MonoDotNetHeader *header;
1834 MonoPEDatadir *datadir;
1835 MonoPEDirEntry *rsrc;
1836 MonoPEResourceDir *resource_dir;
1837 MonoPEResourceDirEntry *res_entries;
1844 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1846 info=image->image_info;
1851 header=&info->cli_header;
1856 datadir=&header->datadir;
1861 rsrc=&datadir->pe_resource_table;
1866 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1867 if(resource_dir==NULL) {
1871 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1872 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1874 for(i=0; i<entries; i++) {
1875 MonoPEResourceDirEntry *entry=&res_entries[i];
1878 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1879 name, entry, resource_dir,
1890 * mono_image_get_entry_point:
1891 * @image: the image where the entry point will be looked up.
1893 * Use this routine to determine the metadata token for method that
1894 * has been flagged as the entry point.
1896 * Returns: the token for the entry point method in the image
1899 mono_image_get_entry_point (MonoImage *image)
1901 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1905 * mono_image_get_resource:
1906 * @image: the image where the resource will be looked up.
1907 * @offset: The offset to add to the resource
1908 * @size: a pointer to an int where the size of the resource will be stored
1910 * This is a low-level routine that fetches a resource from the
1911 * metadata that starts at a given @offset. The @size parameter is
1912 * filled with the data field as encoded in the metadata.
1914 * Returns: the pointer to the resource whose offset is @offset.
1917 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1919 MonoCLIImageInfo *iinfo = image->image_info;
1920 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1923 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1926 data = mono_image_rva_map (image, ch->ch_resources.rva);
1931 *size = read32 (data);
1937 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1939 char *base_dir, *name;
1941 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1945 if (fileidx < 1 || fileidx > t->rows)
1948 mono_loader_lock ();
1949 if (image->files && image->files [fileidx - 1]) {
1950 mono_loader_unlock ();
1951 return image->files [fileidx - 1];
1955 image->files = g_new0 (MonoImage*, t->rows);
1957 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1958 fname = mono_metadata_string_heap (image, fname_id);
1959 base_dir = g_path_get_dirname (image->name);
1960 name = g_build_filename (base_dir, fname, NULL);
1961 res = mono_image_open (name, NULL);
1964 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1965 res->assembly = image->assembly;
1966 for (i = 0; i < res->module_count; ++i) {
1967 if (res->modules [i] && !res->modules [i]->assembly)
1968 res->modules [i]->assembly = image->assembly;
1971 image->files [fileidx - 1] = res;
1973 if (res->is_module_handle)
1974 mono_image_fixup_vtable (res);
1977 mono_loader_unlock ();
1984 * mono_image_get_strong_name:
1985 * @image: a MonoImage
1986 * @size: a guint32 pointer, or NULL.
1988 * If the image has a strong name, and @size is not NULL, the value
1989 * pointed to by size will have the size of the strong name.
1991 * Returns: NULL if the image does not have a strong name, or a
1992 * pointer to the public key.
1995 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1997 MonoCLIImageInfo *iinfo = image->image_info;
1998 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2001 if (!de->size || !de->rva)
2003 data = mono_image_rva_map (image, de->rva);
2012 * mono_image_strong_name_position:
2013 * @image: a MonoImage
2014 * @size: a guint32 pointer, or NULL.
2016 * If the image has a strong name, and @size is not NULL, the value
2017 * pointed to by size will have the size of the strong name.
2019 * Returns: the position within the image file where the strong name
2023 mono_image_strong_name_position (MonoImage *image, guint32 *size)
2025 MonoCLIImageInfo *iinfo = image->image_info;
2026 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2031 if (!de->size || !de->rva)
2033 pos = mono_cli_rva_image_map (image, de->rva);
2034 return pos == INVALID_ADDRESS ? 0 : pos;
2038 * mono_image_get_public_key:
2039 * @image: a MonoImage
2040 * @size: a guint32 pointer, or NULL.
2042 * This is used to obtain the public key in the @image.
2044 * If the image has a public key, and @size is not NULL, the value
2045 * pointed to by size will have the size of the public key.
2047 * Returns: NULL if the image does not have a public key, or a pointer
2048 * to the public key.
2051 mono_image_get_public_key (MonoImage *image, guint32 *size)
2056 if (image->dynamic) {
2058 *size = ((MonoDynamicImage*)image)->public_key_len;
2059 return (char*)((MonoDynamicImage*)image)->public_key;
2061 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
2063 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
2066 pubkey = mono_metadata_blob_heap (image, tok);
2067 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
2074 * mono_image_get_name:
2075 * @name: a MonoImage
2077 * Returns: the name of the assembly.
2080 mono_image_get_name (MonoImage *image)
2082 return image->assembly_name;
2086 * mono_image_get_filename:
2087 * @image: a MonoImage
2089 * Used to get the filename that hold the actual MonoImage
2091 * Returns: the filename.
2094 mono_image_get_filename (MonoImage *image)
2100 mono_image_get_guid (MonoImage *image)
2105 const MonoTableInfo*
2106 mono_image_get_table_info (MonoImage *image, int table_id)
2108 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2110 return &image->tables [table_id];
2114 mono_image_get_table_rows (MonoImage *image, int table_id)
2116 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2118 return image->tables [table_id].rows;
2122 mono_table_info_get_rows (const MonoTableInfo *table)
2128 * mono_image_get_assembly:
2129 * @image: the MonoImage.
2131 * Use this routine to get the assembly that owns this image.
2133 * Returns: the assembly that holds this image.
2136 mono_image_get_assembly (MonoImage *image)
2138 return image->assembly;
2142 * mono_image_is_dynamic:
2143 * @image: the MonoImage
2145 * Determines if the given image was created dynamically through the
2146 * System.Reflection.Emit API
2148 * Returns: TRUE if the image was created dynamically, FALSE if not.
2151 mono_image_is_dynamic (MonoImage *image)
2153 return image->dynamic;
2157 * mono_image_has_authenticode_entry:
2158 * @image: the MonoImage
2160 * Use this routine to determine if the image has a Authenticode
2161 * Certificate Table.
2163 * Returns: TRUE if the image contains an authenticode entry in the PE
2167 mono_image_has_authenticode_entry (MonoImage *image)
2169 MonoCLIImageInfo *iinfo = image->image_info;
2170 MonoDotNetHeader *header = &iinfo->cli_header;
2171 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2172 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2173 return ((de->rva != 0) && (de->size > 8));
2177 mono_image_alloc (MonoImage *image, guint size)
2181 mono_perfcounters->loader_bytes += size;
2182 mono_image_lock (image);
2183 res = mono_mempool_alloc (image->mempool, size);
2184 mono_image_unlock (image);
2190 mono_image_alloc0 (MonoImage *image, guint size)
2194 mono_perfcounters->loader_bytes += size;
2195 mono_image_lock (image);
2196 res = mono_mempool_alloc0 (image->mempool, size);
2197 mono_image_unlock (image);
2203 mono_image_strdup (MonoImage *image, const char *s)
2207 mono_perfcounters->loader_bytes += strlen (s);
2208 mono_image_lock (image);
2209 res = mono_mempool_strdup (image->mempool, s);
2210 mono_image_unlock (image);
2216 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2220 new_list = mono_image_alloc (image, sizeof (GList));
2221 new_list->data = data;
2222 new_list->prev = list ? list->prev : NULL;
2223 new_list->next = list;
2226 new_list->prev->next = new_list;
2228 list->prev = new_list;
2234 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2238 new_list = mono_image_alloc (image, sizeof (GSList));
2239 new_list->data = data;
2240 new_list->next = NULL;
2242 return g_slist_concat (list, new_list);
2246 mono_image_lock (MonoImage *image)
2248 mono_locks_acquire (&image->lock, ImageDataLock);
2252 mono_image_unlock (MonoImage *image)
2254 mono_locks_release (&image->lock, ImageDataLock);
2259 * mono_image_property_lookup:
2261 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2263 * LOCKING: Takes the image lock
2266 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2270 mono_image_lock (image);
2271 res = mono_property_hash_lookup (image->property_hash, subject, property);
2272 mono_image_unlock (image);
2278 * mono_image_property_insert:
2280 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2282 * LOCKING: Takes the image lock
2285 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2287 mono_image_lock (image);
2288 mono_property_hash_insert (image->property_hash, subject, property, value);
2289 mono_image_unlock (image);
2293 * mono_image_property_remove:
2295 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2297 * LOCKING: Takes the image lock
2300 mono_image_property_remove (MonoImage *image, gpointer subject)
2302 mono_image_lock (image);
2303 mono_property_hash_remove_object (image->property_hash, subject);
2304 mono_image_unlock (image);