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 <sys/types.h>
44 #define INVALID_ADDRESS 0xffffffff
47 * Keeps track of the various assemblies loaded
49 static GHashTable *loaded_images_hash;
50 static GHashTable *loaded_images_refonly_hash;
52 static gboolean debug_assembly_unload = FALSE;
54 #define mono_images_lock() EnterCriticalSection (&images_mutex)
55 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
56 static CRITICAL_SECTION images_mutex;
58 /* returns offset relative to image->raw_data */
60 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
62 MonoCLIImageInfo *iinfo = image->image_info;
63 const int top = iinfo->cli_section_count;
64 MonoSectionTable *tables = iinfo->cli_section_tables;
67 for (i = 0; i < top; i++){
68 if ((addr >= tables->st_virtual_address) &&
69 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
71 if (image->is_module_handle)
74 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
78 return INVALID_ADDRESS;
82 * mono_images_rva_map:
84 * @addr: relative virtual address (RVA)
86 * This is a low-level routine used by the runtime to map relative
87 * virtual address (RVA) into their location in memory.
89 * Returns: the address in memory for the given RVA, or NULL if the
90 * RVA is not valid for this image.
93 mono_image_rva_map (MonoImage *image, guint32 addr)
95 MonoCLIImageInfo *iinfo = image->image_info;
96 const int top = iinfo->cli_section_count;
97 MonoSectionTable *tables = iinfo->cli_section_tables;
100 for (i = 0; i < top; i++){
101 if ((addr >= tables->st_virtual_address) &&
102 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
103 if (!iinfo->cli_sections [i]) {
104 if (!mono_image_ensure_section_idx (image, i))
107 #ifdef PLATFORM_WIN32
108 if (image->is_module_handle)
109 return image->raw_data + addr;
111 return (char*)iinfo->cli_sections [i] +
112 (addr - tables->st_virtual_address);
122 * Initialize the global variables used by this module.
125 mono_images_init (void)
127 InitializeCriticalSection (&images_mutex);
129 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
130 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
132 debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
136 * mono_images_cleanup:
138 * Free all resources used by this module.
141 mono_images_cleanup (void)
143 DeleteCriticalSection (&images_mutex);
145 g_hash_table_destroy (loaded_images_hash);
146 g_hash_table_destroy (loaded_images_refonly_hash);
150 * mono_image_ensure_section_idx:
151 * @image: The image we are operating on
152 * @section: section number that we will load/map into memory
154 * This routine makes sure that we have an in-memory copy of
155 * an image section (.text, .rsrc, .data).
157 * Returns: TRUE on success
160 mono_image_ensure_section_idx (MonoImage *image, int section)
162 MonoCLIImageInfo *iinfo = image->image_info;
163 MonoSectionTable *sect;
166 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
168 if (iinfo->cli_sections [section] != NULL)
171 sect = &iinfo->cli_section_tables [section];
173 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
175 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
177 #ifdef PLATFORM_WIN32
178 if (image->is_module_handle)
179 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
182 /* FIXME: we ignore the writable flag since we don't patch the binary */
183 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
188 * mono_image_ensure_section:
189 * @image: The image we are operating on
190 * @section: section name that we will load/map into memory
192 * This routine makes sure that we have an in-memory copy of
193 * an image section (.text, .rsrc, .data).
195 * Returns: TRUE on success
198 mono_image_ensure_section (MonoImage *image, const char *section)
200 MonoCLIImageInfo *ii = image->image_info;
203 for (i = 0; i < ii->cli_section_count; i++){
204 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
207 return mono_image_ensure_section_idx (image, i);
213 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
215 const int top = iinfo->cli_header.coff.coff_sections;
218 iinfo->cli_section_count = top;
219 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
220 iinfo->cli_sections = g_new0 (void *, top);
222 for (i = 0; i < top; i++){
223 MonoSectionTable *t = &iinfo->cli_section_tables [i];
225 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
227 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
228 offset += sizeof (MonoSectionTable);
230 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
231 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
232 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
233 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
234 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
235 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
236 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
237 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
238 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
239 t->st_flags = GUINT32_FROM_LE (t->st_flags);
241 /* consistency checks here */
248 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
252 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
253 if (offset == INVALID_ADDRESS)
256 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
258 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
260 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
261 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
262 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
263 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
264 SWAP32 (iinfo->cli_cli_header.ch_size);
265 SWAP32 (iinfo->cli_cli_header.ch_flags);
266 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
267 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
268 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
269 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
270 SWAPPDE (iinfo->cli_cli_header.ch_resources);
271 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
272 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
273 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
274 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
275 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
276 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
277 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
278 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
279 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
280 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
281 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
282 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
283 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
288 /* Catch new uses of the fields that are supposed to be zero */
290 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
291 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
292 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
293 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
294 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
295 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
296 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
297 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
298 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
301 * No need to scare people who are testing this, I am just
302 * labelling this as a LAMESPEC
304 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
312 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
314 guint32 offset, size;
320 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
321 if (offset == INVALID_ADDRESS)
324 size = iinfo->cli_cli_header.ch_metadata.size;
326 if (offset + size > image->raw_data_len)
328 image->raw_metadata = image->raw_data + offset;
330 ptr = image->raw_metadata;
332 if (strncmp (ptr, "BSJB", 4) == 0){
333 guint32 version_string_len;
336 image->md_version_major = read16 (ptr);
338 image->md_version_minor = read16 (ptr);
341 version_string_len = read32 (ptr);
343 image->version = g_strndup (ptr, version_string_len);
344 ptr += version_string_len;
345 pad = ptr - image->raw_metadata;
347 ptr += 4 - (pad % 4);
351 /* skip over flags */
354 streams = read16 (ptr);
357 for (i = 0; i < streams; i++){
358 if (strncmp (ptr + 8, "#~", 3) == 0){
359 image->heap_tables.data = image->raw_metadata + read32 (ptr);
360 image->heap_tables.size = read32 (ptr + 4);
362 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
363 image->heap_strings.data = image->raw_metadata + read32 (ptr);
364 image->heap_strings.size = read32 (ptr + 4);
366 } else if (strncmp (ptr + 8, "#US", 4) == 0){
367 image->heap_us.data = image->raw_metadata + read32 (ptr);
368 image->heap_us.size = read32 (ptr + 4);
370 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
371 image->heap_blob.data = image->raw_metadata + read32 (ptr);
372 image->heap_blob.size = read32 (ptr + 4);
374 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
375 image->heap_guid.data = image->raw_metadata + read32 (ptr);
376 image->heap_guid.size = read32 (ptr + 4);
378 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
379 image->heap_tables.data = image->raw_metadata + read32 (ptr);
380 image->heap_tables.size = read32 (ptr + 4);
382 image->uncompressed_metadata = TRUE;
383 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);
385 g_message ("Unknown heap type: %s\n", ptr + 8);
386 ptr += 8 + strlen (ptr + 8) + 1;
388 pad = ptr - image->raw_metadata;
390 ptr += 4 - (pad % 4);
393 g_assert (image->heap_guid.data);
394 g_assert (image->heap_guid.size >= 16);
396 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
402 * Load representation of logical metadata tables, from the "#~" stream
405 load_tables (MonoImage *image)
407 const char *heap_tables = image->heap_tables.data;
409 guint64 valid_mask, sorted_mask;
410 int valid = 0, table;
413 heap_sizes = heap_tables [6];
414 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
415 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
416 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
418 valid_mask = read64 (heap_tables + 8);
419 sorted_mask = read64 (heap_tables + 16);
420 rows = (const guint32 *) (heap_tables + 24);
422 for (table = 0; table < 64; table++){
423 if ((valid_mask & ((guint64) 1 << table)) == 0){
424 if (table > MONO_TABLE_LAST)
426 image->tables [table].rows = 0;
429 if (table > MONO_TABLE_LAST) {
430 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
432 image->tables [table].rows = read32 (rows);
434 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
435 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
441 image->tables_base = (heap_tables + 24) + (4 * valid);
443 /* They must be the same */
444 g_assert ((const void *) image->tables_base == (const void *) rows);
446 mono_metadata_compute_table_bases (image);
451 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
453 if (!load_metadata_ptrs (image, iinfo))
456 return load_tables (image);
460 mono_image_check_for_module_cctor (MonoImage *image)
462 MonoTableInfo *t, *mt;
463 t = &image->tables [MONO_TABLE_TYPEDEF];
464 mt = &image->tables [MONO_TABLE_METHOD];
465 if (mono_framework_version () == 1) {
466 image->checked_module_cctor = TRUE;
469 if (image->dynamic) {
471 image->checked_module_cctor = TRUE;
475 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
476 const char *name = mono_metadata_string_heap (image, nameidx);
477 if (strcmp (name, "<Module>") == 0) {
478 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
481 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
483 last_method = mt->rows;
484 for (; first_method < last_method; first_method++) {
485 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
486 name = mono_metadata_string_heap (image, nameidx);
487 if (strcmp (name, ".cctor") == 0) {
488 image->has_module_cctor = TRUE;
489 image->checked_module_cctor = TRUE;
495 image->has_module_cctor = FALSE;
496 image->checked_module_cctor = TRUE;
500 load_modules (MonoImage *image)
507 t = &image->tables [MONO_TABLE_MODULEREF];
508 image->modules = g_new0 (MonoImage *, t->rows);
509 image->modules_loaded = g_new0 (gboolean, t->rows);
510 image->module_count = t->rows;
514 * mono_image_load_module:
516 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
517 * it cannot be loaded.
520 mono_image_load_module (MonoImage *image, int idx)
523 MonoTableInfo *file_table;
526 gboolean refonly = image->ref_only;
527 GList *list_iter, *valid_modules = NULL;
528 MonoImageOpenStatus status;
530 g_assert (idx <= image->module_count);
531 if (image->modules_loaded [idx - 1])
532 return image->modules [idx - 1];
534 file_table = &image->tables [MONO_TABLE_FILE];
535 for (i = 0; i < file_table->rows; i++) {
536 guint32 cols [MONO_FILE_SIZE];
537 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
538 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
540 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
543 t = &image->tables [MONO_TABLE_MODULEREF];
544 base_dir = g_path_get_dirname (image->name);
549 guint32 cols [MONO_MODULEREF_SIZE];
550 /* if there is no file table, we try to load the module... */
551 int valid = file_table->rows == 0;
553 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
554 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
555 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
556 /* be safe with string dups, but we could just compare string indexes */
557 if (strcmp (list_iter->data, name) == 0) {
563 module_ref = g_build_filename (base_dir, name, NULL);
564 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
565 if (image->modules [idx - 1]) {
566 mono_image_addref (image->modules [idx - 1]);
567 image->modules [idx - 1]->assembly = image->assembly;
568 #ifdef PLATFORM_WIN32
569 if (image->modules [idx - 1]->is_module_handle)
570 mono_image_fixup_vtable (image->modules [idx - 1]);
572 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
578 image->modules_loaded [idx - 1] = TRUE;
581 g_list_free (valid_modules);
583 return image->modules [idx - 1];
587 class_key_extract (gpointer value)
589 MonoClass *class = value;
591 return GUINT_TO_POINTER (class->type_token);
595 class_next_value (gpointer value)
597 MonoClass *class = value;
599 return (gpointer*)&class->next_class_cache;
603 mono_image_init (MonoImage *image)
605 image->mempool = mono_mempool_new_size (512);
606 mono_internal_hash_table_init (&image->class_cache,
610 image->field_cache = g_hash_table_new (NULL, NULL);
612 image->typespec_cache = g_hash_table_new (NULL, NULL);
613 image->memberref_signatures = g_hash_table_new (NULL, NULL);
614 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
615 image->method_signatures = g_hash_table_new (NULL, NULL);
617 image->property_hash = mono_property_hash_new ();
618 InitializeCriticalSection (&image->lock);
619 InitializeCriticalSection (&image->szarray_cache_lock);
622 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
623 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
624 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
625 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
626 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
635 * Returns < 0 to indicate an error.
638 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
640 MonoDotNetHeader64 header64;
642 #ifdef PLATFORM_WIN32
643 if (!image->is_module_handle)
645 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
648 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
650 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
653 /* endian swap the fields common between PE and PE+ */
654 SWAP32 (header->coff.coff_time);
655 SWAP32 (header->coff.coff_symptr);
656 SWAP32 (header->coff.coff_symcount);
657 SWAP16 (header->coff.coff_machine);
658 SWAP16 (header->coff.coff_sections);
659 SWAP16 (header->coff.coff_opt_header_size);
660 SWAP16 (header->coff.coff_attributes);
662 SWAP32 (header->pe.pe_code_size);
663 SWAP32 (header->pe.pe_uninit_data_size);
664 SWAP32 (header->pe.pe_rva_entry_point);
665 SWAP32 (header->pe.pe_rva_code_base);
666 SWAP32 (header->pe.pe_rva_data_base);
667 SWAP16 (header->pe.pe_magic);
669 /* now we are ready for the basic tests */
671 if (header->pe.pe_magic == 0x10B) {
672 offset += sizeof (MonoDotNetHeader);
673 SWAP32 (header->pe.pe_data_size);
674 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
677 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
678 SWAP32 (header->nt.pe_stack_reserve);
679 SWAP32 (header->nt.pe_stack_commit);
680 SWAP32 (header->nt.pe_heap_reserve);
681 SWAP32 (header->nt.pe_heap_commit);
682 } else if (header->pe.pe_magic == 0x20B) {
683 /* PE32+ file format */
684 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
686 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
687 offset += sizeof (MonoDotNetHeader64);
688 /* copy the fields already swapped. the last field, pe_data_size, is missing */
689 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
690 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
691 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
693 SWAP64 (header64.nt.pe_image_base);
694 header->nt.pe_image_base = header64.nt.pe_image_base;
695 SWAP64 (header64.nt.pe_stack_reserve);
696 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
697 SWAP64 (header64.nt.pe_stack_commit);
698 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
699 SWAP64 (header64.nt.pe_heap_reserve);
700 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
701 SWAP64 (header64.nt.pe_heap_commit);
702 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
704 header->nt.pe_section_align = header64.nt.pe_section_align;
705 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
706 header->nt.pe_os_major = header64.nt.pe_os_major;
707 header->nt.pe_os_minor = header64.nt.pe_os_minor;
708 header->nt.pe_user_major = header64.nt.pe_user_major;
709 header->nt.pe_user_minor = header64.nt.pe_user_minor;
710 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
711 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
712 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
713 header->nt.pe_image_size = header64.nt.pe_image_size;
714 header->nt.pe_header_size = header64.nt.pe_header_size;
715 header->nt.pe_checksum = header64.nt.pe_checksum;
716 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
717 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
718 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
719 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
721 /* copy the datadir */
722 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
727 /* MonoPEHeaderNT: not used yet */
728 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
729 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
730 SWAP16 (header->nt.pe_os_major); /* must be 4 */
731 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
732 SWAP16 (header->nt.pe_user_major);
733 SWAP16 (header->nt.pe_user_minor);
734 SWAP16 (header->nt.pe_subsys_major);
735 SWAP16 (header->nt.pe_subsys_minor);
736 SWAP32 (header->nt.pe_reserved_1);
737 SWAP32 (header->nt.pe_image_size);
738 SWAP32 (header->nt.pe_header_size);
739 SWAP32 (header->nt.pe_checksum);
740 SWAP16 (header->nt.pe_subsys_required);
741 SWAP16 (header->nt.pe_dll_flags);
742 SWAP32 (header->nt.pe_loader_flags);
743 SWAP32 (header->nt.pe_data_dir_count);
745 /* MonoDotNetHeader: mostly unused */
746 SWAPPDE (header->datadir.pe_export_table);
747 SWAPPDE (header->datadir.pe_import_table);
748 SWAPPDE (header->datadir.pe_resource_table);
749 SWAPPDE (header->datadir.pe_exception_table);
750 SWAPPDE (header->datadir.pe_certificate_table);
751 SWAPPDE (header->datadir.pe_reloc_table);
752 SWAPPDE (header->datadir.pe_debug);
753 SWAPPDE (header->datadir.pe_copyright);
754 SWAPPDE (header->datadir.pe_global_ptr);
755 SWAPPDE (header->datadir.pe_tls_table);
756 SWAPPDE (header->datadir.pe_load_config_table);
757 SWAPPDE (header->datadir.pe_bound_import);
758 SWAPPDE (header->datadir.pe_iat);
759 SWAPPDE (header->datadir.pe_delay_import_desc);
760 SWAPPDE (header->datadir.pe_cli_header);
761 SWAPPDE (header->datadir.pe_reserved);
763 #ifdef PLATFORM_WIN32
764 if (image->is_module_handle)
765 image->raw_data_len = header->nt.pe_image_size;
772 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
773 gboolean care_about_cli)
775 MonoCLIImageInfo *iinfo;
776 MonoDotNetHeader *header;
777 MonoMSDOSHeader msdos;
780 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
782 mono_image_init (image);
784 iinfo = image->image_info;
785 header = &iinfo->cli_header;
788 *status = MONO_IMAGE_IMAGE_INVALID;
790 #ifdef PLATFORM_WIN32
791 if (!image->is_module_handle)
793 if (offset + sizeof (msdos) > image->raw_data_len)
795 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
797 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
800 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
802 offset = msdos.pe_offset;
804 offset = do_load_header (image, header, offset);
809 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
811 if (header->coff.coff_machine != 0x14c)
817 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
818 * which produces binaries with 7.0. From Sergey:
820 * The reason is that MSVC7 uses traditional compile/link
821 * sequence for CIL executables, and VS.NET (and Framework
822 * SDK) includes linker version 7, that puts 7.0 in this
823 * field. That's why it's currently not possible to load VC
824 * binaries with Mono. This field is pretty much meaningless
825 * anyway (what linker?).
827 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
832 * FIXME: byte swap all addresses here for header.
835 if (!load_section_tables (image, iinfo, offset))
838 if (care_about_cli == FALSE) {
842 /* Load the CLI header */
843 if (!load_cli_header (image, iinfo))
846 if (!load_metadata (image, iinfo))
849 /* modules don't have an assembly table row */
850 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
851 image->assembly_name = mono_metadata_string_heap (image,
852 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
853 0, MONO_ASSEMBLY_NAME));
856 image->module_name = mono_metadata_string_heap (image,
857 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
858 0, MONO_MODULE_NAME));
860 load_modules (image);
863 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
865 *status = MONO_IMAGE_OK;
870 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
871 mono_image_close (image);
876 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
877 gboolean care_about_cli, gboolean refonly)
879 MonoCLIImageInfo *iinfo;
883 if ((filed = mono_file_map_open (fname)) == NULL){
884 if (IS_PORTABILITY_SET) {
885 gchar *ffname = mono_portability_find_file (fname, TRUE);
887 filed = mono_file_map_open (ffname);
894 *status = MONO_IMAGE_ERROR_ERRNO;
899 image = g_new0 (MonoImage, 1);
900 image->raw_buffer_used = TRUE;
901 image->raw_data_len = mono_file_map_size (filed);
902 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);
903 if (!image->raw_data) {
904 mono_file_map_close (filed);
907 *status = MONO_IMAGE_IMAGE_INVALID;
910 iinfo = g_new0 (MonoCLIImageInfo, 1);
911 image->image_info = iinfo;
912 image->name = mono_path_resolve_symlinks (fname);
913 image->ref_only = refonly;
914 image->ref_count = 1;
915 /* if MONO_SECURITY_MODE_CORE_CLR is set then determine if this image is platform code */
916 image->core_clr_platform_code = mono_security_core_clr_determine_platform_image (image);
918 mono_file_map_close (filed);
919 return do_mono_image_load (image, status, care_about_cli);
923 mono_image_loaded_full (const char *name, gboolean refonly)
926 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
929 res = g_hash_table_lookup (loaded_images, name);
930 mono_images_unlock ();
936 * @name: name of the image to load
938 * This routine ensures that the given image is loaded.
940 * Returns: the loaded MonoImage, or NULL on failure.
943 mono_image_loaded (const char *name)
945 return mono_image_loaded_full (name, FALSE);
954 find_by_guid (gpointer key, gpointer val, gpointer user_data)
956 GuidData *data = user_data;
962 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
967 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
970 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
975 g_hash_table_foreach (loaded_images, find_by_guid, &data);
976 mono_images_unlock ();
981 mono_image_loaded_by_guid (const char *guid)
983 return mono_image_loaded_by_guid_full (guid, FALSE);
987 register_image (MonoImage *image)
990 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
993 image2 = g_hash_table_lookup (loaded_images, image->name);
996 /* Somebody else beat us to it */
997 mono_image_addref (image2);
998 mono_images_unlock ();
999 mono_image_close (image);
1002 g_hash_table_insert (loaded_images, image->name, image);
1003 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1004 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1005 mono_images_unlock ();
1011 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1013 MonoCLIImageInfo *iinfo;
1017 if (!data || !data_len) {
1019 *status = MONO_IMAGE_IMAGE_INVALID;
1024 datac = g_try_malloc (data_len);
1027 *status = MONO_IMAGE_ERROR_ERRNO;
1030 memcpy (datac, data, data_len);
1033 image = g_new0 (MonoImage, 1);
1034 image->raw_data = datac;
1035 image->raw_data_len = data_len;
1036 image->raw_data_allocated = need_copy;
1037 image->name = g_strdup_printf ("data-%p", datac);
1038 iinfo = g_new0 (MonoCLIImageInfo, 1);
1039 image->image_info = iinfo;
1040 image->ref_only = refonly;
1042 image = do_mono_image_load (image, status, TRUE);
1046 return register_image (image);
1050 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1052 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1055 #ifdef PLATFORM_WIN32
1056 /* fname is not duplicated. */
1058 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1061 MonoCLIImageInfo* iinfo;
1063 image = g_new0 (MonoImage, 1);
1064 image->raw_data = (char*) module_handle;
1065 image->is_module_handle = TRUE;
1066 iinfo = g_new0 (MonoCLIImageInfo, 1);
1067 image->image_info = iinfo;
1068 image->name = fname;
1069 image->ref_count = has_entry_point ? 0 : 1;
1070 image->has_entry_point = has_entry_point;
1072 image = do_mono_image_load (image, status, TRUE);
1076 return register_image (image);
1081 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1084 GHashTable *loaded_images;
1087 g_return_val_if_fail (fname != NULL, NULL);
1089 #ifdef PLATFORM_WIN32
1090 /* Load modules using LoadLibrary. */
1091 if (!refonly && coree_module_handle) {
1092 HMODULE module_handle;
1093 guint16 *fname_utf16;
1096 absfname = mono_path_resolve_symlinks (fname);
1099 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1100 mono_images_lock ();
1101 image = g_hash_table_lookup (loaded_images_hash, absfname);
1103 g_assert (image->is_module_handle);
1104 if (image->has_entry_point && image->ref_count == 0) {
1105 /* Increment reference count on images loaded outside of the runtime. */
1106 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1107 /* The image is already loaded because _CorDllMain removes images from the hash. */
1108 module_handle = LoadLibrary (fname_utf16);
1109 g_assert (module_handle == (HMODULE) image->raw_data);
1111 mono_image_addref (image);
1112 mono_images_unlock ();
1114 g_free (fname_utf16);
1119 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1120 module_handle = MonoLoadImage (fname_utf16);
1121 if (status && module_handle == NULL)
1122 last_error = GetLastError ();
1124 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1125 image = g_hash_table_lookup (loaded_images_hash, absfname);
1127 mono_image_addref (image);
1128 mono_images_unlock ();
1130 g_free (fname_utf16);
1132 if (module_handle == NULL) {
1136 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1137 *status = MONO_IMAGE_IMAGE_INVALID;
1139 *status = MONO_IMAGE_ERROR_ERRNO;
1145 g_assert (image->is_module_handle);
1146 g_assert (image->has_entry_point);
1151 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1155 absfname = mono_path_canonicalize (fname);
1158 * The easiest solution would be to do all the loading inside the mutex,
1159 * but that would lead to scalability problems. So we let the loading
1160 * happen outside the mutex, and if multiple threads happen to load
1161 * the same image, we discard all but the first copy.
1163 mono_images_lock ();
1164 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1165 image = g_hash_table_lookup (loaded_images, absfname);
1169 mono_image_addref (image);
1170 mono_images_unlock ();
1173 mono_images_unlock ();
1175 image = do_mono_image_open (fname, status, TRUE, refonly);
1179 return register_image (image);
1184 * @fname: filename that points to the module we want to open
1185 * @status: An error condition is returned in this field
1187 * Returns: An open image of type %MonoImage or NULL on error.
1188 * The caller holds a temporary reference to the returned image which should be cleared
1189 * when no longer needed by calling mono_image_close ().
1190 * if NULL, then check the value of @status for details on the error
1193 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1195 return mono_image_open_full (fname, status, FALSE);
1199 * mono_pe_file_open:
1200 * @fname: filename that points to the module we want to open
1201 * @status: An error condition is returned in this field
1203 * Returns: An open image of type %MonoImage or NULL on error. if
1204 * NULL, then check the value of @status for details on the error.
1205 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1206 * It's just a PE file loader, used for FileVersionInfo. It also does
1207 * not use the image cache.
1210 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1212 g_return_val_if_fail (fname != NULL, NULL);
1214 return(do_mono_image_open (fname, status, FALSE, FALSE));
1218 mono_image_fixup_vtable (MonoImage *image)
1220 #ifdef PLATFORM_WIN32
1221 MonoCLIImageInfo *iinfo;
1223 MonoVTableFixup *vtfixup;
1229 g_assert (image->is_module_handle);
1231 iinfo = image->image_info;
1232 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1233 if (!de->rva || !de->size)
1235 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1239 count = de->size / sizeof (MonoVTableFixup);
1241 if (!vtfixup->rva || !vtfixup->count)
1244 slot = mono_image_rva_map (image, vtfixup->rva);
1246 slot_type = vtfixup->type;
1247 slot_count = vtfixup->count;
1248 if (slot_type & VTFIXUP_TYPE_32BIT)
1249 while (slot_count--) {
1250 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1251 ((guint32*) slot)++;
1253 else if (slot_type & VTFIXUP_TYPE_64BIT)
1254 while (slot_count--) {
1255 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1256 ((guint64*) slot)++;
1259 g_assert_not_reached();
1264 g_assert_not_reached();
1269 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1271 g_hash_table_destroy ((GHashTable*)val);
1276 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1278 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1283 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1289 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1291 g_slist_free ((GSList*)val);
1295 * mono_image_addref:
1296 * @image: The image file we wish to add a reference to
1298 * Increases the reference count of an image.
1301 mono_image_addref (MonoImage *image)
1303 InterlockedIncrement (&image->ref_count);
1307 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1309 stream->alloc_size = stream->index = stream->offset = 0;
1310 g_free (stream->data);
1311 stream->data = NULL;
1313 g_hash_table_destroy (stream->hash);
1314 stream->hash = NULL;
1319 free_hash (GHashTable *hash)
1322 g_hash_table_destroy (hash);
1327 * @image: The image file we wish to close
1329 * Closes an image file, deallocates all memory consumed and
1330 * unmaps all possible sections of the file
1333 mono_image_close (MonoImage *image)
1336 GHashTable *loaded_images;
1339 g_return_if_fail (image != NULL);
1341 if (InterlockedDecrement (&image->ref_count) > 0)
1344 #ifdef PLATFORM_WIN32
1345 if (image->is_module_handle && image->has_entry_point) {
1346 mono_images_lock ();
1347 if (image->ref_count == 0) {
1348 /* Image will be closed by _CorDllMain. */
1349 FreeLibrary ((HMODULE) image->raw_data);
1350 mono_images_unlock ();
1353 mono_images_unlock ();
1357 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1359 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1361 mono_metadata_clean_for_image (image);
1364 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1365 * assemblies, so we can't release these references in mono_assembly_close () since the
1366 * MonoImage might outlive its associated MonoAssembly.
1368 if (image->references && !image->dynamic) {
1369 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1372 for (i = 0; i < t->rows; i++) {
1373 if (image->references [i])
1374 mono_assembly_close (image->references [i]);
1377 g_free (image->references);
1378 image->references = NULL;
1381 mono_images_lock ();
1382 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1383 image2 = g_hash_table_lookup (loaded_images, image->name);
1384 if (image == image2) {
1385 /* This is not true if we are called from mono_image_open () */
1386 g_hash_table_remove (loaded_images, image->name);
1388 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1389 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1391 #ifdef PLATFORM_WIN32
1392 if (image->is_module_handle && !image->has_entry_point)
1393 FreeLibrary ((HMODULE) image->raw_data);
1396 mono_images_unlock ();
1398 if (image->raw_buffer_used) {
1399 if (image->raw_data != NULL)
1400 mono_file_unmap (image->raw_data, image->raw_data_handle);
1403 if (image->raw_data_allocated) {
1404 /* FIXME: do we need this? (image is disposed anyway) */
1405 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1406 MonoCLIImageInfo *ii = image->image_info;
1408 if ((image->raw_metadata > image->raw_data) &&
1409 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1410 image->raw_metadata = NULL;
1412 for (i = 0; i < ii->cli_section_count; i++)
1413 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1414 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1415 ii->cli_sections [i] = NULL;
1417 g_free (image->raw_data);
1420 if (debug_assembly_unload) {
1421 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1423 g_free (image->name);
1424 g_free (image->guid);
1425 g_free (image->version);
1426 g_free (image->files);
1429 if (image->method_cache)
1430 mono_value_hash_table_destroy (image->method_cache);
1431 if (image->methodref_cache)
1432 g_hash_table_destroy (image->methodref_cache);
1433 mono_internal_hash_table_destroy (&image->class_cache);
1434 g_hash_table_destroy (image->field_cache);
1435 if (image->array_cache) {
1436 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1437 g_hash_table_destroy (image->array_cache);
1439 if (image->szarray_cache)
1440 g_hash_table_destroy (image->szarray_cache);
1441 if (image->ptr_cache)
1442 g_hash_table_destroy (image->ptr_cache);
1443 if (image->name_cache) {
1444 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1445 g_hash_table_destroy (image->name_cache);
1448 free_hash (image->native_wrapper_cache);
1449 free_hash (image->managed_wrapper_cache);
1450 free_hash (image->delegate_begin_invoke_cache);
1451 free_hash (image->delegate_end_invoke_cache);
1452 free_hash (image->delegate_invoke_cache);
1453 free_hash (image->delegate_abstract_invoke_cache);
1454 if (image->remoting_invoke_cache)
1455 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1456 free_hash (image->remoting_invoke_cache);
1457 free_hash (image->runtime_invoke_cache);
1458 free_hash (image->runtime_invoke_direct_cache);
1459 free_hash (image->runtime_invoke_vcall_cache);
1460 free_hash (image->synchronized_cache);
1461 free_hash (image->unbox_wrapper_cache);
1462 free_hash (image->cominterop_invoke_cache);
1463 free_hash (image->cominterop_wrapper_cache);
1464 free_hash (image->typespec_cache);
1465 free_hash (image->ldfld_wrapper_cache);
1466 free_hash (image->ldflda_wrapper_cache);
1467 free_hash (image->stfld_wrapper_cache);
1468 free_hash (image->isinst_cache);
1469 free_hash (image->castclass_cache);
1470 free_hash (image->proxy_isinst_cache);
1471 free_hash (image->thunk_invoke_cache);
1472 free_hash (image->static_rgctx_invoke_cache);
1474 /* The ownership of signatures is not well defined */
1475 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1476 g_hash_table_destroy (image->memberref_signatures);
1477 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1478 g_hash_table_destroy (image->helper_signatures);
1479 g_hash_table_destroy (image->method_signatures);
1481 if (image->generic_class_cache)
1482 g_hash_table_destroy (image->generic_class_cache);
1484 if (image->rgctx_template_hash)
1485 g_hash_table_destroy (image->rgctx_template_hash);
1487 if (image->property_hash)
1488 mono_property_hash_destroy (image->property_hash);
1490 if (image->interface_bitset) {
1491 mono_unload_interface_ids (image->interface_bitset);
1492 mono_bitset_free (image->interface_bitset);
1494 if (image->image_info){
1495 MonoCLIImageInfo *ii = image->image_info;
1497 if (ii->cli_section_tables)
1498 g_free (ii->cli_section_tables);
1499 if (ii->cli_sections)
1500 g_free (ii->cli_sections);
1501 g_free (image->image_info);
1504 for (i = 0; i < image->module_count; ++i) {
1505 if (image->modules [i])
1506 mono_image_close (image->modules [i]);
1509 g_free (image->modules);
1510 if (image->modules_loaded)
1511 g_free (image->modules_loaded);
1512 if (image->references)
1513 g_free (image->references);
1514 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1516 DeleteCriticalSection (&image->szarray_cache_lock);
1517 DeleteCriticalSection (&image->lock);
1519 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1520 if (!image->dynamic) {
1521 if (debug_assembly_unload)
1522 mono_mempool_invalidate (image->mempool);
1524 mono_mempool_destroy (image->mempool);
1528 /* Dynamic images are GC_MALLOCed */
1529 g_free ((char*)image->module_name);
1530 mono_dynamic_image_free ((MonoDynamicImage*)image);
1531 mono_mempool_destroy (image->mempool);
1534 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1538 * mono_image_strerror:
1539 * @status: an code indicating the result from a recent operation
1541 * Returns: a string describing the error
1544 mono_image_strerror (MonoImageOpenStatus status)
1549 case MONO_IMAGE_ERROR_ERRNO:
1550 return strerror (errno);
1551 case MONO_IMAGE_IMAGE_INVALID:
1552 return "File does not contain a valid CIL image";
1553 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1554 return "An assembly was referenced, but could not be found";
1556 return "Internal error";
1560 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1561 guint32 lang_id, gunichar2 *name,
1562 MonoPEResourceDirEntry *entry,
1563 MonoPEResourceDir *root, guint32 level)
1565 gboolean is_string, is_dir;
1566 guint32 name_offset, dir_offset;
1568 /* Level 0 holds a directory entry for each type of resource
1569 * (identified by ID or name).
1571 * Level 1 holds a directory entry for each named resource
1572 * item, and each "anonymous" item of a particular type of
1575 * Level 2 holds a directory entry for each language pointing to
1578 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1579 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1581 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1582 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1587 } else if (level==1) {
1588 if (res_id != name_offset)
1592 is_string==TRUE && name!=lookup (name_offset)) {
1596 } else if (level==2) {
1597 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1600 g_assert_not_reached ();
1604 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1605 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1608 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1610 for(i=0; i<entries; i++) {
1611 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1614 ret=mono_image_walk_resource_tree (info, res_id,
1625 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1626 MonoPEResourceDataEntry *res;
1628 res = g_new0 (MonoPEResourceDataEntry, 1);
1630 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1631 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1632 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1633 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1640 * mono_image_lookup_resource:
1641 * @image: the image to look up the resource in
1642 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1643 * @lang_id: The language id.
1644 * @name: the resource name to lookup.
1646 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1647 * of the given resource. The caller should free it using g_free () when no longer
1651 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1653 MonoCLIImageInfo *info;
1654 MonoDotNetHeader *header;
1655 MonoPEDatadir *datadir;
1656 MonoPEDirEntry *rsrc;
1657 MonoPEResourceDir *resource_dir;
1658 MonoPEResourceDirEntry *res_entries;
1665 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1667 info=image->image_info;
1672 header=&info->cli_header;
1677 datadir=&header->datadir;
1682 rsrc=&datadir->pe_resource_table;
1687 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1688 if(resource_dir==NULL) {
1692 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1693 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1695 for(i=0; i<entries; i++) {
1696 MonoPEResourceDirEntry *entry=&res_entries[i];
1699 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1700 name, entry, resource_dir,
1711 * mono_image_get_entry_point:
1712 * @image: the image where the entry point will be looked up.
1714 * Use this routine to determine the metadata token for method that
1715 * has been flagged as the entry point.
1717 * Returns: the token for the entry point method in the image
1720 mono_image_get_entry_point (MonoImage *image)
1722 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1726 * mono_image_get_resource:
1727 * @image: the image where the resource will be looked up.
1728 * @offset: The offset to add to the resource
1729 * @size: a pointer to an int where the size of the resource will be stored
1731 * This is a low-level routine that fetches a resource from the
1732 * metadata that starts at a given @offset. The @size parameter is
1733 * filled with the data field as encoded in the metadata.
1735 * Returns: the pointer to the resource whose offset is @offset.
1738 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1740 MonoCLIImageInfo *iinfo = image->image_info;
1741 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1744 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1747 data = mono_image_rva_map (image, ch->ch_resources.rva);
1752 *size = read32 (data);
1758 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1760 char *base_dir, *name;
1762 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1766 if (fileidx < 1 || fileidx > t->rows)
1769 mono_loader_lock ();
1770 if (image->files && image->files [fileidx - 1]) {
1771 mono_loader_unlock ();
1772 return image->files [fileidx - 1];
1776 image->files = g_new0 (MonoImage*, t->rows);
1778 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1779 fname = mono_metadata_string_heap (image, fname_id);
1780 base_dir = g_path_get_dirname (image->name);
1781 name = g_build_filename (base_dir, fname, NULL);
1782 res = mono_image_open (name, NULL);
1785 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1786 res->assembly = image->assembly;
1787 for (i = 0; i < res->module_count; ++i) {
1788 if (res->modules [i] && !res->modules [i]->assembly)
1789 res->modules [i]->assembly = image->assembly;
1792 image->files [fileidx - 1] = res;
1793 #ifdef PLATFORM_WIN32
1794 if (res->is_module_handle)
1795 mono_image_fixup_vtable (res);
1798 mono_loader_unlock ();
1805 * mono_image_get_strong_name:
1806 * @image: a MonoImage
1807 * @size: a guint32 pointer, or NULL.
1809 * If the image has a strong name, and @size is not NULL, the value
1810 * pointed to by size will have the size of the strong name.
1812 * Returns: NULL if the image does not have a strong name, or a
1813 * pointer to the public key.
1816 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1818 MonoCLIImageInfo *iinfo = image->image_info;
1819 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1822 if (!de->size || !de->rva)
1824 data = mono_image_rva_map (image, de->rva);
1833 * mono_image_strong_name_position:
1834 * @image: a MonoImage
1835 * @size: a guint32 pointer, or NULL.
1837 * If the image has a strong name, and @size is not NULL, the value
1838 * pointed to by size will have the size of the strong name.
1840 * Returns: the position within the image file where the strong name
1844 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1846 MonoCLIImageInfo *iinfo = image->image_info;
1847 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1852 if (!de->size || !de->rva)
1854 pos = mono_cli_rva_image_map (image, de->rva);
1855 return pos == INVALID_ADDRESS ? 0 : pos;
1859 * mono_image_get_public_key:
1860 * @image: a MonoImage
1861 * @size: a guint32 pointer, or NULL.
1863 * This is used to obtain the public key in the @image.
1865 * If the image has a public key, and @size is not NULL, the value
1866 * pointed to by size will have the size of the public key.
1868 * Returns: NULL if the image does not have a public key, or a pointer
1869 * to the public key.
1872 mono_image_get_public_key (MonoImage *image, guint32 *size)
1877 if (image->dynamic) {
1879 *size = ((MonoDynamicImage*)image)->public_key_len;
1880 return (char*)((MonoDynamicImage*)image)->public_key;
1882 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1884 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1887 pubkey = mono_metadata_blob_heap (image, tok);
1888 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1895 * mono_image_get_name:
1896 * @name: a MonoImage
1898 * Returns: the name of the assembly.
1901 mono_image_get_name (MonoImage *image)
1903 return image->assembly_name;
1907 * mono_image_get_filename:
1908 * @image: a MonoImage
1910 * Used to get the filename that hold the actual MonoImage
1912 * Returns: the filename.
1915 mono_image_get_filename (MonoImage *image)
1921 mono_image_get_guid (MonoImage *image)
1926 const MonoTableInfo*
1927 mono_image_get_table_info (MonoImage *image, int table_id)
1929 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1931 return &image->tables [table_id];
1935 mono_image_get_table_rows (MonoImage *image, int table_id)
1937 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1939 return image->tables [table_id].rows;
1943 mono_table_info_get_rows (const MonoTableInfo *table)
1949 * mono_image_get_assembly:
1950 * @image: the MonoImage.
1952 * Use this routine to get the assembly that owns this image.
1954 * Returns: the assembly that holds this image.
1957 mono_image_get_assembly (MonoImage *image)
1959 return image->assembly;
1963 * mono_image_is_dynamic:
1964 * @image: the MonoImage
1966 * Determines if the given image was created dynamically through the
1967 * System.Reflection.Emit API
1969 * Returns: TRUE if the image was created dynamically, FALSE if not.
1972 mono_image_is_dynamic (MonoImage *image)
1974 return image->dynamic;
1978 * mono_image_has_authenticode_entry:
1979 * @image: the MonoImage
1981 * Use this routine to determine if the image has a Authenticode
1982 * Certificate Table.
1984 * Returns: TRUE if the image contains an authenticode entry in the PE
1988 mono_image_has_authenticode_entry (MonoImage *image)
1990 MonoCLIImageInfo *iinfo = image->image_info;
1991 MonoDotNetHeader *header = &iinfo->cli_header;
1992 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1993 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1994 return ((de->rva != 0) && (de->size > 8));
1998 mono_image_alloc (MonoImage *image, guint size)
2002 mono_perfcounters->loader_bytes += size;
2003 mono_image_lock (image);
2004 res = mono_mempool_alloc (image->mempool, size);
2005 mono_image_unlock (image);
2011 mono_image_alloc0 (MonoImage *image, guint size)
2015 mono_perfcounters->loader_bytes += size;
2016 mono_image_lock (image);
2017 res = mono_mempool_alloc0 (image->mempool, size);
2018 mono_image_unlock (image);
2024 mono_image_strdup (MonoImage *image, const char *s)
2028 mono_perfcounters->loader_bytes += strlen (s);
2029 mono_image_lock (image);
2030 res = mono_mempool_strdup (image->mempool, s);
2031 mono_image_unlock (image);
2037 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2041 new_list = mono_image_alloc (image, sizeof (GList));
2042 new_list->data = data;
2043 new_list->prev = list ? list->prev : NULL;
2044 new_list->next = list;
2047 new_list->prev->next = new_list;
2049 list->prev = new_list;
2055 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2059 new_list = mono_image_alloc (image, sizeof (GSList));
2060 new_list->data = data;
2061 new_list->next = NULL;
2063 return g_slist_concat (list, new_list);
2067 mono_image_lock (MonoImage *image)
2069 mono_locks_acquire (&image->lock, ImageDataLock);
2073 mono_image_unlock (MonoImage *image)
2075 mono_locks_release (&image->lock, ImageDataLock);
2080 * mono_image_property_lookup:
2082 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2084 * LOCKING: Takes the image lock
2087 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2091 mono_image_lock (image);
2092 res = mono_property_hash_lookup (image->property_hash, subject, property);
2093 mono_image_unlock (image);
2099 * mono_image_property_insert:
2101 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2103 * LOCKING: Takes the image lock
2106 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2108 mono_image_lock (image);
2109 mono_property_hash_insert (image->property_hash, subject, property, value);
2110 mono_image_unlock (image);
2114 * mono_image_property_remove:
2116 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2118 * LOCKING: Takes the image lock
2121 mono_image_property_remove (MonoImage *image, gpointer subject)
2123 mono_image_lock (image);
2124 mono_property_hash_remove_object (image->property_hash, subject);
2125 mono_image_unlock (image);