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 /* 24.2.1: Metadata root starts here */
332 ptr = image->raw_metadata;
334 if (strncmp (ptr, "BSJB", 4) == 0){
335 guint32 version_string_len;
338 image->md_version_major = read16 (ptr);
340 image->md_version_minor = read16 (ptr);
343 version_string_len = read32 (ptr);
345 image->version = g_strndup (ptr, version_string_len);
346 ptr += version_string_len;
347 pad = ptr - image->raw_metadata;
349 ptr += 4 - (pad % 4);
353 /* skip over flags */
356 streams = read16 (ptr);
359 for (i = 0; i < streams; i++){
360 if (strncmp (ptr + 8, "#~", 3) == 0){
361 image->heap_tables.data = image->raw_metadata + read32 (ptr);
362 image->heap_tables.size = read32 (ptr + 4);
364 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
365 image->heap_strings.data = image->raw_metadata + read32 (ptr);
366 image->heap_strings.size = read32 (ptr + 4);
368 } else if (strncmp (ptr + 8, "#US", 4) == 0){
369 image->heap_us.data = image->raw_metadata + read32 (ptr);
370 image->heap_us.size = read32 (ptr + 4);
372 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
373 image->heap_blob.data = image->raw_metadata + read32 (ptr);
374 image->heap_blob.size = read32 (ptr + 4);
376 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
377 image->heap_guid.data = image->raw_metadata + read32 (ptr);
378 image->heap_guid.size = read32 (ptr + 4);
380 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
381 image->heap_tables.data = image->raw_metadata + read32 (ptr);
382 image->heap_tables.size = read32 (ptr + 4);
384 image->uncompressed_metadata = TRUE;
385 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);
387 g_message ("Unknown heap type: %s\n", ptr + 8);
388 ptr += 8 + strlen (ptr + 8) + 1;
390 pad = ptr - image->raw_metadata;
392 ptr += 4 - (pad % 4);
395 g_assert (image->heap_guid.data);
396 g_assert (image->heap_guid.size >= 16);
398 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
404 * Load representation of logical metadata tables, from the "#~" stream
407 load_tables (MonoImage *image)
409 const char *heap_tables = image->heap_tables.data;
411 guint64 valid_mask, sorted_mask;
412 int valid = 0, table;
415 heap_sizes = heap_tables [6];
416 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
417 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
418 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
420 valid_mask = read64 (heap_tables + 8);
421 sorted_mask = read64 (heap_tables + 16);
422 rows = (const guint32 *) (heap_tables + 24);
424 for (table = 0; table < 64; table++){
425 if ((valid_mask & ((guint64) 1 << table)) == 0){
426 if (table > MONO_TABLE_LAST)
428 image->tables [table].rows = 0;
431 if (table > MONO_TABLE_LAST) {
432 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
434 image->tables [table].rows = read32 (rows);
436 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
437 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
443 image->tables_base = (heap_tables + 24) + (4 * valid);
445 /* They must be the same */
446 g_assert ((const void *) image->tables_base == (const void *) rows);
448 mono_metadata_compute_table_bases (image);
453 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
455 if (!load_metadata_ptrs (image, iinfo))
458 return load_tables (image);
462 mono_image_check_for_module_cctor (MonoImage *image)
464 MonoTableInfo *t, *mt;
465 t = &image->tables [MONO_TABLE_TYPEDEF];
466 mt = &image->tables [MONO_TABLE_METHOD];
467 if (mono_framework_version () == 1) {
468 image->checked_module_cctor = TRUE;
471 if (image->dynamic) {
473 image->checked_module_cctor = TRUE;
477 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
478 const char *name = mono_metadata_string_heap (image, nameidx);
479 if (strcmp (name, "<Module>") == 0) {
480 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
483 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
485 last_method = mt->rows;
486 for (; first_method < last_method; first_method++) {
487 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
488 name = mono_metadata_string_heap (image, nameidx);
489 if (strcmp (name, ".cctor") == 0) {
490 image->has_module_cctor = TRUE;
491 image->checked_module_cctor = TRUE;
497 image->has_module_cctor = FALSE;
498 image->checked_module_cctor = TRUE;
502 load_modules (MonoImage *image)
509 t = &image->tables [MONO_TABLE_MODULEREF];
510 image->modules = g_new0 (MonoImage *, t->rows);
511 image->modules_loaded = g_new0 (gboolean, t->rows);
512 image->module_count = t->rows;
516 * mono_image_load_module:
518 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
519 * it cannot be loaded.
522 mono_image_load_module (MonoImage *image, int idx)
525 MonoTableInfo *file_table;
528 gboolean refonly = image->ref_only;
529 GList *list_iter, *valid_modules = NULL;
530 MonoImageOpenStatus status;
532 g_assert (idx <= image->module_count);
533 if (image->modules_loaded [idx - 1])
534 return image->modules [idx - 1];
536 file_table = &image->tables [MONO_TABLE_FILE];
537 for (i = 0; i < file_table->rows; i++) {
538 guint32 cols [MONO_FILE_SIZE];
539 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
540 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
542 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
545 t = &image->tables [MONO_TABLE_MODULEREF];
546 base_dir = g_path_get_dirname (image->name);
551 guint32 cols [MONO_MODULEREF_SIZE];
552 /* if there is no file table, we try to load the module... */
553 int valid = file_table->rows == 0;
555 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
556 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
557 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
558 /* be safe with string dups, but we could just compare string indexes */
559 if (strcmp (list_iter->data, name) == 0) {
565 module_ref = g_build_filename (base_dir, name, NULL);
566 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
567 if (image->modules [idx - 1]) {
568 mono_image_addref (image->modules [idx - 1]);
569 image->modules [idx - 1]->assembly = image->assembly;
570 #ifdef PLATFORM_WIN32
571 if (image->modules [idx - 1]->is_module_handle)
572 mono_image_fixup_vtable (image->modules [idx - 1]);
574 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
580 image->modules_loaded [idx - 1] = TRUE;
583 g_list_free (valid_modules);
585 return image->modules [idx - 1];
589 class_key_extract (gpointer value)
591 MonoClass *class = value;
593 return GUINT_TO_POINTER (class->type_token);
597 class_next_value (gpointer value)
599 MonoClass *class = value;
601 return (gpointer*)&class->next_class_cache;
605 mono_image_init (MonoImage *image)
607 image->mempool = mono_mempool_new_size (512);
608 mono_internal_hash_table_init (&image->class_cache,
612 image->field_cache = g_hash_table_new (NULL, NULL);
614 image->typespec_cache = g_hash_table_new (NULL, NULL);
615 image->memberref_signatures = g_hash_table_new (NULL, NULL);
616 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
617 image->method_signatures = g_hash_table_new (NULL, NULL);
619 image->property_hash = mono_property_hash_new ();
620 InitializeCriticalSection (&image->lock);
621 InitializeCriticalSection (&image->szarray_cache_lock);
624 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
625 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
626 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
627 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
628 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
637 * Returns < 0 to indicate an error.
640 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
642 MonoDotNetHeader64 header64;
644 #ifdef PLATFORM_WIN32
645 if (!image->is_module_handle)
647 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
650 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
652 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
655 /* endian swap the fields common between PE and PE+ */
656 SWAP32 (header->coff.coff_time);
657 SWAP32 (header->coff.coff_symptr);
658 SWAP32 (header->coff.coff_symcount);
659 SWAP16 (header->coff.coff_machine);
660 SWAP16 (header->coff.coff_sections);
661 SWAP16 (header->coff.coff_opt_header_size);
662 SWAP16 (header->coff.coff_attributes);
664 SWAP32 (header->pe.pe_code_size);
665 SWAP32 (header->pe.pe_uninit_data_size);
666 SWAP32 (header->pe.pe_rva_entry_point);
667 SWAP32 (header->pe.pe_rva_code_base);
668 SWAP32 (header->pe.pe_rva_data_base);
669 SWAP16 (header->pe.pe_magic);
671 /* now we are ready for the basic tests */
673 if (header->pe.pe_magic == 0x10B) {
674 offset += sizeof (MonoDotNetHeader);
675 SWAP32 (header->pe.pe_data_size);
676 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
679 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
680 SWAP32 (header->nt.pe_stack_reserve);
681 SWAP32 (header->nt.pe_stack_commit);
682 SWAP32 (header->nt.pe_heap_reserve);
683 SWAP32 (header->nt.pe_heap_commit);
684 } else if (header->pe.pe_magic == 0x20B) {
685 /* PE32+ file format */
686 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
688 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
689 offset += sizeof (MonoDotNetHeader64);
690 /* copy the fields already swapped. the last field, pe_data_size, is missing */
691 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
692 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
693 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
695 SWAP64 (header64.nt.pe_image_base);
696 header->nt.pe_image_base = header64.nt.pe_image_base;
697 SWAP64 (header64.nt.pe_stack_reserve);
698 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
699 SWAP64 (header64.nt.pe_stack_commit);
700 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
701 SWAP64 (header64.nt.pe_heap_reserve);
702 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
703 SWAP64 (header64.nt.pe_heap_commit);
704 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
706 header->nt.pe_section_align = header64.nt.pe_section_align;
707 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
708 header->nt.pe_os_major = header64.nt.pe_os_major;
709 header->nt.pe_os_minor = header64.nt.pe_os_minor;
710 header->nt.pe_user_major = header64.nt.pe_user_major;
711 header->nt.pe_user_minor = header64.nt.pe_user_minor;
712 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
713 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
714 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
715 header->nt.pe_image_size = header64.nt.pe_image_size;
716 header->nt.pe_header_size = header64.nt.pe_header_size;
717 header->nt.pe_checksum = header64.nt.pe_checksum;
718 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
719 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
720 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
721 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
723 /* copy the datadir */
724 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
729 /* MonoPEHeaderNT: not used yet */
730 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
731 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
732 SWAP16 (header->nt.pe_os_major); /* must be 4 */
733 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
734 SWAP16 (header->nt.pe_user_major);
735 SWAP16 (header->nt.pe_user_minor);
736 SWAP16 (header->nt.pe_subsys_major);
737 SWAP16 (header->nt.pe_subsys_minor);
738 SWAP32 (header->nt.pe_reserved_1);
739 SWAP32 (header->nt.pe_image_size);
740 SWAP32 (header->nt.pe_header_size);
741 SWAP32 (header->nt.pe_checksum);
742 SWAP16 (header->nt.pe_subsys_required);
743 SWAP16 (header->nt.pe_dll_flags);
744 SWAP32 (header->nt.pe_loader_flags);
745 SWAP32 (header->nt.pe_data_dir_count);
747 /* MonoDotNetHeader: mostly unused */
748 SWAPPDE (header->datadir.pe_export_table);
749 SWAPPDE (header->datadir.pe_import_table);
750 SWAPPDE (header->datadir.pe_resource_table);
751 SWAPPDE (header->datadir.pe_exception_table);
752 SWAPPDE (header->datadir.pe_certificate_table);
753 SWAPPDE (header->datadir.pe_reloc_table);
754 SWAPPDE (header->datadir.pe_debug);
755 SWAPPDE (header->datadir.pe_copyright);
756 SWAPPDE (header->datadir.pe_global_ptr);
757 SWAPPDE (header->datadir.pe_tls_table);
758 SWAPPDE (header->datadir.pe_load_config_table);
759 SWAPPDE (header->datadir.pe_bound_import);
760 SWAPPDE (header->datadir.pe_iat);
761 SWAPPDE (header->datadir.pe_delay_import_desc);
762 SWAPPDE (header->datadir.pe_cli_header);
763 SWAPPDE (header->datadir.pe_reserved);
765 #ifdef PLATFORM_WIN32
766 if (image->is_module_handle)
767 image->raw_data_len = header->nt.pe_image_size;
774 mono_image_load_pe_data (MonoImage *image)
776 MonoCLIImageInfo *iinfo;
777 MonoDotNetHeader *header;
778 MonoMSDOSHeader msdos;
781 iinfo = image->image_info;
782 header = &iinfo->cli_header;
784 #ifdef PLATFORM_WIN32
785 if (!image->is_module_handle)
787 if (offset + sizeof (msdos) > image->raw_data_len)
789 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
791 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
794 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
796 offset = msdos.pe_offset;
798 offset = do_load_header (image, header, offset);
803 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
805 if (header->coff.coff_machine != 0x14c)
811 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
812 * which produces binaries with 7.0. From Sergey:
814 * The reason is that MSVC7 uses traditional compile/link
815 * sequence for CIL executables, and VS.NET (and Framework
816 * SDK) includes linker version 7, that puts 7.0 in this
817 * field. That's why it's currently not possible to load VC
818 * binaries with Mono. This field is pretty much meaningless
819 * anyway (what linker?).
821 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
826 * FIXME: byte swap all addresses here for header.
829 if (!load_section_tables (image, iinfo, offset))
839 mono_image_load_cli_data (MonoImage *image)
841 MonoCLIImageInfo *iinfo;
842 MonoDotNetHeader *header;
844 iinfo = image->image_info;
845 header = &iinfo->cli_header;
847 /* Load the CLI header */
848 if (!load_cli_header (image, iinfo))
851 if (!load_metadata (image, iinfo))
858 mono_image_load_names (MonoImage *image)
860 /* modules don't have an assembly table row */
861 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
862 image->assembly_name = mono_metadata_string_heap (image,
863 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
864 0, MONO_ASSEMBLY_NAME));
867 image->module_name = mono_metadata_string_heap (image,
868 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
869 0, MONO_MODULE_NAME));
873 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
874 gboolean care_about_cli, gboolean care_about_pecoff)
876 MonoCLIImageInfo *iinfo;
877 MonoDotNetHeader *header;
879 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
881 mono_image_init (image);
883 iinfo = image->image_info;
884 header = &iinfo->cli_header;
887 *status = MONO_IMAGE_IMAGE_INVALID;
889 if (care_about_pecoff == FALSE)
892 if (!mono_verifier_verify_pe_data (image, NULL))
895 if (!mono_image_load_pe_data (image))
898 if (care_about_cli == FALSE) {
902 if (!mono_verifier_verify_cli_data (image, NULL))
905 if (!mono_image_load_cli_data (image))
908 if (!mono_verifier_verify_table_data (image, NULL))
911 mono_image_load_names (image);
913 load_modules (image);
916 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
918 *status = MONO_IMAGE_OK;
923 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
924 mono_image_close (image);
929 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
930 gboolean care_about_cli, gboolean care_about_pecoff, gboolean refonly)
932 MonoCLIImageInfo *iinfo;
936 if ((filed = mono_file_map_open (fname)) == NULL){
937 if (IS_PORTABILITY_SET) {
938 gchar *ffname = mono_portability_find_file (fname, TRUE);
940 filed = mono_file_map_open (ffname);
947 *status = MONO_IMAGE_ERROR_ERRNO;
952 image = g_new0 (MonoImage, 1);
953 image->raw_buffer_used = TRUE;
954 image->raw_data_len = mono_file_map_size (filed);
955 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);
956 if (!image->raw_data) {
957 mono_file_map_close (filed);
960 *status = MONO_IMAGE_IMAGE_INVALID;
963 iinfo = g_new0 (MonoCLIImageInfo, 1);
964 image->image_info = iinfo;
965 image->name = mono_path_resolve_symlinks (fname);
966 image->ref_only = refonly;
967 image->ref_count = 1;
968 /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
969 image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
971 mono_file_map_close (filed);
972 return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
976 mono_image_loaded_full (const char *name, gboolean refonly)
979 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
982 res = g_hash_table_lookup (loaded_images, name);
983 mono_images_unlock ();
989 * @name: name of the image to load
991 * This routine ensures that the given image is loaded.
993 * Returns: the loaded MonoImage, or NULL on failure.
996 mono_image_loaded (const char *name)
998 return mono_image_loaded_full (name, FALSE);
1007 find_by_guid (gpointer key, gpointer val, gpointer user_data)
1009 GuidData *data = user_data;
1015 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
1020 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
1023 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1027 mono_images_lock ();
1028 g_hash_table_foreach (loaded_images, find_by_guid, &data);
1029 mono_images_unlock ();
1034 mono_image_loaded_by_guid (const char *guid)
1036 return mono_image_loaded_by_guid_full (guid, FALSE);
1040 register_image (MonoImage *image)
1043 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1045 mono_images_lock ();
1046 image2 = g_hash_table_lookup (loaded_images, image->name);
1049 /* Somebody else beat us to it */
1050 mono_image_addref (image2);
1051 mono_images_unlock ();
1052 mono_image_close (image);
1055 g_hash_table_insert (loaded_images, image->name, image);
1056 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1057 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1058 mono_images_unlock ();
1064 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1066 MonoCLIImageInfo *iinfo;
1070 if (!data || !data_len) {
1072 *status = MONO_IMAGE_IMAGE_INVALID;
1077 datac = g_try_malloc (data_len);
1080 *status = MONO_IMAGE_ERROR_ERRNO;
1083 memcpy (datac, data, data_len);
1086 image = g_new0 (MonoImage, 1);
1087 image->raw_data = datac;
1088 image->raw_data_len = data_len;
1089 image->raw_data_allocated = need_copy;
1090 image->name = g_strdup_printf ("data-%p", datac);
1091 iinfo = g_new0 (MonoCLIImageInfo, 1);
1092 image->image_info = iinfo;
1093 image->ref_only = refonly;
1095 image = do_mono_image_load (image, status, TRUE, TRUE);
1099 return register_image (image);
1103 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1105 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1108 #ifdef PLATFORM_WIN32
1109 /* fname is not duplicated. */
1111 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1114 MonoCLIImageInfo* iinfo;
1116 image = g_new0 (MonoImage, 1);
1117 image->raw_data = (char*) module_handle;
1118 image->is_module_handle = TRUE;
1119 iinfo = g_new0 (MonoCLIImageInfo, 1);
1120 image->image_info = iinfo;
1121 image->name = fname;
1122 image->ref_count = has_entry_point ? 0 : 1;
1123 image->has_entry_point = has_entry_point;
1125 image = do_mono_image_load (image, status, TRUE, TRUE);
1129 return register_image (image);
1134 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1137 GHashTable *loaded_images;
1140 g_return_val_if_fail (fname != NULL, NULL);
1142 #ifdef PLATFORM_WIN32
1143 /* Load modules using LoadLibrary. */
1144 if (!refonly && coree_module_handle) {
1145 HMODULE module_handle;
1146 guint16 *fname_utf16;
1149 absfname = mono_path_resolve_symlinks (fname);
1152 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1153 mono_images_lock ();
1154 image = g_hash_table_lookup (loaded_images_hash, absfname);
1156 g_assert (image->is_module_handle);
1157 if (image->has_entry_point && image->ref_count == 0) {
1158 /* Increment reference count on images loaded outside of the runtime. */
1159 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1160 /* The image is already loaded because _CorDllMain removes images from the hash. */
1161 module_handle = LoadLibrary (fname_utf16);
1162 g_assert (module_handle == (HMODULE) image->raw_data);
1164 mono_image_addref (image);
1165 mono_images_unlock ();
1167 g_free (fname_utf16);
1172 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1173 module_handle = MonoLoadImage (fname_utf16);
1174 if (status && module_handle == NULL)
1175 last_error = GetLastError ();
1177 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1178 image = g_hash_table_lookup (loaded_images_hash, absfname);
1180 mono_image_addref (image);
1181 mono_images_unlock ();
1183 g_free (fname_utf16);
1185 if (module_handle == NULL) {
1189 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1190 *status = MONO_IMAGE_IMAGE_INVALID;
1192 *status = MONO_IMAGE_ERROR_ERRNO;
1198 g_assert (image->is_module_handle);
1199 g_assert (image->has_entry_point);
1204 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1208 absfname = mono_path_canonicalize (fname);
1211 * The easiest solution would be to do all the loading inside the mutex,
1212 * but that would lead to scalability problems. So we let the loading
1213 * happen outside the mutex, and if multiple threads happen to load
1214 * the same image, we discard all but the first copy.
1216 mono_images_lock ();
1217 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1218 image = g_hash_table_lookup (loaded_images, absfname);
1222 mono_image_addref (image);
1223 mono_images_unlock ();
1226 mono_images_unlock ();
1228 image = do_mono_image_open (fname, status, TRUE, TRUE, refonly);
1232 return register_image (image);
1237 * @fname: filename that points to the module we want to open
1238 * @status: An error condition is returned in this field
1240 * Returns: An open image of type %MonoImage or NULL on error.
1241 * The caller holds a temporary reference to the returned image which should be cleared
1242 * when no longer needed by calling mono_image_close ().
1243 * if NULL, then check the value of @status for details on the error
1246 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1248 return mono_image_open_full (fname, status, FALSE);
1252 * mono_pe_file_open:
1253 * @fname: filename that points to the module we want to open
1254 * @status: An error condition is returned in this field
1256 * Returns: An open image of type %MonoImage or NULL on error. if
1257 * NULL, then check the value of @status for details on the error.
1258 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1259 * It's just a PE file loader, used for FileVersionInfo. It also does
1260 * not use the image cache.
1263 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1265 g_return_val_if_fail (fname != NULL, NULL);
1267 return(do_mono_image_open (fname, status, FALSE, TRUE, FALSE));
1271 * mono_image_open_raw
1272 * @fname: filename that points to the module we want to open
1273 * @status: An error condition is returned in this field
1275 * Returns an image without loading neither pe or cli data.
1277 * Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
1280 mono_image_open_raw (const char *fname, MonoImageOpenStatus *status)
1282 g_return_val_if_fail (fname != NULL, NULL);
1284 return(do_mono_image_open (fname, status, FALSE, FALSE, FALSE));
1288 mono_image_fixup_vtable (MonoImage *image)
1290 #ifdef PLATFORM_WIN32
1291 MonoCLIImageInfo *iinfo;
1293 MonoVTableFixup *vtfixup;
1299 g_assert (image->is_module_handle);
1301 iinfo = image->image_info;
1302 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1303 if (!de->rva || !de->size)
1305 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1309 count = de->size / sizeof (MonoVTableFixup);
1311 if (!vtfixup->rva || !vtfixup->count)
1314 slot = mono_image_rva_map (image, vtfixup->rva);
1316 slot_type = vtfixup->type;
1317 slot_count = vtfixup->count;
1318 if (slot_type & VTFIXUP_TYPE_32BIT)
1319 while (slot_count--) {
1320 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1321 slot = ((guint32*) slot) + 1;
1323 else if (slot_type & VTFIXUP_TYPE_64BIT)
1324 while (slot_count--) {
1325 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1326 slot = ((guint32*) slot) + 1;
1329 g_assert_not_reached();
1334 g_assert_not_reached();
1339 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1341 g_hash_table_destroy ((GHashTable*)val);
1346 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1348 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1353 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1359 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1361 g_slist_free ((GSList*)val);
1365 * mono_image_addref:
1366 * @image: The image file we wish to add a reference to
1368 * Increases the reference count of an image.
1371 mono_image_addref (MonoImage *image)
1373 InterlockedIncrement (&image->ref_count);
1377 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1379 stream->alloc_size = stream->index = stream->offset = 0;
1380 g_free (stream->data);
1381 stream->data = NULL;
1383 g_hash_table_destroy (stream->hash);
1384 stream->hash = NULL;
1389 free_hash (GHashTable *hash)
1392 g_hash_table_destroy (hash);
1397 * @image: The image file we wish to close
1399 * Closes an image file, deallocates all memory consumed and
1400 * unmaps all possible sections of the file
1403 mono_image_close (MonoImage *image)
1406 GHashTable *loaded_images;
1409 g_return_if_fail (image != NULL);
1411 if (InterlockedDecrement (&image->ref_count) > 0)
1414 #ifdef PLATFORM_WIN32
1415 if (image->is_module_handle && image->has_entry_point) {
1416 mono_images_lock ();
1417 if (image->ref_count == 0) {
1418 /* Image will be closed by _CorDllMain. */
1419 FreeLibrary ((HMODULE) image->raw_data);
1420 mono_images_unlock ();
1423 mono_images_unlock ();
1427 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1429 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1431 mono_metadata_clean_for_image (image);
1434 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1435 * assemblies, so we can't release these references in mono_assembly_close () since the
1436 * MonoImage might outlive its associated MonoAssembly.
1438 if (image->references && !image->dynamic) {
1439 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1442 for (i = 0; i < t->rows; i++) {
1443 if (image->references [i])
1444 mono_assembly_close (image->references [i]);
1447 g_free (image->references);
1448 image->references = NULL;
1451 mono_images_lock ();
1452 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1453 image2 = g_hash_table_lookup (loaded_images, image->name);
1454 if (image == image2) {
1455 /* This is not true if we are called from mono_image_open () */
1456 g_hash_table_remove (loaded_images, image->name);
1458 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1459 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1461 #ifdef PLATFORM_WIN32
1462 if (image->is_module_handle && !image->has_entry_point)
1463 FreeLibrary ((HMODULE) image->raw_data);
1466 mono_images_unlock ();
1468 if (image->raw_buffer_used) {
1469 if (image->raw_data != NULL)
1470 mono_file_unmap (image->raw_data, image->raw_data_handle);
1473 if (image->raw_data_allocated) {
1474 /* FIXME: do we need this? (image is disposed anyway) */
1475 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1476 MonoCLIImageInfo *ii = image->image_info;
1478 if ((image->raw_metadata > image->raw_data) &&
1479 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1480 image->raw_metadata = NULL;
1482 for (i = 0; i < ii->cli_section_count; i++)
1483 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1484 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1485 ii->cli_sections [i] = NULL;
1487 g_free (image->raw_data);
1490 if (debug_assembly_unload) {
1491 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1493 g_free (image->name);
1494 g_free (image->guid);
1495 g_free (image->version);
1496 g_free (image->files);
1499 if (image->method_cache)
1500 mono_value_hash_table_destroy (image->method_cache);
1501 if (image->methodref_cache)
1502 g_hash_table_destroy (image->methodref_cache);
1503 mono_internal_hash_table_destroy (&image->class_cache);
1504 g_hash_table_destroy (image->field_cache);
1505 if (image->array_cache) {
1506 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1507 g_hash_table_destroy (image->array_cache);
1509 if (image->szarray_cache)
1510 g_hash_table_destroy (image->szarray_cache);
1511 if (image->ptr_cache)
1512 g_hash_table_destroy (image->ptr_cache);
1513 if (image->name_cache) {
1514 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1515 g_hash_table_destroy (image->name_cache);
1518 free_hash (image->native_wrapper_cache);
1519 free_hash (image->managed_wrapper_cache);
1520 free_hash (image->delegate_begin_invoke_cache);
1521 free_hash (image->delegate_end_invoke_cache);
1522 free_hash (image->delegate_invoke_cache);
1523 free_hash (image->delegate_abstract_invoke_cache);
1524 if (image->remoting_invoke_cache)
1525 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1526 free_hash (image->remoting_invoke_cache);
1527 free_hash (image->runtime_invoke_cache);
1528 free_hash (image->runtime_invoke_direct_cache);
1529 free_hash (image->runtime_invoke_vcall_cache);
1530 free_hash (image->synchronized_cache);
1531 free_hash (image->unbox_wrapper_cache);
1532 free_hash (image->cominterop_invoke_cache);
1533 free_hash (image->cominterop_wrapper_cache);
1534 free_hash (image->typespec_cache);
1535 free_hash (image->ldfld_wrapper_cache);
1536 free_hash (image->ldflda_wrapper_cache);
1537 free_hash (image->stfld_wrapper_cache);
1538 free_hash (image->isinst_cache);
1539 free_hash (image->castclass_cache);
1540 free_hash (image->proxy_isinst_cache);
1541 free_hash (image->thunk_invoke_cache);
1543 /* The ownership of signatures is not well defined */
1544 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1545 g_hash_table_destroy (image->memberref_signatures);
1546 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1547 g_hash_table_destroy (image->helper_signatures);
1548 g_hash_table_destroy (image->method_signatures);
1550 if (image->generic_class_cache)
1551 g_hash_table_destroy (image->generic_class_cache);
1553 if (image->rgctx_template_hash)
1554 g_hash_table_destroy (image->rgctx_template_hash);
1556 if (image->property_hash)
1557 mono_property_hash_destroy (image->property_hash);
1559 g_slist_free (image->reflection_info_unregister_classes);
1561 if (image->interface_bitset) {
1562 mono_unload_interface_ids (image->interface_bitset);
1563 mono_bitset_free (image->interface_bitset);
1565 if (image->image_info){
1566 MonoCLIImageInfo *ii = image->image_info;
1568 if (ii->cli_section_tables)
1569 g_free (ii->cli_section_tables);
1570 if (ii->cli_sections)
1571 g_free (ii->cli_sections);
1572 g_free (image->image_info);
1575 for (i = 0; i < image->module_count; ++i) {
1576 if (image->modules [i])
1577 mono_image_close (image->modules [i]);
1580 g_free (image->modules);
1581 if (image->modules_loaded)
1582 g_free (image->modules_loaded);
1583 if (image->references)
1584 g_free (image->references);
1585 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1587 DeleteCriticalSection (&image->szarray_cache_lock);
1588 DeleteCriticalSection (&image->lock);
1590 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1591 if (!image->dynamic) {
1592 if (debug_assembly_unload)
1593 mono_mempool_invalidate (image->mempool);
1595 mono_mempool_destroy (image->mempool);
1599 /* Dynamic images are GC_MALLOCed */
1600 g_free ((char*)image->module_name);
1601 mono_dynamic_image_free ((MonoDynamicImage*)image);
1602 if (debug_assembly_unload)
1603 mono_mempool_invalidate (image->mempool);
1605 mono_mempool_destroy (image->mempool);
1608 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1612 * mono_image_strerror:
1613 * @status: an code indicating the result from a recent operation
1615 * Returns: a string describing the error
1618 mono_image_strerror (MonoImageOpenStatus status)
1623 case MONO_IMAGE_ERROR_ERRNO:
1624 return strerror (errno);
1625 case MONO_IMAGE_IMAGE_INVALID:
1626 return "File does not contain a valid CIL image";
1627 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1628 return "An assembly was referenced, but could not be found";
1630 return "Internal error";
1634 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1635 guint32 lang_id, gunichar2 *name,
1636 MonoPEResourceDirEntry *entry,
1637 MonoPEResourceDir *root, guint32 level)
1639 gboolean is_string, is_dir;
1640 guint32 name_offset, dir_offset;
1642 /* Level 0 holds a directory entry for each type of resource
1643 * (identified by ID or name).
1645 * Level 1 holds a directory entry for each named resource
1646 * item, and each "anonymous" item of a particular type of
1649 * Level 2 holds a directory entry for each language pointing to
1652 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1653 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1655 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1656 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1661 } else if (level==1) {
1662 if (res_id != name_offset)
1666 is_string==TRUE && name!=lookup (name_offset)) {
1670 } else if (level==2) {
1671 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1674 g_assert_not_reached ();
1678 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1679 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1682 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1684 for(i=0; i<entries; i++) {
1685 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1688 ret=mono_image_walk_resource_tree (info, res_id,
1699 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1700 MonoPEResourceDataEntry *res;
1702 res = g_new0 (MonoPEResourceDataEntry, 1);
1704 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1705 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1706 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1707 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1714 * mono_image_lookup_resource:
1715 * @image: the image to look up the resource in
1716 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1717 * @lang_id: The language id.
1718 * @name: the resource name to lookup.
1720 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1721 * of the given resource. The caller should free it using g_free () when no longer
1725 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1727 MonoCLIImageInfo *info;
1728 MonoDotNetHeader *header;
1729 MonoPEDatadir *datadir;
1730 MonoPEDirEntry *rsrc;
1731 MonoPEResourceDir *resource_dir;
1732 MonoPEResourceDirEntry *res_entries;
1739 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1741 info=image->image_info;
1746 header=&info->cli_header;
1751 datadir=&header->datadir;
1756 rsrc=&datadir->pe_resource_table;
1761 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1762 if(resource_dir==NULL) {
1766 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1767 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1769 for(i=0; i<entries; i++) {
1770 MonoPEResourceDirEntry *entry=&res_entries[i];
1773 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1774 name, entry, resource_dir,
1785 * mono_image_get_entry_point:
1786 * @image: the image where the entry point will be looked up.
1788 * Use this routine to determine the metadata token for method that
1789 * has been flagged as the entry point.
1791 * Returns: the token for the entry point method in the image
1794 mono_image_get_entry_point (MonoImage *image)
1796 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1800 * mono_image_get_resource:
1801 * @image: the image where the resource will be looked up.
1802 * @offset: The offset to add to the resource
1803 * @size: a pointer to an int where the size of the resource will be stored
1805 * This is a low-level routine that fetches a resource from the
1806 * metadata that starts at a given @offset. The @size parameter is
1807 * filled with the data field as encoded in the metadata.
1809 * Returns: the pointer to the resource whose offset is @offset.
1812 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1814 MonoCLIImageInfo *iinfo = image->image_info;
1815 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1818 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1821 data = mono_image_rva_map (image, ch->ch_resources.rva);
1826 *size = read32 (data);
1832 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1834 char *base_dir, *name;
1836 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1840 if (fileidx < 1 || fileidx > t->rows)
1843 mono_loader_lock ();
1844 if (image->files && image->files [fileidx - 1]) {
1845 mono_loader_unlock ();
1846 return image->files [fileidx - 1];
1850 image->files = g_new0 (MonoImage*, t->rows);
1852 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1853 fname = mono_metadata_string_heap (image, fname_id);
1854 base_dir = g_path_get_dirname (image->name);
1855 name = g_build_filename (base_dir, fname, NULL);
1856 res = mono_image_open (name, NULL);
1859 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1860 res->assembly = image->assembly;
1861 for (i = 0; i < res->module_count; ++i) {
1862 if (res->modules [i] && !res->modules [i]->assembly)
1863 res->modules [i]->assembly = image->assembly;
1866 image->files [fileidx - 1] = res;
1867 #ifdef PLATFORM_WIN32
1868 if (res->is_module_handle)
1869 mono_image_fixup_vtable (res);
1872 mono_loader_unlock ();
1879 * mono_image_get_strong_name:
1880 * @image: a MonoImage
1881 * @size: a guint32 pointer, or NULL.
1883 * If the image has a strong name, and @size is not NULL, the value
1884 * pointed to by size will have the size of the strong name.
1886 * Returns: NULL if the image does not have a strong name, or a
1887 * pointer to the public key.
1890 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1892 MonoCLIImageInfo *iinfo = image->image_info;
1893 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1896 if (!de->size || !de->rva)
1898 data = mono_image_rva_map (image, de->rva);
1907 * mono_image_strong_name_position:
1908 * @image: a MonoImage
1909 * @size: a guint32 pointer, or NULL.
1911 * If the image has a strong name, and @size is not NULL, the value
1912 * pointed to by size will have the size of the strong name.
1914 * Returns: the position within the image file where the strong name
1918 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1920 MonoCLIImageInfo *iinfo = image->image_info;
1921 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1926 if (!de->size || !de->rva)
1928 pos = mono_cli_rva_image_map (image, de->rva);
1929 return pos == INVALID_ADDRESS ? 0 : pos;
1933 * mono_image_get_public_key:
1934 * @image: a MonoImage
1935 * @size: a guint32 pointer, or NULL.
1937 * This is used to obtain the public key in the @image.
1939 * If the image has a public key, and @size is not NULL, the value
1940 * pointed to by size will have the size of the public key.
1942 * Returns: NULL if the image does not have a public key, or a pointer
1943 * to the public key.
1946 mono_image_get_public_key (MonoImage *image, guint32 *size)
1951 if (image->dynamic) {
1953 *size = ((MonoDynamicImage*)image)->public_key_len;
1954 return (char*)((MonoDynamicImage*)image)->public_key;
1956 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1958 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1961 pubkey = mono_metadata_blob_heap (image, tok);
1962 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1969 * mono_image_get_name:
1970 * @name: a MonoImage
1972 * Returns: the name of the assembly.
1975 mono_image_get_name (MonoImage *image)
1977 return image->assembly_name;
1981 * mono_image_get_filename:
1982 * @image: a MonoImage
1984 * Used to get the filename that hold the actual MonoImage
1986 * Returns: the filename.
1989 mono_image_get_filename (MonoImage *image)
1995 mono_image_get_guid (MonoImage *image)
2000 const MonoTableInfo*
2001 mono_image_get_table_info (MonoImage *image, int table_id)
2003 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2005 return &image->tables [table_id];
2009 mono_image_get_table_rows (MonoImage *image, int table_id)
2011 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
2013 return image->tables [table_id].rows;
2017 mono_table_info_get_rows (const MonoTableInfo *table)
2023 * mono_image_get_assembly:
2024 * @image: the MonoImage.
2026 * Use this routine to get the assembly that owns this image.
2028 * Returns: the assembly that holds this image.
2031 mono_image_get_assembly (MonoImage *image)
2033 return image->assembly;
2037 * mono_image_is_dynamic:
2038 * @image: the MonoImage
2040 * Determines if the given image was created dynamically through the
2041 * System.Reflection.Emit API
2043 * Returns: TRUE if the image was created dynamically, FALSE if not.
2046 mono_image_is_dynamic (MonoImage *image)
2048 return image->dynamic;
2052 * mono_image_has_authenticode_entry:
2053 * @image: the MonoImage
2055 * Use this routine to determine if the image has a Authenticode
2056 * Certificate Table.
2058 * Returns: TRUE if the image contains an authenticode entry in the PE
2062 mono_image_has_authenticode_entry (MonoImage *image)
2064 MonoCLIImageInfo *iinfo = image->image_info;
2065 MonoDotNetHeader *header = &iinfo->cli_header;
2066 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
2067 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
2068 return ((de->rva != 0) && (de->size > 8));
2072 mono_image_alloc (MonoImage *image, guint size)
2076 mono_perfcounters->loader_bytes += size;
2077 mono_image_lock (image);
2078 res = mono_mempool_alloc (image->mempool, size);
2079 mono_image_unlock (image);
2085 mono_image_alloc0 (MonoImage *image, guint size)
2089 mono_perfcounters->loader_bytes += size;
2090 mono_image_lock (image);
2091 res = mono_mempool_alloc0 (image->mempool, size);
2092 mono_image_unlock (image);
2098 mono_image_strdup (MonoImage *image, const char *s)
2102 mono_perfcounters->loader_bytes += strlen (s);
2103 mono_image_lock (image);
2104 res = mono_mempool_strdup (image->mempool, s);
2105 mono_image_unlock (image);
2111 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2115 new_list = mono_image_alloc (image, sizeof (GList));
2116 new_list->data = data;
2117 new_list->prev = list ? list->prev : NULL;
2118 new_list->next = list;
2121 new_list->prev->next = new_list;
2123 list->prev = new_list;
2129 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2133 new_list = mono_image_alloc (image, sizeof (GSList));
2134 new_list->data = data;
2135 new_list->next = NULL;
2137 return g_slist_concat (list, new_list);
2141 mono_image_lock (MonoImage *image)
2143 mono_locks_acquire (&image->lock, ImageDataLock);
2147 mono_image_unlock (MonoImage *image)
2149 mono_locks_release (&image->lock, ImageDataLock);
2154 * mono_image_property_lookup:
2156 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2158 * LOCKING: Takes the image lock
2161 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2165 mono_image_lock (image);
2166 res = mono_property_hash_lookup (image->property_hash, subject, property);
2167 mono_image_unlock (image);
2173 * mono_image_property_insert:
2175 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2177 * LOCKING: Takes the image lock
2180 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2182 mono_image_lock (image);
2183 mono_property_hash_insert (image->property_hash, subject, property, value);
2184 mono_image_unlock (image);
2188 * mono_image_property_remove:
2190 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2192 * LOCKING: Takes the image lock
2195 mono_image_property_remove (MonoImage *image, gpointer subject)
2197 mono_image_lock (image);
2198 mono_property_hash_remove_object (image->property_hash, subject);
2199 mono_image_unlock (image);