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.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() EnterCriticalSection (&images_mutex)
56 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
57 static CRITICAL_SECTION images_mutex;
59 /* returns offset relative to image->raw_data */
61 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
63 MonoCLIImageInfo *iinfo = image->image_info;
64 const int top = iinfo->cli_section_count;
65 MonoSectionTable *tables = iinfo->cli_section_tables;
68 for (i = 0; i < top; i++){
69 if ((addr >= tables->st_virtual_address) &&
70 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
72 if (image->is_module_handle)
75 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
79 return INVALID_ADDRESS;
83 * mono_images_rva_map:
85 * @addr: relative virtual address (RVA)
87 * This is a low-level routine used by the runtime to map relative
88 * virtual address (RVA) into their location in memory.
90 * Returns: the address in memory for the given RVA, or NULL if the
91 * RVA is not valid for this image.
94 mono_image_rva_map (MonoImage *image, guint32 addr)
96 MonoCLIImageInfo *iinfo = image->image_info;
97 const int top = iinfo->cli_section_count;
98 MonoSectionTable *tables = iinfo->cli_section_tables;
101 for (i = 0; i < top; i++){
102 if ((addr >= tables->st_virtual_address) &&
103 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
104 if (!iinfo->cli_sections [i]) {
105 if (!mono_image_ensure_section_idx (image, i))
108 #ifdef PLATFORM_WIN32
109 if (image->is_module_handle)
110 return image->raw_data + addr;
112 return (char*)iinfo->cli_sections [i] +
113 (addr - tables->st_virtual_address);
123 * Initialize the global variables used by this module.
126 mono_images_init (void)
128 InitializeCriticalSection (&images_mutex);
130 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
131 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
133 debug_assembly_unload = g_getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
137 * mono_images_cleanup:
139 * Free all resources used by this module.
142 mono_images_cleanup (void)
144 DeleteCriticalSection (&images_mutex);
146 g_hash_table_destroy (loaded_images_hash);
147 g_hash_table_destroy (loaded_images_refonly_hash);
151 * mono_image_ensure_section_idx:
152 * @image: The image we are operating on
153 * @section: section number that we will load/map into memory
155 * This routine makes sure that we have an in-memory copy of
156 * an image section (.text, .rsrc, .data).
158 * Returns: TRUE on success
161 mono_image_ensure_section_idx (MonoImage *image, int section)
163 MonoCLIImageInfo *iinfo = image->image_info;
164 MonoSectionTable *sect;
167 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
169 if (iinfo->cli_sections [section] != NULL)
172 sect = &iinfo->cli_section_tables [section];
174 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
176 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
178 #ifdef PLATFORM_WIN32
179 if (image->is_module_handle)
180 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
183 /* FIXME: we ignore the writable flag since we don't patch the binary */
184 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
189 * mono_image_ensure_section:
190 * @image: The image we are operating on
191 * @section: section name 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 (MonoImage *image, const char *section)
201 MonoCLIImageInfo *ii = image->image_info;
204 for (i = 0; i < ii->cli_section_count; i++){
205 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
208 return mono_image_ensure_section_idx (image, i);
214 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
216 const int top = iinfo->cli_header.coff.coff_sections;
219 iinfo->cli_section_count = top;
220 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
221 iinfo->cli_sections = g_new0 (void *, top);
223 for (i = 0; i < top; i++){
224 MonoSectionTable *t = &iinfo->cli_section_tables [i];
226 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
228 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
229 offset += sizeof (MonoSectionTable);
231 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
232 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
233 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
234 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
235 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
236 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
237 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
238 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
239 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
240 t->st_flags = GUINT32_FROM_LE (t->st_flags);
242 /* consistency checks here */
249 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
253 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
254 if (offset == INVALID_ADDRESS)
257 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
259 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
261 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
262 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
263 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
264 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
265 SWAP32 (iinfo->cli_cli_header.ch_size);
266 SWAP32 (iinfo->cli_cli_header.ch_flags);
267 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
268 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
269 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
270 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
271 SWAPPDE (iinfo->cli_cli_header.ch_resources);
272 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
273 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
274 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
275 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
276 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
277 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
278 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
279 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
280 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
281 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
282 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
283 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
284 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
289 /* Catch new uses of the fields that are supposed to be zero */
291 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
292 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
293 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
294 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
295 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
296 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
297 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
298 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
299 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
302 * No need to scare people who are testing this, I am just
303 * labelling this as a LAMESPEC
305 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
313 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
315 guint32 offset, size;
321 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
322 if (offset == INVALID_ADDRESS)
325 size = iinfo->cli_cli_header.ch_metadata.size;
327 if (offset + size > image->raw_data_len)
329 image->raw_metadata = image->raw_data + offset;
331 ptr = image->raw_metadata;
333 if (strncmp (ptr, "BSJB", 4) == 0){
334 guint32 version_string_len;
337 image->md_version_major = read16 (ptr);
339 image->md_version_minor = read16 (ptr);
342 version_string_len = read32 (ptr);
344 image->version = g_strndup (ptr, version_string_len);
345 ptr += version_string_len;
346 pad = ptr - image->raw_metadata;
348 ptr += 4 - (pad % 4);
352 /* skip over flags */
355 streams = read16 (ptr);
358 for (i = 0; i < streams; i++){
359 if (strncmp (ptr + 8, "#~", 3) == 0){
360 image->heap_tables.data = image->raw_metadata + read32 (ptr);
361 image->heap_tables.size = read32 (ptr + 4);
363 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
364 image->heap_strings.data = image->raw_metadata + read32 (ptr);
365 image->heap_strings.size = read32 (ptr + 4);
367 } else if (strncmp (ptr + 8, "#US", 4) == 0){
368 image->heap_us.data = image->raw_metadata + read32 (ptr);
369 image->heap_us.size = read32 (ptr + 4);
371 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
372 image->heap_blob.data = image->raw_metadata + read32 (ptr);
373 image->heap_blob.size = read32 (ptr + 4);
375 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
376 image->heap_guid.data = image->raw_metadata + read32 (ptr);
377 image->heap_guid.size = read32 (ptr + 4);
379 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
380 image->heap_tables.data = image->raw_metadata + read32 (ptr);
381 image->heap_tables.size = read32 (ptr + 4);
383 image->uncompressed_metadata = TRUE;
384 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);
386 g_message ("Unknown heap type: %s\n", ptr + 8);
387 ptr += 8 + strlen (ptr + 8) + 1;
389 pad = ptr - image->raw_metadata;
391 ptr += 4 - (pad % 4);
394 g_assert (image->heap_guid.data);
395 g_assert (image->heap_guid.size >= 16);
397 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
403 * Load representation of logical metadata tables, from the "#~" stream
406 load_tables (MonoImage *image)
408 const char *heap_tables = image->heap_tables.data;
410 guint64 valid_mask, sorted_mask;
411 int valid = 0, table;
414 heap_sizes = heap_tables [6];
415 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
416 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
417 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
419 valid_mask = read64 (heap_tables + 8);
420 sorted_mask = read64 (heap_tables + 16);
421 rows = (const guint32 *) (heap_tables + 24);
423 for (table = 0; table < 64; table++){
424 if ((valid_mask & ((guint64) 1 << table)) == 0){
425 if (table > MONO_TABLE_LAST)
427 image->tables [table].rows = 0;
430 if (table > MONO_TABLE_LAST) {
431 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
433 image->tables [table].rows = read32 (rows);
435 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
436 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
442 image->tables_base = (heap_tables + 24) + (4 * valid);
444 /* They must be the same */
445 g_assert ((const void *) image->tables_base == (const void *) rows);
447 mono_metadata_compute_table_bases (image);
452 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
454 if (!load_metadata_ptrs (image, iinfo))
457 return load_tables (image);
461 mono_image_check_for_module_cctor (MonoImage *image)
463 MonoTableInfo *t, *mt;
464 t = &image->tables [MONO_TABLE_TYPEDEF];
465 mt = &image->tables [MONO_TABLE_METHOD];
466 if (mono_framework_version () == 1) {
467 image->checked_module_cctor = TRUE;
470 if (image->dynamic) {
472 image->checked_module_cctor = TRUE;
476 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
477 const char *name = mono_metadata_string_heap (image, nameidx);
478 if (strcmp (name, "<Module>") == 0) {
479 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
482 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
484 last_method = mt->rows;
485 for (; first_method < last_method; first_method++) {
486 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
487 name = mono_metadata_string_heap (image, nameidx);
488 if (strcmp (name, ".cctor") == 0) {
489 image->has_module_cctor = TRUE;
490 image->checked_module_cctor = TRUE;
496 image->has_module_cctor = FALSE;
497 image->checked_module_cctor = TRUE;
501 load_modules (MonoImage *image)
508 t = &image->tables [MONO_TABLE_MODULEREF];
509 image->modules = g_new0 (MonoImage *, t->rows);
510 image->modules_loaded = g_new0 (gboolean, t->rows);
511 image->module_count = t->rows;
515 * mono_image_load_module:
517 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
518 * it cannot be loaded.
521 mono_image_load_module (MonoImage *image, int idx)
524 MonoTableInfo *file_table;
527 gboolean refonly = image->ref_only;
528 GList *list_iter, *valid_modules = NULL;
529 MonoImageOpenStatus status;
531 g_assert (idx <= image->module_count);
532 if (image->modules_loaded [idx - 1])
533 return image->modules [idx - 1];
535 file_table = &image->tables [MONO_TABLE_FILE];
536 for (i = 0; i < file_table->rows; i++) {
537 guint32 cols [MONO_FILE_SIZE];
538 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
539 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
541 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
544 t = &image->tables [MONO_TABLE_MODULEREF];
545 base_dir = g_path_get_dirname (image->name);
550 guint32 cols [MONO_MODULEREF_SIZE];
551 /* if there is no file table, we try to load the module... */
552 int valid = file_table->rows == 0;
554 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
555 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
556 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
557 /* be safe with string dups, but we could just compare string indexes */
558 if (strcmp (list_iter->data, name) == 0) {
564 module_ref = g_build_filename (base_dir, name, NULL);
565 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
566 if (image->modules [idx - 1]) {
567 mono_image_addref (image->modules [idx - 1]);
568 image->modules [idx - 1]->assembly = image->assembly;
569 #ifdef PLATFORM_WIN32
570 if (image->modules [idx - 1]->is_module_handle)
571 mono_image_fixup_vtable (image->modules [idx - 1]);
573 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
579 image->modules_loaded [idx - 1] = TRUE;
582 g_list_free (valid_modules);
584 return image->modules [idx - 1];
588 class_key_extract (gpointer value)
590 MonoClass *class = value;
592 return GUINT_TO_POINTER (class->type_token);
596 class_next_value (gpointer value)
598 MonoClass *class = value;
600 return (gpointer*)&class->next_class_cache;
604 mono_image_init (MonoImage *image)
606 image->mempool = mono_mempool_new_size (512);
607 mono_internal_hash_table_init (&image->class_cache,
611 image->field_cache = g_hash_table_new (NULL, NULL);
613 image->typespec_cache = g_hash_table_new (NULL, NULL);
614 image->memberref_signatures = g_hash_table_new (NULL, NULL);
615 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
616 image->method_signatures = g_hash_table_new (NULL, NULL);
618 image->property_hash = mono_property_hash_new ();
619 InitializeCriticalSection (&image->lock);
620 InitializeCriticalSection (&image->szarray_cache_lock);
623 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
624 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
625 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
626 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
627 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
636 * Returns < 0 to indicate an error.
639 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
641 MonoDotNetHeader64 header64;
643 #ifdef PLATFORM_WIN32
644 if (!image->is_module_handle)
646 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
649 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
651 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
654 /* endian swap the fields common between PE and PE+ */
655 SWAP32 (header->coff.coff_time);
656 SWAP32 (header->coff.coff_symptr);
657 SWAP32 (header->coff.coff_symcount);
658 SWAP16 (header->coff.coff_machine);
659 SWAP16 (header->coff.coff_sections);
660 SWAP16 (header->coff.coff_opt_header_size);
661 SWAP16 (header->coff.coff_attributes);
663 SWAP32 (header->pe.pe_code_size);
664 SWAP32 (header->pe.pe_uninit_data_size);
665 SWAP32 (header->pe.pe_rva_entry_point);
666 SWAP32 (header->pe.pe_rva_code_base);
667 SWAP32 (header->pe.pe_rva_data_base);
668 SWAP16 (header->pe.pe_magic);
670 /* now we are ready for the basic tests */
672 if (header->pe.pe_magic == 0x10B) {
673 offset += sizeof (MonoDotNetHeader);
674 SWAP32 (header->pe.pe_data_size);
675 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
678 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
679 SWAP32 (header->nt.pe_stack_reserve);
680 SWAP32 (header->nt.pe_stack_commit);
681 SWAP32 (header->nt.pe_heap_reserve);
682 SWAP32 (header->nt.pe_heap_commit);
683 } else if (header->pe.pe_magic == 0x20B) {
684 /* PE32+ file format */
685 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
687 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
688 offset += sizeof (MonoDotNetHeader64);
689 /* copy the fields already swapped. the last field, pe_data_size, is missing */
690 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
691 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
692 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
694 SWAP64 (header64.nt.pe_image_base);
695 header->nt.pe_image_base = header64.nt.pe_image_base;
696 SWAP64 (header64.nt.pe_stack_reserve);
697 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
698 SWAP64 (header64.nt.pe_stack_commit);
699 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
700 SWAP64 (header64.nt.pe_heap_reserve);
701 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
702 SWAP64 (header64.nt.pe_heap_commit);
703 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
705 header->nt.pe_section_align = header64.nt.pe_section_align;
706 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
707 header->nt.pe_os_major = header64.nt.pe_os_major;
708 header->nt.pe_os_minor = header64.nt.pe_os_minor;
709 header->nt.pe_user_major = header64.nt.pe_user_major;
710 header->nt.pe_user_minor = header64.nt.pe_user_minor;
711 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
712 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
713 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
714 header->nt.pe_image_size = header64.nt.pe_image_size;
715 header->nt.pe_header_size = header64.nt.pe_header_size;
716 header->nt.pe_checksum = header64.nt.pe_checksum;
717 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
718 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
719 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
720 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
722 /* copy the datadir */
723 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
728 /* MonoPEHeaderNT: not used yet */
729 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
730 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
731 SWAP16 (header->nt.pe_os_major); /* must be 4 */
732 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
733 SWAP16 (header->nt.pe_user_major);
734 SWAP16 (header->nt.pe_user_minor);
735 SWAP16 (header->nt.pe_subsys_major);
736 SWAP16 (header->nt.pe_subsys_minor);
737 SWAP32 (header->nt.pe_reserved_1);
738 SWAP32 (header->nt.pe_image_size);
739 SWAP32 (header->nt.pe_header_size);
740 SWAP32 (header->nt.pe_checksum);
741 SWAP16 (header->nt.pe_subsys_required);
742 SWAP16 (header->nt.pe_dll_flags);
743 SWAP32 (header->nt.pe_loader_flags);
744 SWAP32 (header->nt.pe_data_dir_count);
746 /* MonoDotNetHeader: mostly unused */
747 SWAPPDE (header->datadir.pe_export_table);
748 SWAPPDE (header->datadir.pe_import_table);
749 SWAPPDE (header->datadir.pe_resource_table);
750 SWAPPDE (header->datadir.pe_exception_table);
751 SWAPPDE (header->datadir.pe_certificate_table);
752 SWAPPDE (header->datadir.pe_reloc_table);
753 SWAPPDE (header->datadir.pe_debug);
754 SWAPPDE (header->datadir.pe_copyright);
755 SWAPPDE (header->datadir.pe_global_ptr);
756 SWAPPDE (header->datadir.pe_tls_table);
757 SWAPPDE (header->datadir.pe_load_config_table);
758 SWAPPDE (header->datadir.pe_bound_import);
759 SWAPPDE (header->datadir.pe_iat);
760 SWAPPDE (header->datadir.pe_delay_import_desc);
761 SWAPPDE (header->datadir.pe_cli_header);
762 SWAPPDE (header->datadir.pe_reserved);
764 #ifdef PLATFORM_WIN32
765 if (image->is_module_handle)
766 image->raw_data_len = header->nt.pe_image_size;
773 mono_image_load_pe_data (MonoImage *image)
775 MonoCLIImageInfo *iinfo;
776 MonoDotNetHeader *header;
777 MonoMSDOSHeader msdos;
780 iinfo = image->image_info;
781 header = &iinfo->cli_header;
783 #ifdef PLATFORM_WIN32
784 if (!image->is_module_handle)
786 if (offset + sizeof (msdos) > image->raw_data_len)
788 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
790 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
793 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
795 offset = msdos.pe_offset;
797 offset = do_load_header (image, header, offset);
802 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
804 if (header->coff.coff_machine != 0x14c)
810 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
811 * which produces binaries with 7.0. From Sergey:
813 * The reason is that MSVC7 uses traditional compile/link
814 * sequence for CIL executables, and VS.NET (and Framework
815 * SDK) includes linker version 7, that puts 7.0 in this
816 * field. That's why it's currently not possible to load VC
817 * binaries with Mono. This field is pretty much meaningless
818 * anyway (what linker?).
820 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
825 * FIXME: byte swap all addresses here for header.
828 if (!load_section_tables (image, iinfo, offset))
838 mono_image_load_cli_data (MonoImage *image)
840 MonoCLIImageInfo *iinfo;
841 MonoDotNetHeader *header;
843 iinfo = image->image_info;
844 header = &iinfo->cli_header;
846 /* Load the CLI header */
847 if (!load_cli_header (image, iinfo))
850 if (!load_metadata (image, iinfo))
857 mono_image_load_names (MonoImage *image)
859 /* modules don't have an assembly table row */
860 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
861 image->assembly_name = mono_metadata_string_heap (image,
862 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
863 0, MONO_ASSEMBLY_NAME));
866 image->module_name = mono_metadata_string_heap (image,
867 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
868 0, MONO_MODULE_NAME));
872 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
873 gboolean care_about_cli, gboolean care_about_pecoff)
875 MonoCLIImageInfo *iinfo;
876 MonoDotNetHeader *header;
878 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
880 mono_image_init (image);
882 iinfo = image->image_info;
883 header = &iinfo->cli_header;
886 *status = MONO_IMAGE_IMAGE_INVALID;
888 if (care_about_pecoff == FALSE)
891 if (!mono_verifier_verify_pe_data (image, NULL))
894 if (!mono_image_load_pe_data (image))
897 if (care_about_cli == FALSE) {
901 if (!mono_verifier_verify_cli_data (image, NULL))
904 if (!mono_image_load_cli_data (image))
907 if (!mono_verifier_verify_table_data (image, NULL))
910 mono_image_load_names (image);
912 load_modules (image);
915 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
917 *status = MONO_IMAGE_OK;
922 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
923 mono_image_close (image);
928 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
929 gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
931 MonoCLIImageInfo *iinfo;
935 if ((filed = mono_file_map_open (fname)) == NULL){
936 if (IS_PORTABILITY_SET) {
937 gchar *ffname = mono_portability_find_file (fname, TRUE);
939 filed = mono_file_map_open (ffname);
946 *status = MONO_IMAGE_ERROR_ERRNO;
951 image = g_new0 (MonoImage, 1);
952 image->raw_buffer_used = TRUE;
953 image->raw_data_len = mono_file_map_size (filed);
954 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);
955 if (!image->raw_data) {
956 mono_file_map_close (filed);
959 *status = MONO_IMAGE_IMAGE_INVALID;
962 iinfo = g_new0 (MonoCLIImageInfo, 1);
963 image->image_info = iinfo;
964 image->name = mono_path_resolve_symlinks (fname);
965 image->ref_only = refonly;
966 image->ref_count = 1;
967 /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
968 image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
970 mono_file_map_close (filed);
971 return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
975 mono_image_loaded_full (const char *name, gboolean refonly)
978 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
981 res = g_hash_table_lookup (loaded_images, name);
982 mono_images_unlock ();
988 * @name: name of the image to load
990 * This routine ensures that the given image is loaded.
992 * Returns: the loaded MonoImage, or NULL on failure.
995 mono_image_loaded (const char *name)
997 return mono_image_loaded_full (name, FALSE);
1006 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1008 GuidData *data = user_data;
1014 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1019 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1022 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1026 mono_images_lock ();
1027 g_hash_table_foreach (loaded_images, find_by_guid, &data);
1028 mono_images_unlock ();
1033 mono_image_loaded_by_guid (const char *guid)
1035 return mono_image_loaded_by_guid_full (guid, FALSE);
1039 register_image (MonoImage *image)
1042 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1044 mono_images_lock ();
1045 image2 = g_hash_table_lookup (loaded_images, image->name);
1048 /* Somebody else beat us to it */
1049 mono_image_addref (image2);
1050 mono_images_unlock ();
1051 mono_image_close (image);
1054 g_hash_table_insert (loaded_images, image->name, image);
1055 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1056 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1057 mono_images_unlock ();
1063 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1065 MonoCLIImageInfo *iinfo;
1069 if (!data || !data_len) {
1071 *status = MONO_IMAGE_IMAGE_INVALID;
1076 datac = g_try_malloc (data_len);
1079 *status = MONO_IMAGE_ERROR_ERRNO;
1082 memcpy (datac, data, data_len);
1085 image = g_new0 (MonoImage, 1);
1086 image->raw_data = datac;
1087 image->raw_data_len = data_len;
1088 image->raw_data_allocated = need_copy;
1089 image->name = g_strdup_printf ("data-%p", datac);
1090 iinfo = g_new0 (MonoCLIImageInfo, 1);
1091 image->image_info = iinfo;
1092 image->ref_only = refonly;
1094 image = do_mono_image_load (image, status, TRUE, TRUE);
1098 return register_image (image);
1102 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1104 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1107 #ifdef PLATFORM_WIN32
1108 /* fname is not duplicated. */
1110 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1113 MonoCLIImageInfo* iinfo;
1115 image = g_new0 (MonoImage, 1);
1116 image->raw_data = (char*) module_handle;
1117 image->is_module_handle = TRUE;
1118 iinfo = g_new0 (MonoCLIImageInfo, 1);
1119 image->image_info = iinfo;
1120 image->name = fname;
1121 image->ref_count = has_entry_point ? 0 : 1;
1122 image->has_entry_point = has_entry_point;
1124 image = do_mono_image_load (image, status, TRUE, TRUE);
1128 return register_image (image);
1133 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1136 GHashTable *loaded_images;
1139 g_return_val_if_fail (fname != NULL, NULL);
1141 #ifdef PLATFORM_WIN32
1142 /* Load modules using LoadLibrary. */
1143 if (!refonly && coree_module_handle) {
1144 HMODULE module_handle;
1145 guint16 *fname_utf16;
1148 absfname = mono_path_resolve_symlinks (fname);
1151 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1152 mono_images_lock ();
1153 image = g_hash_table_lookup (loaded_images_hash, absfname);
1155 g_assert (image->is_module_handle);
1156 if (image->has_entry_point && image->ref_count == 0) {
1157 /* Increment reference count on images loaded outside of the runtime. */
1158 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1159 /* The image is already loaded because _CorDllMain removes images from the hash. */
1160 module_handle = LoadLibrary (fname_utf16);
1161 g_assert (module_handle == (HMODULE) image->raw_data);
1163 mono_image_addref (image);
1164 mono_images_unlock ();
1166 g_free (fname_utf16);
1171 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1172 module_handle = MonoLoadImage (fname_utf16);
1173 if (status && module_handle == NULL)
1174 last_error = GetLastError ();
1176 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1177 image = g_hash_table_lookup (loaded_images_hash, absfname);
1179 mono_image_addref (image);
1180 mono_images_unlock ();
1182 g_free (fname_utf16);
1184 if (module_handle == NULL) {
1188 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1189 *status = MONO_IMAGE_IMAGE_INVALID;
1191 *status = MONO_IMAGE_ERROR_ERRNO;
1197 g_assert (image->is_module_handle);
1198 g_assert (image->has_entry_point);
1203 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1207 absfname = mono_path_canonicalize (fname);
1210 * The easiest solution would be to do all the loading inside the mutex,
1211 * but that would lead to scalability problems. So we let the loading
1212 * happen outside the mutex, and if multiple threads happen to load
1213 * the same image, we discard all but the first copy.
1215 mono_images_lock ();
1216 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1217 image = g_hash_table_lookup (loaded_images, absfname);
1221 mono_image_addref (image);
1222 mono_images_unlock ();
1225 mono_images_unlock ();
1227 image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1231 return register_image (image);
1236 * @fname: filename that points to the module we want to open
1237 * @status: An error condition is returned in this field
1239 * Returns: An open image of type %MonoImage or NULL on error.
1240 * The caller holds a temporary reference to the returned image which should be cleared
1241 * when no longer needed by calling mono_image_close ().
1242 * if NULL, then check the value of @status for details on the error
1245 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1247 return mono_image_open_full (fname, status, FALSE);
1251 * mono_pe_file_open:
1252 * @fname: filename that points to the module we want to open
1253 * @status: An error condition is returned in this field
1255 * Returns: An open image of type %MonoImage or NULL on error. if
1256 * NULL, then check the value of @status for details on the error.
1257 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1258 * It's just a PE file loader, used for FileVersionInfo. It also does
1259 * not use the image cache.
1262 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1264 g_return_val_if_fail (fname != NULL, NULL);
1266 return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1270 * mono_image_open_raw
1271 * @fname: filename that points to the module we want to open
1272 * @status: An error condition is returned in this field
1274 * Returns an image without loading neither pe or cli data.
1276 * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
1279 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1281 g_return_val_if_fail (fname != NULL, NULL);
1283 return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1287 mono_image_fixup_vtable (MonoImage *image)
1289 #ifdef PLATFORM_WIN32
1290 MonoCLIImageInfo *iinfo;
1292 MonoVTableFixup *vtfixup;
1298 g_assert (image->is_module_handle);
1300 iinfo = image->image_info;
1301 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1302 if (!de->rva || !de->size)
1304 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1308 count = de->size / sizeof (MonoVTableFixup);
1310 if (!vtfixup->rva || !vtfixup->count)
1313 slot = mono_image_rva_map (image, vtfixup->rva);
1315 slot_type = vtfixup->type;
1316 slot_count = vtfixup->count;
1317 if (slot_type & VTFIXUP_TYPE_32BIT)
1318 while (slot_count--) {
1319 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1320 slot = ((guint32*) slot) + 1;
1322 else if (slot_type & VTFIXUP_TYPE_64BIT)
1323 while (slot_count--) {
1324 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1325 slot = ((guint32*) slot) + 1;
1328 g_assert_not_reached();
1333 g_assert_not_reached();
1338 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1340 g_hash_table_destroy ((GHashTable*)val);
1345 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1347 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1352 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1358 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1360 g_slist_free ((GSList*)val);
1364 * mono_image_addref:
1365 * @image: The image file we wish to add a reference to
1367 * Increases the reference count of an image.
1370 mono_image_addref (MonoImage *image)
1372 InterlockedIncrement (&image->ref_count);
1376 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1378 stream->alloc_size = stream->index = stream->offset = 0;
1379 g_free (stream->data);
1380 stream->data = NULL;
1382 g_hash_table_destroy (stream->hash);
1383 stream->hash = NULL;
1388 free_hash (GHashTable *hash)
1391 g_hash_table_destroy (hash);
1396 * @image: The image file we wish to close
1398 * Closes an image file, deallocates all memory consumed and
1399 * unmaps all possible sections of the file
1402 mono_image_close (MonoImage *image)
1405 GHashTable *loaded_images;
1408 g_return_if_fail (image != NULL);
1410 if (InterlockedDecrement (&image->ref_count) > 0)
1413 #ifdef PLATFORM_WIN32
1414 if (image->is_module_handle && image->has_entry_point) {
1415 mono_images_lock ();
1416 if (image->ref_count == 0) {
1417 /* Image will be closed by _CorDllMain. */
1418 FreeLibrary ((HMODULE) image->raw_data);
1419 mono_images_unlock ();
1422 mono_images_unlock ();
1426 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1428 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1430 mono_metadata_clean_for_image (image);
1433 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1434 * assemblies, so we can't release these references in mono_assembly_close () since the
1435 * MonoImage might outlive its associated MonoAssembly.
1437 if (image->references && !image->dynamic) {
1438 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1441 for (i = 0; i < t->rows; i++) {
1442 if (image->references [i])
1443 mono_assembly_close (image->references [i]);
1446 g_free (image->references);
1447 image->references = NULL;
1450 mono_images_lock ();
1451 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1452 image2 = g_hash_table_lookup (loaded_images, image->name);
1453 if (image == image2) {
1454 /* This is not true if we are called from mono_image_open () */
1455 g_hash_table_remove (loaded_images, image->name);
1457 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1458 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1460 #ifdef PLATFORM_WIN32
1461 if (image->is_module_handle && !image->has_entry_point)
1462 FreeLibrary ((HMODULE) image->raw_data);
1465 mono_images_unlock ();
1467 if (image->raw_buffer_used) {
1468 if (image->raw_data != NULL)
1469 mono_file_unmap (image->raw_data, image->raw_data_handle);
1472 if (image->raw_data_allocated) {
1473 /* FIXME: do we need this? (image is disposed anyway) */
1474 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1475 MonoCLIImageInfo *ii = image->image_info;
1477 if ((image->raw_metadata > image->raw_data) &&
1478 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1479 image->raw_metadata = NULL;
1481 for (i = 0; i < ii->cli_section_count; i++)
1482 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1483 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1484 ii->cli_sections [i] = NULL;
1486 g_free (image->raw_data);
1489 if (debug_assembly_unload) {
1490 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1492 g_free (image->name);
1493 g_free (image->guid);
1494 g_free (image->version);
1495 g_free (image->files);
1498 if (image->method_cache)
1499 mono_value_hash_table_destroy (image->method_cache);
1500 if (image->methodref_cache)
1501 g_hash_table_destroy (image->methodref_cache);
1502 mono_internal_hash_table_destroy (&image->class_cache);
1503 g_hash_table_destroy (image->field_cache);
1504 if (image->array_cache) {
1505 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1506 g_hash_table_destroy (image->array_cache);
1508 if (image->szarray_cache)
1509 g_hash_table_destroy (image->szarray_cache);
1510 if (image->ptr_cache)
1511 g_hash_table_destroy (image->ptr_cache);
1512 if (image->name_cache) {
1513 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1514 g_hash_table_destroy (image->name_cache);
1517 free_hash (image->native_wrapper_cache);
1518 free_hash (image->managed_wrapper_cache);
1519 free_hash (image->delegate_begin_invoke_cache);
1520 free_hash (image->delegate_end_invoke_cache);
1521 free_hash (image->delegate_invoke_cache);
1522 free_hash (image->delegate_abstract_invoke_cache);
1523 if (image->remoting_invoke_cache)
1524 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1525 free_hash (image->remoting_invoke_cache);
1526 free_hash (image->runtime_invoke_cache);
1527 free_hash (image->runtime_invoke_direct_cache);
1528 free_hash (image->runtime_invoke_vcall_cache);
1529 free_hash (image->synchronized_cache);
1530 free_hash (image->unbox_wrapper_cache);
1531 free_hash (image->cominterop_invoke_cache);
1532 free_hash (image->cominterop_wrapper_cache);
1533 free_hash (image->typespec_cache);
1534 free_hash (image->ldfld_wrapper_cache);
1535 free_hash (image->ldflda_wrapper_cache);
1536 free_hash (image->stfld_wrapper_cache);
1537 free_hash (image->isinst_cache);
1538 free_hash (image->castclass_cache);
1539 free_hash (image->proxy_isinst_cache);
1540 free_hash (image->thunk_invoke_cache);
1542 /* The ownership of signatures is not well defined */
1543 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1544 g_hash_table_destroy (image->memberref_signatures);
1545 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1546 g_hash_table_destroy (image->helper_signatures);
1547 g_hash_table_destroy (image->method_signatures);
1549 if (image->generic_class_cache)
1550 g_hash_table_destroy (image->generic_class_cache);
1552 if (image->rgctx_template_hash)
1553 g_hash_table_destroy (image->rgctx_template_hash);
1555 if (image->property_hash)
1556 mono_property_hash_destroy (image->property_hash);
1558 if (image->interface_bitset) {
1559 mono_unload_interface_ids (image->interface_bitset);
1560 mono_bitset_free (image->interface_bitset);
1562 if (image->image_info){
1563 MonoCLIImageInfo *ii = image->image_info;
1565 if (ii->cli_section_tables)
1566 g_free (ii->cli_section_tables);
1567 if (ii->cli_sections)
1568 g_free (ii->cli_sections);
1569 g_free (image->image_info);
1572 for (i = 0; i < image->module_count; ++i) {
1573 if (image->modules [i])
1574 mono_image_close (image->modules [i]);
1577 g_free (image->modules);
1578 if (image->modules_loaded)
1579 g_free (image->modules_loaded);
1580 if (image->references)
1581 g_free (image->references);
1582 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1584 DeleteCriticalSection (&image->szarray_cache_lock);
1585 DeleteCriticalSection (&image->lock);
1587 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1588 if (!image->dynamic) {
1589 if (debug_assembly_unload)
1590 mono_mempool_invalidate (image->mempool);
1592 mono_mempool_destroy (image->mempool);
1596 /* Dynamic images are GC_MALLOCed */
1597 g_free ((char*)image->module_name);
1598 mono_dynamic_image_free ((MonoDynamicImage*)image);
1599 if (debug_assembly_unload)
1600 mono_mempool_invalidate (image->mempool);
1602 mono_mempool_destroy (image->mempool);
1605 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1609 * mono_image_strerror:
1610 * @status: an code indicating the result from a recent operation
1612 * Returns: a string describing the error
1615 mono_image_strerror (MonoImageOpenStatus status)
1620 case MONO_IMAGE_ERROR_ERRNO:
1621 return strerror (errno);
1622 case MONO_IMAGE_IMAGE_INVALID:
1623 return "File does not contain a valid CIL image";
1624 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1625 return "An assembly was referenced, but could not be found";
1627 return "Internal error";
1631 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1632 guint32 lang_id, gunichar2 *name,
1633 MonoPEResourceDirEntry *entry,
1634 MonoPEResourceDir *root, guint32 level)
1636 gboolean is_string, is_dir;
1637 guint32 name_offset, dir_offset;
1639 /* Level 0 holds a directory entry for each type of resource
1640 * (identified by ID or name).
1642 * Level 1 holds a directory entry for each named resource
1643 * item, and each "anonymous" item of a particular type of
1646 * Level 2 holds a directory entry for each language pointing to
1649 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1650 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1652 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1653 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1658 } else if (level==1) {
1659 if (res_id != name_offset)
1663 is_string==TRUE && name!=lookup (name_offset)) {
1667 } else if (level==2) {
1668 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1671 g_assert_not_reached ();
1675 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1676 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1679 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1681 for(i=0; i<entries; i++) {
1682 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1685 ret=mono_image_walk_resource_tree (info, res_id,
1696 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1697 MonoPEResourceDataEntry *res;
1699 res = g_new0 (MonoPEResourceDataEntry, 1);
1701 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1702 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1703 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1704 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1711 * mono_image_lookup_resource:
1712 * @image: the image to look up the resource in
1713 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1714 * @lang_id: The language id.
1715 * @name: the resource name to lookup.
1717 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1718 * of the given resource. The caller should free it using g_free () when no longer
1722 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1724 MonoCLIImageInfo *info;
1725 MonoDotNetHeader *header;
1726 MonoPEDatadir *datadir;
1727 MonoPEDirEntry *rsrc;
1728 MonoPEResourceDir *resource_dir;
1729 MonoPEResourceDirEntry *res_entries;
1736 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1738 info=image->image_info;
1743 header=&info->cli_header;
1748 datadir=&header->datadir;
1753 rsrc=&datadir->pe_resource_table;
1758 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1759 if(resource_dir==NULL) {
1763 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1764 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1766 for(i=0; i<entries; i++) {
1767 MonoPEResourceDirEntry *entry=&res_entries[i];
1770 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1771 name, entry, resource_dir,
1782 * mono_image_get_entry_point:
1783 * @image: the image where the entry point will be looked up.
1785 * Use this routine to determine the metadata token for method that
1786 * has been flagged as the entry point.
1788 * Returns: the token for the entry point method in the image
1791 mono_image_get_entry_point (MonoImage *image)
1793 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1797 * mono_image_get_resource:
1798 * @image: the image where the resource will be looked up.
1799 * @offset: The offset to add to the resource
1800 * @size: a pointer to an int where the size of the resource will be stored
1802 * This is a low-level routine that fetches a resource from the
1803 * metadata that starts at a given @offset. The @size parameter is
1804 * filled with the data field as encoded in the metadata.
1806 * Returns: the pointer to the resource whose offset is @offset.
1809 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1811 MonoCLIImageInfo *iinfo = image->image_info;
1812 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1815 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1818 data = mono_image_rva_map (image, ch->ch_resources.rva);
1823 *size = read32 (data);
1829 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1831 char *base_dir, *name;
1833 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1837 if (fileidx < 1 || fileidx > t->rows)
1840 mono_loader_lock ();
1841 if (image->files && image->files [fileidx - 1]) {
1842 mono_loader_unlock ();
1843 return image->files [fileidx - 1];
1847 image->files = g_new0 (MonoImage*, t->rows);
1849 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1850 fname = mono_metadata_string_heap (image, fname_id);
1851 base_dir = g_path_get_dirname (image->name);
1852 name = g_build_filename (base_dir, fname, NULL);
1853 res = mono_image_open (name, NULL);
1856 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1857 res->assembly = image->assembly;
1858 for (i = 0; i < res->module_count; ++i) {
1859 if (res->modules [i] && !res->modules [i]->assembly)
1860 res->modules [i]->assembly = image->assembly;
1863 image->files [fileidx - 1] = res;
1864 #ifdef PLATFORM_WIN32
1865 if (res->is_module_handle)
1866 mono_image_fixup_vtable (res);
1869 mono_loader_unlock ();
1876 * mono_image_get_strong_name:
1877 * @image: a MonoImage
1878 * @size: a guint32 pointer, or NULL.
1880 * If the image has a strong name, and @size is not NULL, the value
1881 * pointed to by size will have the size of the strong name.
1883 * Returns: NULL if the image does not have a strong name, or a
1884 * pointer to the public key.
1887 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1889 MonoCLIImageInfo *iinfo = image->image_info;
1890 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1893 if (!de->size || !de->rva)
1895 data = mono_image_rva_map (image, de->rva);
1904 * mono_image_strong_name_position:
1905 * @image: a MonoImage
1906 * @size: a guint32 pointer, or NULL.
1908 * If the image has a strong name, and @size is not NULL, the value
1909 * pointed to by size will have the size of the strong name.
1911 * Returns: the position within the image file where the strong name
1915 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1917 MonoCLIImageInfo *iinfo = image->image_info;
1918 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1923 if (!de->size || !de->rva)
1925 pos = mono_cli_rva_image_map (image, de->rva);
1926 return pos == INVALID_ADDRESS ? 0 : pos;
1930 * mono_image_get_public_key:
1931 * @image: a MonoImage
1932 * @size: a guint32 pointer, or NULL.
1934 * This is used to obtain the public key in the @image.
1936 * If the image has a public key, and @size is not NULL, the value
1937 * pointed to by size will have the size of the public key.
1939 * Returns: NULL if the image does not have a public key, or a pointer
1940 * to the public key.
1943 mono_image_get_public_key (MonoImage *image, guint32 *size)
1948 if (image->dynamic) {
1950 *size = ((MonoDynamicImage*)image)->public_key_len;
1951 return (char*)((MonoDynamicImage*)image)->public_key;
1953 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1955 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1958 pubkey = mono_metadata_blob_heap (image, tok);
1959 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1966 * mono_image_get_name:
1967 * @name: a MonoImage
1969 * Returns: the name of the assembly.
1972 mono_image_get_name (MonoImage *image)
1974 return image->assembly_name;
1978 * mono_image_get_filename:
1979 * @image: a MonoImage
1981 * Used to get the filename that hold the actual MonoImage
1983 * Returns: the filename.
1986 mono_image_get_filename (MonoImage *image)
1992 mono_image_get_guid (MonoImage *image)
1997 const MonoTableInfo*
1998 mono_image_get_table_info (MonoImage *image, int table_id)
2000 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2002 return &image->tables [table_id];
2006 mono_image_get_table_rows (MonoImage *image, int table_id)
2008 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2010 return image->tables [table_id].rows;
2014 mono_table_info_get_rows (const MonoTableInfo *table)
2020 * mono_image_get_assembly:
2021 * @image: the MonoImage.
2023 * Use this routine to get the assembly that owns this image.
2025 * Returns: the assembly that holds this image.
2028 mono_image_get_assembly (MonoImage *image)
2030 return image->assembly;
2034 * mono_image_is_dynamic:
2035 * @image: the MonoImage
2037 * Determines if the given image was created dynamically through the
2038 * System.Reflection.Emit API
2040 * Returns: TRUE if the image was created dynamically, FALSE if not.
2043 mono_image_is_dynamic (MonoImage *image)
2045 return image->dynamic;
2049 * mono_image_has_authenticode_entry:
2050 * @image: the MonoImage
2052 * Use this routine to determine if the image has a Authenticode
2053 * Certificate Table.
2055 * Returns: TRUE if the image contains an authenticode entry in the PE
2059 mono_image_has_authenticode_entry (MonoImage *image)
2061 MonoCLIImageInfo *iinfo = image->image_info;
2062 MonoDotNetHeader *header = &iinfo->cli_header;
2063 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2064 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2065 return ((de->rva != 0) && (de->size > 8));
2069 mono_image_alloc (MonoImage *image, guint size)
2073 mono_perfcounters->loader_bytes += size;
2074 mono_image_lock (image);
2075 res = mono_mempool_alloc (image->mempool, size);
2076 mono_image_unlock (image);
2082 mono_image_alloc0 (MonoImage *image, guint size)
2086 mono_perfcounters->loader_bytes += size;
2087 mono_image_lock (image);
2088 res = mono_mempool_alloc0 (image->mempool, size);
2089 mono_image_unlock (image);
2095 mono_image_strdup (MonoImage *image, const char *s)
2099 mono_perfcounters->loader_bytes += strlen (s);
2100 mono_image_lock (image);
2101 res = mono_mempool_strdup (image->mempool, s);
2102 mono_image_unlock (image);
2108 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2112 new_list = mono_image_alloc (image, sizeof (GList));
2113 new_list->data = data;
2114 new_list->prev = list ? list->prev : NULL;
2115 new_list->next = list;
2118 new_list->prev->next = new_list;
2120 list->prev = new_list;
2126 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2130 new_list = mono_image_alloc (image, sizeof (GSList));
2131 new_list->data = data;
2132 new_list->next = NULL;
2134 return g_slist_concat (list, new_list);
2138 mono_image_lock (MonoImage *image)
2140 mono_locks_acquire (&image->lock, ImageDataLock);
2144 mono_image_unlock (MonoImage *image)
2146 mono_locks_release (&image->lock, ImageDataLock);
2151 * mono_image_property_lookup:
2153 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2155 * LOCKING: Takes the image lock
2158 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2162 mono_image_lock (image);
2163 res = mono_property_hash_lookup (image->property_hash, subject, property);
2164 mono_image_unlock (image);
2170 * mono_image_property_insert:
2172 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2174 * LOCKING: Takes the image lock
2177 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2179 mono_image_lock (image);
2180 mono_property_hash_insert (image->property_hash, subject, property, value);
2181 mono_image_unlock (image);
2185 * mono_image_property_remove:
2187 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2189 * LOCKING: Takes the image lock
2192 mono_image_property_remove (MonoImage *image, gpointer subject)
2194 mono_image_lock (image);
2195 mono_property_hash_remove_object (image->property_hash, subject);
2196 mono_image_unlock (image);