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 <mono/metadata/verify.h>
40 #include <sys/types.h>
46 #define INVALID_ADDRESS 0xffffffff
49 * Keeps track of the various assemblies loaded
51 static GHashTable *loaded_images_hash;
52 static GHashTable *loaded_images_refonly_hash;
54 static gboolean debug_assembly_unload = FALSE;
56 #define mono_images_lock() if (mutex_inited) EnterCriticalSection (&images_mutex)
57 #define mono_images_unlock() if (mutex_inited) LeaveCriticalSection (&images_mutex)
58 static gboolean mutex_inited;
59 static CRITICAL_SECTION images_mutex;
61 typedef struct ImageUnloadHook ImageUnloadHook;
62 struct ImageUnloadHook {
63 MonoImageUnloadFunc func;
67 GSList *image_unload_hooks;
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 image_unload_hooks = g_slist_prepend (image_unload_hooks, hook);
83 mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
86 ImageUnloadHook *hook;
88 for (l = image_unload_hooks; l; l = l->next) {
91 if (hook->func == func && hook->user_data == user_data) {
93 image_unload_hooks = g_slist_delete_link (image_unload_hooks, l);
100 mono_image_invoke_unload_hook (MonoImage *image)
103 ImageUnloadHook *hook;
105 for (l = image_unload_hooks; l; l = l->next) {
108 hook->func (image, hook->user_data);
112 /* returns offset relative to image->raw_data */
114 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
116 MonoCLIImageInfo *iinfo = image->image_info;
117 const int top = iinfo->cli_section_count;
118 MonoSectionTable *tables = iinfo->cli_section_tables;
121 for (i = 0; i < top; i++){
122 if ((addr >= tables->st_virtual_address) &&
123 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
125 if (image->is_module_handle)
128 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
132 return INVALID_ADDRESS;
136 * mono_images_rva_map:
137 * @image: a MonoImage
138 * @addr: relative virtual address (RVA)
140 * This is a low-level routine used by the runtime to map relative
141 * virtual address (RVA) into their location in memory.
143 * Returns: the address in memory for the given RVA, or NULL if the
144 * RVA is not valid for this image.
147 mono_image_rva_map (MonoImage *image, guint32 addr)
149 MonoCLIImageInfo *iinfo = image->image_info;
150 const int top = iinfo->cli_section_count;
151 MonoSectionTable *tables = iinfo->cli_section_tables;
154 for (i = 0; i < top; i++){
155 if ((addr >= tables->st_virtual_address) &&
156 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
157 if (!iinfo->cli_sections [i]) {
158 if (!mono_image_ensure_section_idx (image, i))
162 if (image->is_module_handle)
163 return image->raw_data + addr;
165 return (char*)iinfo->cli_sections [i] +
166 (addr - tables->st_virtual_address);
176 * Initialize the global variables used by this module.
179 mono_images_init (void)
181 InitializeCriticalSection (&images_mutex);
183 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
184 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
186 debug_assembly_unload = g_getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
192 * mono_images_cleanup:
194 * Free all resources used by this module.
197 mono_images_cleanup (void)
202 DeleteCriticalSection (&images_mutex);
204 g_hash_table_iter_init (&iter, loaded_images_hash);
205 while (g_hash_table_iter_next (&iter, NULL, (void**)&image))
206 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly image '%s' still loaded at shutdown.", image->name);
208 g_hash_table_destroy (loaded_images_hash);
209 g_hash_table_destroy (loaded_images_refonly_hash);
211 mutex_inited = FALSE;
215 * mono_image_ensure_section_idx:
216 * @image: The image we are operating on
217 * @section: section number that we will load/map into memory
219 * This routine makes sure that we have an in-memory copy of
220 * an image section (.text, .rsrc, .data).
222 * Returns: TRUE on success
225 mono_image_ensure_section_idx (MonoImage *image, int section)
227 MonoCLIImageInfo *iinfo = image->image_info;
228 MonoSectionTable *sect;
231 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
233 if (iinfo->cli_sections [section] != NULL)
236 sect = &iinfo->cli_section_tables [section];
238 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
240 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
243 if (image->is_module_handle)
244 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
247 /* FIXME: we ignore the writable flag since we don't patch the binary */
248 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
253 * mono_image_ensure_section:
254 * @image: The image we are operating on
255 * @section: section name that we will load/map into memory
257 * This routine makes sure that we have an in-memory copy of
258 * an image section (.text, .rsrc, .data).
260 * Returns: TRUE on success
263 mono_image_ensure_section (MonoImage *image, const char *section)
265 MonoCLIImageInfo *ii = image->image_info;
268 for (i = 0; i < ii->cli_section_count; i++){
269 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
272 return mono_image_ensure_section_idx (image, i);
278 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
280 const int top = iinfo->cli_header.coff.coff_sections;
283 iinfo->cli_section_count = top;
284 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
285 iinfo->cli_sections = g_new0 (void *, top);
287 for (i = 0; i < top; i++){
288 MonoSectionTable *t = &iinfo->cli_section_tables [i];
290 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
292 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
293 offset += sizeof (MonoSectionTable);
295 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
296 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
297 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
298 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
299 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
300 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
301 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
302 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
303 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
304 t->st_flags = GUINT32_FROM_LE (t->st_flags);
306 /* consistency checks here */
313 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
317 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
318 if (offset == INVALID_ADDRESS)
321 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
323 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
325 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
326 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
327 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
328 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
329 SWAP32 (iinfo->cli_cli_header.ch_size);
330 SWAP32 (iinfo->cli_cli_header.ch_flags);
331 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
332 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
333 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
334 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
335 SWAPPDE (iinfo->cli_cli_header.ch_resources);
336 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
337 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
338 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
339 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
340 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
341 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
342 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
343 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
344 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
345 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
346 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
347 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
348 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
353 /* Catch new uses of the fields that are supposed to be zero */
355 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
356 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
357 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
358 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
359 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
360 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
361 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
362 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
363 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
366 * No need to scare people who are testing this, I am just
367 * labelling this as a LAMESPEC
369 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
377 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
379 guint32 offset, size;
385 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
386 if (offset == INVALID_ADDRESS)
389 size = iinfo->cli_cli_header.ch_metadata.size;
391 if (offset + size > image->raw_data_len)
393 image->raw_metadata = image->raw_data + offset;
395 /* 24.2.1: Metadata root starts here */
396 ptr = image->raw_metadata;
398 if (strncmp (ptr, "BSJB", 4) == 0){
399 guint32 version_string_len;
402 image->md_version_major = read16 (ptr);
404 image->md_version_minor = read16 (ptr);
407 version_string_len = read32 (ptr);
409 image->version = g_strndup (ptr, version_string_len);
410 ptr += version_string_len;
411 pad = ptr - image->raw_metadata;
413 ptr += 4 - (pad % 4);
417 /* skip over flags */
420 streams = read16 (ptr);
423 for (i = 0; i < streams; i++){
424 if (strncmp (ptr + 8, "#~", 3) == 0){
425 image->heap_tables.data = image->raw_metadata + read32 (ptr);
426 image->heap_tables.size = read32 (ptr + 4);
428 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
429 image->heap_strings.data = image->raw_metadata + read32 (ptr);
430 image->heap_strings.size = read32 (ptr + 4);
432 } else if (strncmp (ptr + 8, "#US", 4) == 0){
433 image->heap_us.data = image->raw_metadata + read32 (ptr);
434 image->heap_us.size = read32 (ptr + 4);
436 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
437 image->heap_blob.data = image->raw_metadata + read32 (ptr);
438 image->heap_blob.size = read32 (ptr + 4);
440 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
441 image->heap_guid.data = image->raw_metadata + read32 (ptr);
442 image->heap_guid.size = read32 (ptr + 4);
444 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
445 image->heap_tables.data = image->raw_metadata + read32 (ptr);
446 image->heap_tables.size = read32 (ptr + 4);
448 image->uncompressed_metadata = TRUE;
449 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);
451 g_message ("Unknown heap type: %s\n", ptr + 8);
452 ptr += 8 + strlen (ptr + 8) + 1;
454 pad = ptr - image->raw_metadata;
456 ptr += 4 - (pad % 4);
459 g_assert (image->heap_guid.data);
460 g_assert (image->heap_guid.size >= 16);
462 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
468 * Load representation of logical metadata tables, from the "#~" stream
471 load_tables (MonoImage *image)
473 const char *heap_tables = image->heap_tables.data;
475 guint64 valid_mask, sorted_mask;
476 int valid = 0, table;
479 heap_sizes = heap_tables [6];
480 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
481 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
482 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
484 valid_mask = read64 (heap_tables + 8);
485 sorted_mask = read64 (heap_tables + 16);
486 rows = (const guint32 *) (heap_tables + 24);
488 for (table = 0; table < 64; table++){
489 if ((valid_mask & ((guint64) 1 << table)) == 0){
490 if (table > MONO_TABLE_LAST)
492 image->tables [table].rows = 0;
495 if (table > MONO_TABLE_LAST) {
496 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
498 image->tables [table].rows = read32 (rows);
500 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
501 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
507 image->tables_base = (heap_tables + 24) + (4 * valid);
509 /* They must be the same */
510 g_assert ((const void *) image->tables_base == (const void *) rows);
512 mono_metadata_compute_table_bases (image);
517 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
519 if (!load_metadata_ptrs (image, iinfo))
522 return load_tables (image);
526 mono_image_check_for_module_cctor (MonoImage *image)
528 MonoTableInfo *t, *mt;
529 t = &image->tables [MONO_TABLE_TYPEDEF];
530 mt = &image->tables [MONO_TABLE_METHOD];
531 if (image->dynamic) {
533 image->checked_module_cctor = TRUE;
537 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
538 const char *name = mono_metadata_string_heap (image, nameidx);
539 if (strcmp (name, "<Module>") == 0) {
540 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
543 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
545 last_method = mt->rows;
546 for (; first_method < last_method; first_method++) {
547 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
548 name = mono_metadata_string_heap (image, nameidx);
549 if (strcmp (name, ".cctor") == 0) {
550 image->has_module_cctor = TRUE;
551 image->checked_module_cctor = TRUE;
557 image->has_module_cctor = FALSE;
558 image->checked_module_cctor = TRUE;
562 load_modules (MonoImage *image)
569 t = &image->tables [MONO_TABLE_MODULEREF];
570 image->modules = g_new0 (MonoImage *, t->rows);
571 image->modules_loaded = g_new0 (gboolean, t->rows);
572 image->module_count = t->rows;
576 * mono_image_load_module:
578 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
579 * it cannot be loaded.
582 mono_image_load_module (MonoImage *image, int idx)
585 MonoTableInfo *file_table;
588 gboolean refonly = image->ref_only;
589 GList *list_iter, *valid_modules = NULL;
590 MonoImageOpenStatus status;
592 if ((image->module_count == 0) || (idx > image->module_count || idx <= 0))
594 if (image->modules_loaded [idx - 1])
595 return image->modules [idx - 1];
597 file_table = &image->tables [MONO_TABLE_FILE];
598 for (i = 0; i < file_table->rows; i++) {
599 guint32 cols [MONO_FILE_SIZE];
600 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
601 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
603 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
606 t = &image->tables [MONO_TABLE_MODULEREF];
607 base_dir = g_path_get_dirname (image->name);
612 guint32 cols [MONO_MODULEREF_SIZE];
613 /* if there is no file table, we try to load the module... */
614 int valid = file_table->rows == 0;
616 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
617 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
618 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
619 /* be safe with string dups, but we could just compare string indexes */
620 if (strcmp (list_iter->data, name) == 0) {
626 module_ref = g_build_filename (base_dir, name, NULL);
627 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
628 if (image->modules [idx - 1]) {
629 mono_image_addref (image->modules [idx - 1]);
630 image->modules [idx - 1]->assembly = image->assembly;
632 if (image->modules [idx - 1]->is_module_handle)
633 mono_image_fixup_vtable (image->modules [idx - 1]);
635 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
641 image->modules_loaded [idx - 1] = TRUE;
644 g_list_free (valid_modules);
646 return image->modules [idx - 1];
650 class_key_extract (gpointer value)
652 MonoClass *class = value;
654 return GUINT_TO_POINTER (class->type_token);
658 class_next_value (gpointer value)
660 MonoClass *class = value;
662 return (gpointer*)&class->next_class_cache;
666 mono_image_init (MonoImage *image)
668 image->mempool = mono_mempool_new_size (512);
669 mono_internal_hash_table_init (&image->class_cache,
673 image->field_cache = g_hash_table_new (NULL, NULL);
675 image->typespec_cache = g_hash_table_new (NULL, NULL);
676 image->memberref_signatures = g_hash_table_new (NULL, NULL);
677 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
678 image->method_signatures = g_hash_table_new (NULL, NULL);
680 image->property_hash = mono_property_hash_new ();
681 InitializeCriticalSection (&image->lock);
682 InitializeCriticalSection (&image->szarray_cache_lock);
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;
903 MonoDotNetHeader *header;
905 iinfo = image->image_info;
906 header = &iinfo->cli_header;
908 /* Load the CLI header */
909 if (!load_cli_header (image, iinfo))
912 if (!load_metadata (image, iinfo))
919 mono_image_load_names (MonoImage *image)
921 /* modules don't have an assembly table row */
922 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
923 image->assembly_name = mono_metadata_string_heap (image,
924 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
925 0, MONO_ASSEMBLY_NAME));
928 image->module_name = mono_metadata_string_heap (image,
929 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
930 0, MONO_MODULE_NAME));
934 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
935 gboolean care_about_cli, gboolean care_about_pecoff)
937 MonoCLIImageInfo *iinfo;
938 MonoDotNetHeader *header;
939 GSList *errors = NULL;
941 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
943 mono_image_init (image);
945 iinfo = image->image_info;
946 header = &iinfo->cli_header;
949 *status = MONO_IMAGE_IMAGE_INVALID;
951 if (care_about_pecoff == FALSE)
954 if (!mono_verifier_verify_pe_data (image, &errors))
957 if (!mono_image_load_pe_data (image))
960 if (care_about_cli == FALSE) {
964 if (!mono_verifier_verify_cli_data (image, &errors))
967 if (!mono_image_load_cli_data (image))
970 if (!mono_verifier_verify_table_data (image, &errors))
973 mono_image_load_names (image);
975 load_modules (image);
978 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
980 *status = MONO_IMAGE_OK;
986 MonoVerifyInfo *info = errors->data;
987 g_warning ("Could not load image %s due to %s", image->name, info->message);
988 mono_free_verify_list (errors);
990 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
991 mono_image_close (image);
996 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
997 gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
999 MonoCLIImageInfo *iinfo;
1003 if ((filed = mono_file_map_open (fname)) == NULL){
1004 if (IS_PORTABILITY_SET) {
1005 gchar *ffname = mono_portability_find_file (fname, TRUE);
1007 filed = mono_file_map_open (ffname);
1012 if (filed == NULL) {
1014 *status = MONO_IMAGE_ERROR_ERRNO;
1019 image = g_new0 (MonoImage, 1);
1020 image->raw_buffer_used = TRUE;
1021 image->raw_data_len = mono_file_map_size (filed);
1022 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);
1023 if (!image->raw_data) {
1024 mono_file_map_close (filed);
1027 *status = MONO_IMAGE_IMAGE_INVALID;
1030 iinfo = g_new0 (MonoCLIImageInfo, 1);
1031 image->image_info = iinfo;
1032 image->name = mono_path_resolve_symlinks (fname);
1033 image->ref_only = refonly;
1034 image->ref_count = 1;
1035 /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
1036 image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
1038 mono_file_map_close (filed);
1039 return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
1043 mono_image_loaded_full (const char *name, gboolean refonly)
1046 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1048 mono_images_lock ();
1049 res = g_hash_table_lookup (loaded_images, name);
1050 mono_images_unlock ();
1055 * mono_image_loaded:
1056 * @name: name of the image to load
1058 * This routine ensures that the given image is loaded.
1060 * Returns: the loaded MonoImage, or NULL on failure.
1063 mono_image_loaded (const char *name)
1065 return mono_image_loaded_full (name, FALSE);
1074 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1076 GuidData *data = user_data;
1082 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1087 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1090 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1094 mono_images_lock ();
1095 g_hash_table_foreach (loaded_images, find_by_guid, &data);
1096 mono_images_unlock ();
1101 mono_image_loaded_by_guid (const char *guid)
1103 return mono_image_loaded_by_guid_full (guid, FALSE);
1107 register_image (MonoImage *image)
1110 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1112 mono_images_lock ();
1113 image2 = g_hash_table_lookup (loaded_images, image->name);
1116 /* Somebody else beat us to it */
1117 mono_image_addref (image2);
1118 mono_images_unlock ();
1119 mono_image_close (image);
1122 g_hash_table_insert (loaded_images, image->name, image);
1123 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1124 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1125 mono_images_unlock ();
1131 mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
1133 MonoCLIImageInfo *iinfo;
1137 if (!data || !data_len) {
1139 *status = MONO_IMAGE_IMAGE_INVALID;
1144 datac = g_try_malloc (data_len);
1147 *status = MONO_IMAGE_ERROR_ERRNO;
1150 memcpy (datac, data, data_len);
1153 image = g_new0 (MonoImage, 1);
1154 image->raw_data = datac;
1155 image->raw_data_len = data_len;
1156 image->raw_data_allocated = need_copy;
1157 image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup(name);
1158 iinfo = g_new0 (MonoCLIImageInfo, 1);
1159 image->image_info = iinfo;
1160 image->ref_only = refonly;
1162 image = do_mono_image_load (image, status, TRUE, TRUE);
1166 return register_image (image);
1170 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1172 return mono_image_open_from_data_with_name (data, data_len, need_copy, status, refonly, NULL);
1176 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1178 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1182 /* fname is not duplicated. */
1184 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1187 MonoCLIImageInfo* iinfo;
1189 image = g_new0 (MonoImage, 1);
1190 image->raw_data = (char*) module_handle;
1191 image->is_module_handle = TRUE;
1192 iinfo = g_new0 (MonoCLIImageInfo, 1);
1193 image->image_info = iinfo;
1194 image->name = fname;
1195 image->ref_count = has_entry_point ? 0 : 1;
1196 image->has_entry_point = has_entry_point;
1198 image = do_mono_image_load (image, status, TRUE, TRUE);
1202 return register_image (image);
1207 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1210 GHashTable *loaded_images;
1213 g_return_val_if_fail (fname != NULL, NULL);
1216 /* Load modules using LoadLibrary. */
1217 if (!refonly && coree_module_handle) {
1218 HMODULE module_handle;
1219 guint16 *fname_utf16;
1222 absfname = mono_path_resolve_symlinks (fname);
1225 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1226 mono_images_lock ();
1227 image = g_hash_table_lookup (loaded_images_hash, absfname);
1229 g_assert (image->is_module_handle);
1230 if (image->has_entry_point && image->ref_count == 0) {
1231 /* Increment reference count on images loaded outside of the runtime. */
1232 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1233 /* The image is already loaded because _CorDllMain removes images from the hash. */
1234 module_handle = LoadLibrary (fname_utf16);
1235 g_assert (module_handle == (HMODULE) image->raw_data);
1237 mono_image_addref (image);
1238 mono_images_unlock ();
1240 g_free (fname_utf16);
1245 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1246 module_handle = MonoLoadImage (fname_utf16);
1247 if (status && module_handle == NULL)
1248 last_error = GetLastError ();
1250 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1251 image = g_hash_table_lookup (loaded_images_hash, absfname);
1253 mono_image_addref (image);
1254 mono_images_unlock ();
1256 g_free (fname_utf16);
1258 if (module_handle == NULL) {
1262 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1263 *status = MONO_IMAGE_IMAGE_INVALID;
1265 if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND)
1275 g_assert (image->is_module_handle);
1276 g_assert (image->has_entry_point);
1281 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1285 absfname = mono_path_canonicalize (fname);
1288 * The easiest solution would be to do all the loading inside the mutex,
1289 * but that would lead to scalability problems. So we let the loading
1290 * happen outside the mutex, and if multiple threads happen to load
1291 * the same image, we discard all but the first copy.
1293 mono_images_lock ();
1294 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1295 image = g_hash_table_lookup (loaded_images, absfname);
1299 mono_image_addref (image);
1300 mono_images_unlock ();
1303 mono_images_unlock ();
1305 image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1309 return register_image (image);
1314 * @fname: filename that points to the module we want to open
1315 * @status: An error condition is returned in this field
1317 * Returns: An open image of type %MonoImage or NULL on error.
1318 * The caller holds a temporary reference to the returned image which should be cleared
1319 * when no longer needed by calling mono_image_close ().
1320 * if NULL, then check the value of @status for details on the error
1323 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1325 return mono_image_open_full (fname, status, FALSE);
1329 * mono_pe_file_open:
1330 * @fname: filename that points to the module we want to open
1331 * @status: An error condition is returned in this field
1333 * Returns: An open image of type %MonoImage or NULL on error. if
1334 * NULL, then check the value of @status for details on the error.
1335 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1336 * It's just a PE file loader, used for FileVersionInfo. It also does
1337 * not use the image cache.
1340 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1342 g_return_val_if_fail (fname != NULL, NULL);
1344 return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1348 * mono_image_open_raw
1349 * @fname: filename that points to the module we want to open
1350 * @status: An error condition is returned in this field
1352 * Returns an image without loading neither pe or cli data.
1354 * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
1357 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1359 g_return_val_if_fail (fname != NULL, NULL);
1361 return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1365 mono_image_fixup_vtable (MonoImage *image)
1368 MonoCLIImageInfo *iinfo;
1370 MonoVTableFixup *vtfixup;
1376 g_assert (image->is_module_handle);
1378 iinfo = image->image_info;
1379 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1380 if (!de->rva || !de->size)
1382 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1386 count = de->size / sizeof (MonoVTableFixup);
1388 if (!vtfixup->rva || !vtfixup->count)
1391 slot = mono_image_rva_map (image, vtfixup->rva);
1393 slot_type = vtfixup->type;
1394 slot_count = vtfixup->count;
1395 if (slot_type & VTFIXUP_TYPE_32BIT)
1396 while (slot_count--) {
1397 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1398 slot = ((guint32*) slot) + 1;
1400 else if (slot_type & VTFIXUP_TYPE_64BIT)
1401 while (slot_count--) {
1402 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1403 slot = ((guint32*) slot) + 1;
1406 g_assert_not_reached();
1411 g_assert_not_reached();
1416 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1418 g_hash_table_destroy ((GHashTable*)val);
1423 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1425 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1430 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1432 g_slist_free ((GSList*)val);
1436 * mono_image_addref:
1437 * @image: The image file we wish to add a reference to
1439 * Increases the reference count of an image.
1442 mono_image_addref (MonoImage *image)
1444 InterlockedIncrement (&image->ref_count);
1448 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1450 stream->alloc_size = stream->index = stream->offset = 0;
1451 g_free (stream->data);
1452 stream->data = NULL;
1454 g_hash_table_destroy (stream->hash);
1455 stream->hash = NULL;
1460 free_hash (GHashTable *hash)
1463 g_hash_table_destroy (hash);
1467 * Returns whether mono_image_close_finish() must be called as well.
1468 * We must unload images in two steps because clearing the domain in
1469 * SGen requires the class metadata to be intact, but we need to free
1470 * the mono_g_hash_tables in case a collection occurs during domain
1471 * unloading and the roots would trip up the GC.
1474 mono_image_close_except_pools (MonoImage *image)
1477 GHashTable *loaded_images;
1481 g_return_val_if_fail (image != NULL, FALSE);
1484 * Atomically decrement the refcount and remove ourselves from the hash tables, so
1485 * register_image () can't grab an image which is being closed.
1487 mono_images_lock ();
1489 if (InterlockedDecrement (&image->ref_count) > 0) {
1490 mono_images_unlock ();
1494 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1495 image2 = g_hash_table_lookup (loaded_images, image->name);
1496 if (image == image2) {
1497 /* This is not true if we are called from mono_image_open () */
1498 g_hash_table_remove (loaded_images, image->name);
1500 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1501 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1503 mono_images_unlock ();
1506 if (image->is_module_handle && image->has_entry_point) {
1507 mono_images_lock ();
1508 if (image->ref_count == 0) {
1509 /* Image will be closed by _CorDllMain. */
1510 FreeLibrary ((HMODULE) image->raw_data);
1511 mono_images_unlock ();
1514 mono_images_unlock ();
1518 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1520 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1522 mono_image_invoke_unload_hook (image);
1524 free_list = mono_metadata_clean_for_image (image);
1527 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1528 * assemblies, so we can't release these references in mono_assembly_close () since the
1529 * MonoImage might outlive its associated MonoAssembly.
1531 if (image->references && !image->dynamic) {
1532 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1535 for (i = 0; i < t->rows; 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)
1557 mono_file_unmap (image->raw_data, image->raw_data_handle);
1560 if (image->raw_data_allocated) {
1561 /* FIXME: do we need this? (image is disposed anyway) */
1562 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1563 MonoCLIImageInfo *ii = image->image_info;
1565 if ((image->raw_metadata > image->raw_data) &&
1566 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1567 image->raw_metadata = NULL;
1569 for (i = 0; i < ii->cli_section_count; i++)
1570 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1571 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1572 ii->cli_sections [i] = NULL;
1574 g_free (image->raw_data);
1577 if (debug_assembly_unload) {
1578 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1580 g_free (image->name);
1581 g_free (image->guid);
1582 g_free (image->version);
1583 g_free (image->files);
1586 if (image->method_cache)
1587 g_hash_table_destroy (image->method_cache);
1588 if (image->methodref_cache)
1589 g_hash_table_destroy (image->methodref_cache);
1590 mono_internal_hash_table_destroy (&image->class_cache);
1591 g_hash_table_destroy (image->field_cache);
1592 if (image->array_cache) {
1593 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1594 g_hash_table_destroy (image->array_cache);
1596 if (image->szarray_cache)
1597 g_hash_table_destroy (image->szarray_cache);
1598 if (image->ptr_cache)
1599 g_hash_table_destroy (image->ptr_cache);
1600 if (image->name_cache) {
1601 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1602 g_hash_table_destroy (image->name_cache);
1605 free_hash (image->native_wrapper_cache);
1606 free_hash (image->managed_wrapper_cache);
1607 free_hash (image->delegate_begin_invoke_cache);
1608 free_hash (image->delegate_end_invoke_cache);
1609 free_hash (image->delegate_invoke_cache);
1610 free_hash (image->delegate_abstract_invoke_cache);
1611 free_hash (image->delegate_bound_static_invoke_cache);
1612 free_hash (image->remoting_invoke_cache);
1613 free_hash (image->runtime_invoke_cache);
1614 free_hash (image->runtime_invoke_direct_cache);
1615 free_hash (image->runtime_invoke_vcall_cache);
1616 free_hash (image->synchronized_cache);
1617 free_hash (image->unbox_wrapper_cache);
1618 free_hash (image->cominterop_invoke_cache);
1619 free_hash (image->cominterop_wrapper_cache);
1620 free_hash (image->typespec_cache);
1621 free_hash (image->ldfld_wrapper_cache);
1622 free_hash (image->ldflda_wrapper_cache);
1623 free_hash (image->stfld_wrapper_cache);
1624 free_hash (image->isinst_cache);
1625 free_hash (image->castclass_cache);
1626 free_hash (image->proxy_isinst_cache);
1627 free_hash (image->thunk_invoke_cache);
1629 /* The ownership of signatures is not well defined */
1630 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1631 g_hash_table_destroy (image->memberref_signatures);
1632 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1633 g_hash_table_destroy (image->helper_signatures);
1634 g_hash_table_destroy (image->method_signatures);
1636 if (image->rgctx_template_hash)
1637 g_hash_table_destroy (image->rgctx_template_hash);
1639 if (image->property_hash)
1640 mono_property_hash_destroy (image->property_hash);
1642 g_slist_free (image->reflection_info_unregister_classes);
1643 image->reflection_info_unregister_classes = free_list;
1645 if (image->interface_bitset) {
1646 mono_unload_interface_ids (image->interface_bitset);
1647 mono_bitset_free (image->interface_bitset);
1649 if (image->image_info){
1650 MonoCLIImageInfo *ii = image->image_info;
1652 if (ii->cli_section_tables)
1653 g_free (ii->cli_section_tables);
1654 if (ii->cli_sections)
1655 g_free (ii->cli_sections);
1656 g_free (image->image_info);
1659 for (i = 0; i < image->module_count; ++i) {
1660 if (image->modules [i]) {
1661 if (!mono_image_close_except_pools (image->modules [i]))
1662 image->modules [i] = NULL;
1665 if (image->modules_loaded)
1666 g_free (image->modules_loaded);
1668 DeleteCriticalSection (&image->szarray_cache_lock);
1669 DeleteCriticalSection (&image->lock);
1671 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1672 if (image->dynamic) {
1673 /* Dynamic images are GC_MALLOCed */
1674 g_free ((char*)image->module_name);
1675 mono_dynamic_image_free ((MonoDynamicImage*)image);
1678 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1684 mono_image_close_finish (MonoImage *image)
1689 for (l = image->reflection_info_unregister_classes; l; l = l->next)
1691 g_slist_free (image->reflection_info_unregister_classes);
1692 image->reflection_info_unregister_classes = NULL;
1694 if (image->references && !image->dynamic) {
1695 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1698 for (i = 0; i < t->rows; i++) {
1699 if (image->references [i] && image->references [i] != REFERENCE_MISSING)
1700 mono_assembly_close_finish (image->references [i]);
1703 g_free (image->references);
1704 image->references = NULL;
1707 for (i = 0; i < image->module_count; ++i) {
1708 if (image->modules [i])
1709 mono_image_close_finish (image->modules [i]);
1712 g_free (image->modules);
1714 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1716 if (!image->dynamic) {
1717 if (debug_assembly_unload)
1718 mono_mempool_invalidate (image->mempool);
1720 mono_mempool_destroy (image->mempool);
1724 if (debug_assembly_unload)
1725 mono_mempool_invalidate (image->mempool);
1727 mono_mempool_destroy (image->mempool);
1733 * @image: The image file we wish to close
1735 * Closes an image file, deallocates all memory consumed and
1736 * unmaps all possible sections of the file
1739 mono_image_close (MonoImage *image)
1741 if (mono_image_close_except_pools (image))
1742 mono_image_close_finish (image);
1746 * mono_image_strerror:
1747 * @status: an code indicating the result from a recent operation
1749 * Returns: a string describing the error
1752 mono_image_strerror (MonoImageOpenStatus status)
1757 case MONO_IMAGE_ERROR_ERRNO:
1758 return strerror (errno);
1759 case MONO_IMAGE_IMAGE_INVALID:
1760 return "File does not contain a valid CIL image";
1761 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1762 return "An assembly was referenced, but could not be found";
1764 return "Internal error";
1768 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1769 guint32 lang_id, gunichar2 *name,
1770 MonoPEResourceDirEntry *entry,
1771 MonoPEResourceDir *root, guint32 level)
1773 gboolean is_string, is_dir;
1774 guint32 name_offset, dir_offset;
1776 /* Level 0 holds a directory entry for each type of resource
1777 * (identified by ID or name).
1779 * Level 1 holds a directory entry for each named resource
1780 * item, and each "anonymous" item of a particular type of
1783 * Level 2 holds a directory entry for each language pointing to
1786 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1787 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1789 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1790 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1795 } else if (level==1) {
1796 if (res_id != name_offset)
1800 is_string==TRUE && name!=lookup (name_offset)) {
1804 } else if (level==2) {
1805 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1808 g_assert_not_reached ();
1812 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1813 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1816 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1818 for(i=0; i<entries; i++) {
1819 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1822 ret=mono_image_walk_resource_tree (info, res_id,
1833 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1834 MonoPEResourceDataEntry *res;
1836 res = g_new0 (MonoPEResourceDataEntry, 1);
1838 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1839 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1840 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1841 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1848 * mono_image_lookup_resource:
1849 * @image: the image to look up the resource in
1850 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1851 * @lang_id: The language id.
1852 * @name: the resource name to lookup.
1854 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1855 * of the given resource. The caller should free it using g_free () when no longer
1859 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1861 MonoCLIImageInfo *info;
1862 MonoDotNetHeader *header;
1863 MonoPEDatadir *datadir;
1864 MonoPEDirEntry *rsrc;
1865 MonoPEResourceDir *resource_dir;
1866 MonoPEResourceDirEntry *res_entries;
1873 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1875 info=image->image_info;
1880 header=&info->cli_header;
1885 datadir=&header->datadir;
1890 rsrc=&datadir->pe_resource_table;
1895 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1896 if(resource_dir==NULL) {
1900 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1901 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1903 for(i=0; i<entries; i++) {
1904 MonoPEResourceDirEntry *entry=&res_entries[i];
1907 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1908 name, entry, resource_dir,
1919 * mono_image_get_entry_point:
1920 * @image: the image where the entry point will be looked up.
1922 * Use this routine to determine the metadata token for method that
1923 * has been flagged as the entry point.
1925 * Returns: the token for the entry point method in the image
1928 mono_image_get_entry_point (MonoImage *image)
1930 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1934 * mono_image_get_resource:
1935 * @image: the image where the resource will be looked up.
1936 * @offset: The offset to add to the resource
1937 * @size: a pointer to an int where the size of the resource will be stored
1939 * This is a low-level routine that fetches a resource from the
1940 * metadata that starts at a given @offset. The @size parameter is
1941 * filled with the data field as encoded in the metadata.
1943 * Returns: the pointer to the resource whose offset is @offset.
1946 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1948 MonoCLIImageInfo *iinfo = image->image_info;
1949 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1952 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1955 data = mono_image_rva_map (image, ch->ch_resources.rva);
1960 *size = read32 (data);
1966 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1968 char *base_dir, *name;
1970 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1974 if (fileidx < 1 || fileidx > t->rows)
1977 mono_loader_lock ();
1978 if (image->files && image->files [fileidx - 1]) {
1979 mono_loader_unlock ();
1980 return image->files [fileidx - 1];
1984 image->files = g_new0 (MonoImage*, t->rows);
1986 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1987 fname = mono_metadata_string_heap (image, fname_id);
1988 base_dir = g_path_get_dirname (image->name);
1989 name = g_build_filename (base_dir, fname, NULL);
1990 res = mono_image_open (name, NULL);
1993 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1994 res->assembly = image->assembly;
1995 for (i = 0; i < res->module_count; ++i) {
1996 if (res->modules [i] && !res->modules [i]->assembly)
1997 res->modules [i]->assembly = image->assembly;
2000 image->files [fileidx - 1] = res;
2002 if (res->is_module_handle)
2003 mono_image_fixup_vtable (res);
2006 mono_loader_unlock ();
2013 * mono_image_get_strong_name:
2014 * @image: a MonoImage
2015 * @size: a guint32 pointer, or NULL.
2017 * If the image has a strong name, and @size is not NULL, the value
2018 * pointed to by size will have the size of the strong name.
2020 * Returns: NULL if the image does not have a strong name, or a
2021 * pointer to the public key.
2024 mono_image_get_strong_name (MonoImage *image, guint32 *size)
2026 MonoCLIImageInfo *iinfo = image->image_info;
2027 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2030 if (!de->size || !de->rva)
2032 data = mono_image_rva_map (image, de->rva);
2041 * mono_image_strong_name_position:
2042 * @image: a MonoImage
2043 * @size: a guint32 pointer, or NULL.
2045 * If the image has a strong name, and @size is not NULL, the value
2046 * pointed to by size will have the size of the strong name.
2048 * Returns: the position within the image file where the strong name
2052 mono_image_strong_name_position (MonoImage *image, guint32 *size)
2054 MonoCLIImageInfo *iinfo = image->image_info;
2055 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
2060 if (!de->size || !de->rva)
2062 pos = mono_cli_rva_image_map (image, de->rva);
2063 return pos == INVALID_ADDRESS ? 0 : pos;
2067 * mono_image_get_public_key:
2068 * @image: a MonoImage
2069 * @size: a guint32 pointer, or NULL.
2071 * This is used to obtain the public key in the @image.
2073 * If the image has a public key, and @size is not NULL, the value
2074 * pointed to by size will have the size of the public key.
2076 * Returns: NULL if the image does not have a public key, or a pointer
2077 * to the public key.
2080 mono_image_get_public_key (MonoImage *image, guint32 *size)
2085 if (image->dynamic) {
2087 *size = ((MonoDynamicImage*)image)->public_key_len;
2088 return (char*)((MonoDynamicImage*)image)->public_key;
2090 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
2092 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
2095 pubkey = mono_metadata_blob_heap (image, tok);
2096 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
2103 * mono_image_get_name:
2104 * @name: a MonoImage
2106 * Returns: the name of the assembly.
2109 mono_image_get_name (MonoImage *image)
2111 return image->assembly_name;
2115 * mono_image_get_filename:
2116 * @image: a MonoImage
2118 * Used to get the filename that hold the actual MonoImage
2120 * Returns: the filename.
2123 mono_image_get_filename (MonoImage *image)
2129 mono_image_get_guid (MonoImage *image)
2134 const MonoTableInfo*
2135 mono_image_get_table_info (MonoImage *image, int table_id)
2137 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2139 return &image->tables [table_id];
2143 mono_image_get_table_rows (MonoImage *image, int table_id)
2145 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2147 return image->tables [table_id].rows;
2151 mono_table_info_get_rows (const MonoTableInfo *table)
2157 * mono_image_get_assembly:
2158 * @image: the MonoImage.
2160 * Use this routine to get the assembly that owns this image.
2162 * Returns: the assembly that holds this image.
2165 mono_image_get_assembly (MonoImage *image)
2167 return image->assembly;
2171 * mono_image_is_dynamic:
2172 * @image: the MonoImage
2174 * Determines if the given image was created dynamically through the
2175 * System.Reflection.Emit API
2177 * Returns: TRUE if the image was created dynamically, FALSE if not.
2180 mono_image_is_dynamic (MonoImage *image)
2182 return image->dynamic;
2186 * mono_image_has_authenticode_entry:
2187 * @image: the MonoImage
2189 * Use this routine to determine if the image has a Authenticode
2190 * Certificate Table.
2192 * Returns: TRUE if the image contains an authenticode entry in the PE
2196 mono_image_has_authenticode_entry (MonoImage *image)
2198 MonoCLIImageInfo *iinfo = image->image_info;
2199 MonoDotNetHeader *header = &iinfo->cli_header;
2200 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2201 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2202 return ((de->rva != 0) && (de->size > 8));
2206 mono_image_alloc (MonoImage *image, guint size)
2210 mono_perfcounters->loader_bytes += size;
2211 mono_image_lock (image);
2212 res = mono_mempool_alloc (image->mempool, size);
2213 mono_image_unlock (image);
2219 mono_image_alloc0 (MonoImage *image, guint size)
2223 mono_perfcounters->loader_bytes += size;
2224 mono_image_lock (image);
2225 res = mono_mempool_alloc0 (image->mempool, size);
2226 mono_image_unlock (image);
2232 mono_image_strdup (MonoImage *image, const char *s)
2236 mono_perfcounters->loader_bytes += strlen (s);
2237 mono_image_lock (image);
2238 res = mono_mempool_strdup (image->mempool, s);
2239 mono_image_unlock (image);
2245 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2249 new_list = mono_image_alloc (image, sizeof (GList));
2250 new_list->data = data;
2251 new_list->prev = list ? list->prev : NULL;
2252 new_list->next = list;
2255 new_list->prev->next = new_list;
2257 list->prev = new_list;
2263 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2267 new_list = mono_image_alloc (image, sizeof (GSList));
2268 new_list->data = data;
2269 new_list->next = NULL;
2271 return g_slist_concat (list, new_list);
2275 mono_image_lock (MonoImage *image)
2277 mono_locks_acquire (&image->lock, ImageDataLock);
2281 mono_image_unlock (MonoImage *image)
2283 mono_locks_release (&image->lock, ImageDataLock);
2288 * mono_image_property_lookup:
2290 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2292 * LOCKING: Takes the image lock
2295 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2299 mono_image_lock (image);
2300 res = mono_property_hash_lookup (image->property_hash, subject, property);
2301 mono_image_unlock (image);
2307 * mono_image_property_insert:
2309 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2311 * LOCKING: Takes the image lock
2314 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2316 mono_image_lock (image);
2317 mono_property_hash_insert (image->property_hash, subject, property, value);
2318 mono_image_unlock (image);
2322 * mono_image_property_remove:
2324 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2326 * LOCKING: Takes the image lock
2329 mono_image_property_remove (MonoImage *image, gpointer subject)
2331 mono_image_lock (image);
2332 mono_property_hash_remove_object (image->property_hash, subject);
2333 mono_image_unlock (image);