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 * (C) 2001-2003 Ximian, Inc. http://www.ximian.com
20 #include "mono-endian.h"
21 #include "tabledefs.h"
22 #include "tokentype.h"
23 #include "metadata-internals.h"
24 #include "profiler-private.h"
28 #include <mono/io-layer/io-layer.h>
29 #include <mono/utils/mono-logger.h>
30 #include <mono/utils/mono-path.h>
31 #include <mono/utils/mono-mmap.h>
32 #include <mono/utils/mono-io-portability.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/assembly.h>
35 #include <mono/metadata/object-internals.h>
36 #include <sys/types.h>
42 #define INVALID_ADDRESS 0xffffffff
45 * Keeps track of the various assemblies loaded
47 static GHashTable *loaded_images_hash;
48 static GHashTable *loaded_images_refonly_hash;
50 static gboolean debug_assembly_unload = FALSE;
52 #define mono_images_lock() EnterCriticalSection (&images_mutex)
53 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
54 static CRITICAL_SECTION images_mutex;
56 /* returns offset relative to image->raw_data */
58 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
60 MonoCLIImageInfo *iinfo = image->image_info;
61 const int top = iinfo->cli_section_count;
62 MonoSectionTable *tables = iinfo->cli_section_tables;
65 for (i = 0; i < top; i++){
66 if ((addr >= tables->st_virtual_address) &&
67 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
69 if (image->is_module_handle)
72 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
76 return INVALID_ADDRESS;
80 * mono_images_rva_map:
82 * @addr: relative virtual address (RVA)
84 * This is a low-level routine used by the runtime to map relative
85 * virtual address (RVA) into their location in memory.
87 * Returns: the address in memory for the given RVA, or NULL if the
88 * RVA is not valid for this image.
91 mono_image_rva_map (MonoImage *image, guint32 addr)
93 MonoCLIImageInfo *iinfo = image->image_info;
94 const int top = iinfo->cli_section_count;
95 MonoSectionTable *tables = iinfo->cli_section_tables;
98 for (i = 0; i < top; i++){
99 if ((addr >= tables->st_virtual_address) &&
100 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
101 if (!iinfo->cli_sections [i]) {
102 if (!mono_image_ensure_section_idx (image, i))
105 #ifdef PLATFORM_WIN32
106 if (image->is_module_handle)
107 return image->raw_data + addr;
109 return (char*)iinfo->cli_sections [i] +
110 (addr - tables->st_virtual_address);
120 * Initialize the global variables used by this module.
123 mono_images_init (void)
125 InitializeCriticalSection (&images_mutex);
127 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
128 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
130 debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
134 * mono_images_cleanup:
136 * Free all resources used by this module.
139 mono_images_cleanup (void)
141 DeleteCriticalSection (&images_mutex);
143 g_hash_table_destroy (loaded_images_hash);
144 g_hash_table_destroy (loaded_images_refonly_hash);
148 * mono_image_ensure_section_idx:
149 * @image: The image we are operating on
150 * @section: section number that we will load/map into memory
152 * This routine makes sure that we have an in-memory copy of
153 * an image section (.text, .rsrc, .data).
155 * Returns: TRUE on success
158 mono_image_ensure_section_idx (MonoImage *image, int section)
160 MonoCLIImageInfo *iinfo = image->image_info;
161 MonoSectionTable *sect;
164 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
166 if (iinfo->cli_sections [section] != NULL)
169 sect = &iinfo->cli_section_tables [section];
171 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
173 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
175 #ifdef PLATFORM_WIN32
176 if (image->is_module_handle)
177 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
180 /* FIXME: we ignore the writable flag since we don't patch the binary */
181 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
186 * mono_image_ensure_section:
187 * @image: The image we are operating on
188 * @section: section name that we will load/map into memory
190 * This routine makes sure that we have an in-memory copy of
191 * an image section (.text, .rsrc, .data).
193 * Returns: TRUE on success
196 mono_image_ensure_section (MonoImage *image, const char *section)
198 MonoCLIImageInfo *ii = image->image_info;
201 for (i = 0; i < ii->cli_section_count; i++){
202 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
205 return mono_image_ensure_section_idx (image, i);
211 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
213 const int top = iinfo->cli_header.coff.coff_sections;
216 iinfo->cli_section_count = top;
217 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
218 iinfo->cli_sections = g_new0 (void *, top);
220 for (i = 0; i < top; i++){
221 MonoSectionTable *t = &iinfo->cli_section_tables [i];
223 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
225 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
226 offset += sizeof (MonoSectionTable);
228 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
229 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
230 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
231 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
232 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
233 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
234 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
235 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
236 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
237 t->st_flags = GUINT32_FROM_LE (t->st_flags);
239 /* consistency checks here */
246 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
250 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
251 if (offset == INVALID_ADDRESS)
254 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
256 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
258 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
259 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
260 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
261 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
262 SWAP32 (iinfo->cli_cli_header.ch_size);
263 SWAP32 (iinfo->cli_cli_header.ch_flags);
264 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
265 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
266 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
267 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
268 SWAPPDE (iinfo->cli_cli_header.ch_resources);
269 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
270 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
271 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
272 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
273 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
274 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
275 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
276 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
277 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
278 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
279 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
280 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
281 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
286 /* Catch new uses of the fields that are supposed to be zero */
288 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
289 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
290 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
291 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
292 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
293 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
294 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
295 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
296 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
299 * No need to scare people who are testing this, I am just
300 * labelling this as a LAMESPEC
302 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
310 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
312 guint32 offset, size;
318 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
319 if (offset == INVALID_ADDRESS)
322 size = iinfo->cli_cli_header.ch_metadata.size;
324 if (offset + size > image->raw_data_len)
326 image->raw_metadata = image->raw_data + offset;
328 ptr = image->raw_metadata;
330 if (strncmp (ptr, "BSJB", 4) == 0){
331 guint32 version_string_len;
334 image->md_version_major = read16 (ptr);
336 image->md_version_minor = read16 (ptr);
339 version_string_len = read32 (ptr);
341 image->version = g_strndup (ptr, version_string_len);
342 ptr += version_string_len;
343 pad = ptr - image->raw_metadata;
345 ptr += 4 - (pad % 4);
349 /* skip over flags */
352 streams = read16 (ptr);
355 for (i = 0; i < streams; i++){
356 if (strncmp (ptr + 8, "#~", 3) == 0){
357 image->heap_tables.data = image->raw_metadata + read32 (ptr);
358 image->heap_tables.size = read32 (ptr + 4);
360 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
361 image->heap_strings.data = image->raw_metadata + read32 (ptr);
362 image->heap_strings.size = read32 (ptr + 4);
364 } else if (strncmp (ptr + 8, "#US", 4) == 0){
365 image->heap_us.data = image->raw_metadata + read32 (ptr);
366 image->heap_us.size = read32 (ptr + 4);
368 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
369 image->heap_blob.data = image->raw_metadata + read32 (ptr);
370 image->heap_blob.size = read32 (ptr + 4);
372 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
373 image->heap_guid.data = image->raw_metadata + read32 (ptr);
374 image->heap_guid.size = read32 (ptr + 4);
376 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
377 image->heap_tables.data = image->raw_metadata + read32 (ptr);
378 image->heap_tables.size = read32 (ptr + 4);
380 image->uncompressed_metadata = TRUE;
381 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);
383 g_message ("Unknown heap type: %s\n", ptr + 8);
384 ptr += 8 + strlen (ptr + 8) + 1;
386 pad = ptr - image->raw_metadata;
388 ptr += 4 - (pad % 4);
391 g_assert (image->heap_guid.data);
392 g_assert (image->heap_guid.size >= 16);
394 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
400 * Load representation of logical metadata tables, from the "#~" stream
403 load_tables (MonoImage *image)
405 const char *heap_tables = image->heap_tables.data;
407 guint64 valid_mask, sorted_mask;
408 int valid = 0, table;
411 heap_sizes = heap_tables [6];
412 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
413 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
414 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
416 valid_mask = read64 (heap_tables + 8);
417 sorted_mask = read64 (heap_tables + 16);
418 rows = (const guint32 *) (heap_tables + 24);
420 for (table = 0; table < 64; table++){
421 if ((valid_mask & ((guint64) 1 << table)) == 0){
422 if (table > MONO_TABLE_LAST)
424 image->tables [table].rows = 0;
427 if (table > MONO_TABLE_LAST) {
428 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
430 image->tables [table].rows = read32 (rows);
432 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
433 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
439 image->tables_base = (heap_tables + 24) + (4 * valid);
441 /* They must be the same */
442 g_assert ((const void *) image->tables_base == (const void *) rows);
444 mono_metadata_compute_table_bases (image);
449 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
451 if (!load_metadata_ptrs (image, iinfo))
454 return load_tables (image);
458 mono_image_check_for_module_cctor (MonoImage *image)
460 MonoTableInfo *t, *mt;
461 t = &image->tables [MONO_TABLE_TYPEDEF];
462 mt = &image->tables [MONO_TABLE_METHOD];
463 if (mono_framework_version () == 1) {
464 image->checked_module_cctor = TRUE;
467 if (image->dynamic) {
469 image->checked_module_cctor = TRUE;
473 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
474 const char *name = mono_metadata_string_heap (image, nameidx);
475 if (strcmp (name, "<Module>") == 0) {
476 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
479 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
481 last_method = mt->rows;
482 for (; first_method < last_method; first_method++) {
483 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
484 name = mono_metadata_string_heap (image, nameidx);
485 if (strcmp (name, ".cctor") == 0) {
486 image->has_module_cctor = TRUE;
487 image->checked_module_cctor = TRUE;
493 image->has_module_cctor = FALSE;
494 image->checked_module_cctor = TRUE;
498 load_modules (MonoImage *image)
505 t = &image->tables [MONO_TABLE_MODULEREF];
506 image->modules = g_new0 (MonoImage *, t->rows);
507 image->modules_loaded = g_new0 (gboolean, t->rows);
508 image->module_count = t->rows;
512 * mono_image_load_module:
514 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
515 * it cannot be loaded.
518 mono_image_load_module (MonoImage *image, int idx)
521 MonoTableInfo *file_table;
524 gboolean refonly = image->ref_only;
525 GList *list_iter, *valid_modules = NULL;
526 MonoImageOpenStatus status;
528 g_assert (idx <= image->module_count);
529 if (image->modules_loaded [idx - 1])
530 return image->modules [idx - 1];
532 file_table = &image->tables [MONO_TABLE_FILE];
533 for (i = 0; i < file_table->rows; i++) {
534 guint32 cols [MONO_FILE_SIZE];
535 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
536 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
538 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
541 t = &image->tables [MONO_TABLE_MODULEREF];
542 base_dir = g_path_get_dirname (image->name);
547 guint32 cols [MONO_MODULEREF_SIZE];
548 /* if there is no file table, we try to load the module... */
549 int valid = file_table->rows == 0;
551 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
552 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
553 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
554 /* be safe with string dups, but we could just compare string indexes */
555 if (strcmp (list_iter->data, name) == 0) {
561 module_ref = g_build_filename (base_dir, name, NULL);
562 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
563 if (image->modules [idx - 1]) {
564 mono_image_addref (image->modules [idx - 1]);
565 image->modules [idx - 1]->assembly = image->assembly;
566 #ifdef PLATFORM_WIN32
567 if (image->modules [idx - 1]->is_module_handle)
568 mono_image_fixup_vtable (image->modules [idx - 1]);
570 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
576 image->modules_loaded [idx - 1] = TRUE;
579 g_list_free (valid_modules);
581 return image->modules [idx - 1];
585 class_key_extract (gpointer value)
587 MonoClass *class = value;
589 return GUINT_TO_POINTER (class->type_token);
593 class_next_value (gpointer value)
595 MonoClass *class = value;
597 return (gpointer*)&class->next_class_cache;
601 mono_image_init (MonoImage *image)
603 image->mempool = mono_mempool_new_size (512);
604 mono_internal_hash_table_init (&image->class_cache,
608 image->field_cache = g_hash_table_new (NULL, NULL);
610 image->native_wrapper_cache = g_hash_table_new (mono_aligned_addr_hash, 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 ();
620 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
621 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
622 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
623 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
624 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
633 * Returns < 0 to indicate an error.
636 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
638 MonoDotNetHeader64 header64;
640 #ifdef PLATFORM_WIN32
641 if (!image->is_module_handle)
643 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
646 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
648 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
651 /* endian swap the fields common between PE and PE+ */
652 SWAP32 (header->coff.coff_time);
653 SWAP32 (header->coff.coff_symptr);
654 SWAP32 (header->coff.coff_symcount);
655 SWAP16 (header->coff.coff_machine);
656 SWAP16 (header->coff.coff_sections);
657 SWAP16 (header->coff.coff_opt_header_size);
658 SWAP16 (header->coff.coff_attributes);
660 SWAP32 (header->pe.pe_code_size);
661 SWAP32 (header->pe.pe_uninit_data_size);
662 SWAP32 (header->pe.pe_rva_entry_point);
663 SWAP32 (header->pe.pe_rva_code_base);
664 SWAP32 (header->pe.pe_rva_data_base);
665 SWAP16 (header->pe.pe_magic);
667 /* now we are ready for the basic tests */
669 if (header->pe.pe_magic == 0x10B) {
670 offset += sizeof (MonoDotNetHeader);
671 SWAP32 (header->pe.pe_data_size);
672 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
675 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
676 SWAP32 (header->nt.pe_stack_reserve);
677 SWAP32 (header->nt.pe_stack_commit);
678 SWAP32 (header->nt.pe_heap_reserve);
679 SWAP32 (header->nt.pe_heap_commit);
680 } else if (header->pe.pe_magic == 0x20B) {
681 /* PE32+ file format */
682 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
684 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
685 offset += sizeof (MonoDotNetHeader64);
686 /* copy the fields already swapped. the last field, pe_data_size, is missing */
687 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
688 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
689 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
691 SWAP64 (header64.nt.pe_image_base);
692 header->nt.pe_image_base = header64.nt.pe_image_base;
693 SWAP64 (header64.nt.pe_stack_reserve);
694 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
695 SWAP64 (header64.nt.pe_stack_commit);
696 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
697 SWAP64 (header64.nt.pe_heap_reserve);
698 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
699 SWAP64 (header64.nt.pe_heap_commit);
700 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
702 header->nt.pe_section_align = header64.nt.pe_section_align;
703 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
704 header->nt.pe_os_major = header64.nt.pe_os_major;
705 header->nt.pe_os_minor = header64.nt.pe_os_minor;
706 header->nt.pe_user_major = header64.nt.pe_user_major;
707 header->nt.pe_user_minor = header64.nt.pe_user_minor;
708 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
709 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
710 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
711 header->nt.pe_image_size = header64.nt.pe_image_size;
712 header->nt.pe_header_size = header64.nt.pe_header_size;
713 header->nt.pe_checksum = header64.nt.pe_checksum;
714 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
715 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
716 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
717 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
719 /* copy the datadir */
720 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
725 /* MonoPEHeaderNT: not used yet */
726 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
727 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
728 SWAP16 (header->nt.pe_os_major); /* must be 4 */
729 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
730 SWAP16 (header->nt.pe_user_major);
731 SWAP16 (header->nt.pe_user_minor);
732 SWAP16 (header->nt.pe_subsys_major);
733 SWAP16 (header->nt.pe_subsys_minor);
734 SWAP32 (header->nt.pe_reserved_1);
735 SWAP32 (header->nt.pe_image_size);
736 SWAP32 (header->nt.pe_header_size);
737 SWAP32 (header->nt.pe_checksum);
738 SWAP16 (header->nt.pe_subsys_required);
739 SWAP16 (header->nt.pe_dll_flags);
740 SWAP32 (header->nt.pe_loader_flags);
741 SWAP32 (header->nt.pe_data_dir_count);
743 /* MonoDotNetHeader: mostly unused */
744 SWAPPDE (header->datadir.pe_export_table);
745 SWAPPDE (header->datadir.pe_import_table);
746 SWAPPDE (header->datadir.pe_resource_table);
747 SWAPPDE (header->datadir.pe_exception_table);
748 SWAPPDE (header->datadir.pe_certificate_table);
749 SWAPPDE (header->datadir.pe_reloc_table);
750 SWAPPDE (header->datadir.pe_debug);
751 SWAPPDE (header->datadir.pe_copyright);
752 SWAPPDE (header->datadir.pe_global_ptr);
753 SWAPPDE (header->datadir.pe_tls_table);
754 SWAPPDE (header->datadir.pe_load_config_table);
755 SWAPPDE (header->datadir.pe_bound_import);
756 SWAPPDE (header->datadir.pe_iat);
757 SWAPPDE (header->datadir.pe_delay_import_desc);
758 SWAPPDE (header->datadir.pe_cli_header);
759 SWAPPDE (header->datadir.pe_reserved);
761 #ifdef PLATFORM_WIN32
762 if (image->is_module_handle)
763 image->raw_data_len = header->nt.pe_image_size;
770 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
771 gboolean care_about_cli)
773 MonoCLIImageInfo *iinfo;
774 MonoDotNetHeader *header;
775 MonoMSDOSHeader msdos;
778 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
780 mono_image_init (image);
782 iinfo = image->image_info;
783 header = &iinfo->cli_header;
786 *status = MONO_IMAGE_IMAGE_INVALID;
788 #ifdef PLATFORM_WIN32
789 if (!image->is_module_handle)
791 if (offset + sizeof (msdos) > image->raw_data_len)
793 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
795 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
798 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
800 offset = msdos.pe_offset;
802 offset = do_load_header (image, header, offset);
807 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
809 if (header->coff.coff_machine != 0x14c)
815 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
816 * which produces binaries with 7.0. From Sergey:
818 * The reason is that MSVC7 uses traditional compile/link
819 * sequence for CIL executables, and VS.NET (and Framework
820 * SDK) includes linker version 7, that puts 7.0 in this
821 * field. That's why it's currently not possible to load VC
822 * binaries with Mono. This field is pretty much meaningless
823 * anyway (what linker?).
825 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
830 * FIXME: byte swap all addresses here for header.
833 if (!load_section_tables (image, iinfo, offset))
836 if (care_about_cli == FALSE) {
840 /* Load the CLI header */
841 if (!load_cli_header (image, iinfo))
844 if (!load_metadata (image, iinfo))
847 /* modules don't have an assembly table row */
848 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
849 image->assembly_name = mono_metadata_string_heap (image,
850 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
851 0, MONO_ASSEMBLY_NAME));
854 image->module_name = mono_metadata_string_heap (image,
855 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
856 0, MONO_MODULE_NAME));
858 load_modules (image);
861 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
863 *status = MONO_IMAGE_OK;
868 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
869 mono_image_close (image);
874 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
875 gboolean care_about_cli, gboolean refonly)
877 MonoCLIImageInfo *iinfo;
880 struct stat stat_buf;
882 if ((filed = fopen (fname, "rb")) == NULL){
883 if (IS_PORTABILITY_SET) {
884 gchar *ffname = mono_portability_find_file (fname, TRUE);
886 filed = fopen (ffname, "rb");
893 *status = MONO_IMAGE_ERROR_ERRNO;
898 if (fstat (fileno (filed), &stat_buf)) {
901 *status = MONO_IMAGE_ERROR_ERRNO;
904 image = g_new0 (MonoImage, 1);
905 image->raw_buffer_used = TRUE;
906 image->raw_data_len = stat_buf.st_size;
907 image->raw_data = mono_file_map (stat_buf.st_size, MONO_MMAP_READ|MONO_MMAP_PRIVATE, fileno (filed), 0, &image->raw_data_handle);
908 if (!image->raw_data) {
912 *status = MONO_IMAGE_IMAGE_INVALID;
915 iinfo = g_new0 (MonoCLIImageInfo, 1);
916 image->image_info = iinfo;
917 image->name = mono_path_resolve_symlinks (fname);
918 image->ref_only = refonly;
919 image->ref_count = 1;
923 return do_mono_image_load (image, status, care_about_cli);
927 mono_image_loaded_full (const char *name, gboolean refonly)
930 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
933 res = g_hash_table_lookup (loaded_images, name);
934 mono_images_unlock ();
940 * @name: name of the image to load
942 * This routine ensures that the given image is loaded.
944 * Returns: the loaded MonoImage, or NULL on failure.
947 mono_image_loaded (const char *name)
949 return mono_image_loaded_full (name, FALSE);
958 find_by_guid (gpointer key, gpointer val, gpointer user_data)
960 GuidData *data = user_data;
966 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
971 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
974 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
979 g_hash_table_foreach (loaded_images, find_by_guid, &data);
980 mono_images_unlock ();
985 mono_image_loaded_by_guid (const char *guid)
987 return mono_image_loaded_by_guid_full (guid, FALSE);
991 register_image (MonoImage *image)
994 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
997 image2 = g_hash_table_lookup (loaded_images, image->name);
1000 /* Somebody else beat us to it */
1001 mono_image_addref (image2);
1002 mono_images_unlock ();
1003 mono_image_close (image);
1006 g_hash_table_insert (loaded_images, image->name, image);
1007 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1008 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1009 mono_images_unlock ();
1015 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1017 MonoCLIImageInfo *iinfo;
1021 if (!data || !data_len) {
1023 *status = MONO_IMAGE_IMAGE_INVALID;
1028 datac = g_try_malloc (data_len);
1031 *status = MONO_IMAGE_ERROR_ERRNO;
1034 memcpy (datac, data, data_len);
1037 image = g_new0 (MonoImage, 1);
1038 image->raw_data = datac;
1039 image->raw_data_len = data_len;
1040 image->raw_data_allocated = need_copy;
1041 image->name = g_strdup_printf ("data-%p", datac);
1042 iinfo = g_new0 (MonoCLIImageInfo, 1);
1043 image->image_info = iinfo;
1044 image->ref_only = refonly;
1046 image = do_mono_image_load (image, status, TRUE);
1050 return register_image (image);
1054 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1056 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1059 #ifdef PLATFORM_WIN32
1060 /* fname is not duplicated. */
1062 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1065 MonoCLIImageInfo* iinfo;
1067 image = g_new0 (MonoImage, 1);
1068 image->raw_data = (char*) module_handle;
1069 image->is_module_handle = TRUE;
1070 iinfo = g_new0 (MonoCLIImageInfo, 1);
1071 image->image_info = iinfo;
1072 image->name = fname;
1073 image->ref_count = has_entry_point ? 0 : 1;
1074 image->has_entry_point = has_entry_point;
1076 image = do_mono_image_load (image, status, TRUE);
1080 return register_image (image);
1085 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1088 GHashTable *loaded_images;
1091 g_return_val_if_fail (fname != NULL, NULL);
1093 #ifdef PLATFORM_WIN32
1094 /* Load modules using LoadLibrary. */
1095 if (!refonly && coree_module_handle) {
1096 HMODULE module_handle;
1097 guint16 *fname_utf16;
1100 absfname = mono_path_resolve_symlinks (fname);
1103 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1104 mono_images_lock ();
1105 image = g_hash_table_lookup (loaded_images_hash, absfname);
1107 g_assert (image->is_module_handle);
1108 if (image->has_entry_point && image->ref_count == 0) {
1109 /* Increment reference count on images loaded outside of the runtime. */
1110 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1111 /* The image is already loaded because _CorDllMain removes images from the hash. */
1112 module_handle = LoadLibrary (fname_utf16);
1113 g_assert (module_handle == (HMODULE) image->raw_data);
1115 mono_image_addref (image);
1116 mono_images_unlock ();
1118 g_free (fname_utf16);
1123 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1124 module_handle = MonoLoadImage (fname_utf16);
1125 if (status && module_handle == NULL)
1126 last_error = GetLastError ();
1128 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1129 image = g_hash_table_lookup (loaded_images_hash, absfname);
1131 mono_image_addref (image);
1132 mono_images_unlock ();
1134 g_free (fname_utf16);
1136 if (module_handle == NULL) {
1140 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1141 *status = MONO_IMAGE_IMAGE_INVALID;
1143 *status = MONO_IMAGE_ERROR_ERRNO;
1149 g_assert (image->is_module_handle);
1150 g_assert (image->has_entry_point);
1155 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1159 absfname = mono_path_canonicalize (fname);
1162 * The easiest solution would be to do all the loading inside the mutex,
1163 * but that would lead to scalability problems. So we let the loading
1164 * happen outside the mutex, and if multiple threads happen to load
1165 * the same image, we discard all but the first copy.
1167 mono_images_lock ();
1168 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1169 image = g_hash_table_lookup (loaded_images, absfname);
1173 mono_image_addref (image);
1174 mono_images_unlock ();
1177 mono_images_unlock ();
1179 image = do_mono_image_open (fname, status, TRUE, refonly);
1183 return register_image (image);
1188 * @fname: filename that points to the module we want to open
1189 * @status: An error condition is returned in this field
1191 * Returns: An open image of type %MonoImage or NULL on error.
1192 * The caller holds a temporary reference to the returned image which should be cleared
1193 * when no longer needed by calling mono_image_close ().
1194 * if NULL, then check the value of @status for details on the error
1197 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1199 return mono_image_open_full (fname, status, FALSE);
1203 * mono_pe_file_open:
1204 * @fname: filename that points to the module we want to open
1205 * @status: An error condition is returned in this field
1207 * Returns: An open image of type %MonoImage or NULL on error. if
1208 * NULL, then check the value of @status for details on the error.
1209 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1210 * It's just a PE file loader, used for FileVersionInfo. It also does
1211 * not use the image cache.
1214 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1216 g_return_val_if_fail (fname != NULL, NULL);
1218 return(do_mono_image_open (fname, status, FALSE, FALSE));
1222 mono_image_fixup_vtable (MonoImage *image)
1224 #ifdef PLATFORM_WIN32
1225 MonoCLIImageInfo *iinfo;
1227 MonoVTableFixup *vtfixup;
1233 g_assert (image->is_module_handle);
1235 iinfo = image->image_info;
1236 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1237 if (!de->rva || !de->size)
1239 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1243 count = de->size / sizeof (MonoVTableFixup);
1245 if (!vtfixup->rva || !vtfixup->count)
1248 slot = mono_image_rva_map (image, vtfixup->rva);
1250 slot_type = vtfixup->type;
1251 slot_count = vtfixup->count;
1252 if (slot_type & VTFIXUP_TYPE_32BIT)
1253 while (slot_count--) {
1254 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1255 ((guint32*) slot)++;
1257 else if (slot_type & VTFIXUP_TYPE_64BIT)
1258 while (slot_count--) {
1259 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1260 ((guint64*) slot)++;
1263 g_assert_not_reached();
1268 g_assert_not_reached();
1273 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1275 g_hash_table_destroy ((GHashTable*)val);
1280 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1282 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1287 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1293 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1295 g_slist_free ((GSList*)val);
1299 * mono_image_addref:
1300 * @image: The image file we wish to add a reference to
1302 * Increases the reference count of an image.
1305 mono_image_addref (MonoImage *image)
1307 InterlockedIncrement (&image->ref_count);
1311 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1313 stream->alloc_size = stream->index = stream->offset = 0;
1314 g_free (stream->data);
1315 stream->data = NULL;
1317 g_hash_table_destroy (stream->hash);
1318 stream->hash = NULL;
1323 free_hash (GHashTable *hash)
1326 g_hash_table_destroy (hash);
1331 * @image: The image file we wish to close
1333 * Closes an image file, deallocates all memory consumed and
1334 * unmaps all possible sections of the file
1337 mono_image_close (MonoImage *image)
1340 GHashTable *loaded_images;
1343 g_return_if_fail (image != NULL);
1345 if (InterlockedDecrement (&image->ref_count) > 0)
1348 #ifdef PLATFORM_WIN32
1349 if (image->is_module_handle && image->has_entry_point) {
1350 mono_images_lock ();
1351 if (image->ref_count == 0) {
1352 /* Image will be closed by _CorDllMain. */
1353 FreeLibrary ((HMODULE) image->raw_data);
1354 mono_images_unlock ();
1357 mono_images_unlock ();
1361 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1363 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1365 mono_metadata_clean_for_image (image);
1368 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1369 * assemblies, so we can't release these references in mono_assembly_close () since the
1370 * MonoImage might outlive its associated MonoAssembly.
1372 if (image->references) {
1375 for (i = 0; image->references [i]; i++) {
1376 if (image->references [i])
1377 mono_assembly_close (image->references [i]);
1380 g_free (image->references);
1381 image->references = NULL;
1384 mono_images_lock ();
1385 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1386 image2 = g_hash_table_lookup (loaded_images, image->name);
1387 if (image == image2) {
1388 /* This is not true if we are called from mono_image_open () */
1389 g_hash_table_remove (loaded_images, image->name);
1391 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1392 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1394 #ifdef PLATFORM_WIN32
1395 if (image->is_module_handle && !image->has_entry_point)
1396 FreeLibrary ((HMODULE) image->raw_data);
1399 mono_images_unlock ();
1401 if (image->raw_buffer_used) {
1402 if (image->raw_data != NULL)
1403 mono_file_unmap (image->raw_data, image->raw_data_handle);
1406 if (image->raw_data_allocated) {
1407 /* FIXME: do we need this? (image is disposed anyway) */
1408 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1409 MonoCLIImageInfo *ii = image->image_info;
1411 if ((image->raw_metadata > image->raw_data) &&
1412 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1413 image->raw_metadata = NULL;
1415 for (i = 0; i < ii->cli_section_count; i++)
1416 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1417 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1418 ii->cli_sections [i] = NULL;
1420 g_free (image->raw_data);
1423 if (debug_assembly_unload) {
1424 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1426 g_free (image->name);
1427 g_free (image->guid);
1428 g_free (image->version);
1429 g_free (image->files);
1432 if (image->method_cache)
1433 mono_value_hash_table_destroy (image->method_cache);
1434 if (image->methodref_cache)
1435 g_hash_table_destroy (image->methodref_cache);
1436 mono_internal_hash_table_destroy (&image->class_cache);
1437 g_hash_table_destroy (image->field_cache);
1438 if (image->array_cache) {
1439 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1440 g_hash_table_destroy (image->array_cache);
1442 if (image->ptr_cache)
1443 g_hash_table_destroy (image->ptr_cache);
1444 if (image->name_cache) {
1445 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1446 g_hash_table_destroy (image->name_cache);
1449 free_hash (image->native_wrapper_cache);
1450 free_hash (image->managed_wrapper_cache);
1451 free_hash (image->delegate_begin_invoke_cache);
1452 free_hash (image->delegate_end_invoke_cache);
1453 free_hash (image->delegate_invoke_cache);
1454 free_hash (image->delegate_abstract_invoke_cache);
1455 if (image->remoting_invoke_cache)
1456 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1457 free_hash (image->remoting_invoke_cache);
1458 free_hash (image->runtime_invoke_cache);
1459 free_hash (image->runtime_invoke_direct_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);
1515 /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
1516 if (!image->dynamic) {
1517 if (debug_assembly_unload)
1518 mono_mempool_invalidate (image->mempool);
1520 mono_mempool_destroy (image->mempool);
1524 /* Dynamic images are GC_MALLOCed */
1525 g_free ((char*)image->module_name);
1526 mono_dynamic_image_free ((MonoDynamicImage*)image);
1527 mono_mempool_destroy (image->mempool);
1530 mono_profiler_module_event (image, MONO_PROFILE_END_UNLOAD);
1534 * mono_image_strerror:
1535 * @status: an code indicating the result from a recent operation
1537 * Returns: a string describing the error
1540 mono_image_strerror (MonoImageOpenStatus status)
1545 case MONO_IMAGE_ERROR_ERRNO:
1546 return strerror (errno);
1547 case MONO_IMAGE_IMAGE_INVALID:
1548 return "File does not contain a valid CIL image";
1549 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1550 return "An assembly was referenced, but could not be found";
1552 return "Internal error";
1556 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1557 guint32 lang_id, gunichar2 *name,
1558 MonoPEResourceDirEntry *entry,
1559 MonoPEResourceDir *root, guint32 level)
1561 gboolean is_string, is_dir;
1562 guint32 name_offset, dir_offset;
1564 /* Level 0 holds a directory entry for each type of resource
1565 * (identified by ID or name).
1567 * Level 1 holds a directory entry for each named resource
1568 * item, and each "anonymous" item of a particular type of
1571 * Level 2 holds a directory entry for each language pointing to
1574 is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
1575 name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
1577 is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
1578 dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
1581 if((is_string==FALSE && name_offset!=res_id) ||
1582 (is_string==TRUE)) {
1585 } else if (level==1) {
1588 is_string==TRUE && name!=lookup (name_offset)) {
1592 } else if (level==2) {
1593 if ((is_string == FALSE &&
1594 name_offset != lang_id &&
1596 (is_string == TRUE)) {
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 info=image->image_info;
1670 header=&info->cli_header;
1675 datadir=&header->datadir;
1680 rsrc=&datadir->pe_resource_table;
1685 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1686 if(resource_dir==NULL) {
1690 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1691 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1693 for(i=0; i<entries; i++) {
1694 MonoPEResourceDirEntry *entry=&res_entries[i];
1697 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1698 name, entry, resource_dir,
1709 * mono_image_get_entry_point:
1710 * @image: the image where the entry point will be looked up.
1712 * Use this routine to determine the metadata token for method that
1713 * has been flagged as the entry point.
1715 * Returns: the token for the entry point method in the image
1718 mono_image_get_entry_point (MonoImage *image)
1720 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1724 * mono_image_get_resource:
1725 * @image: the image where the resource will be looked up.
1726 * @offset: The offset to add to the resource
1727 * @size: a pointer to an int where the size of the resource will be stored
1729 * This is a low-level routine that fetches a resource from the
1730 * metadata that starts at a given @offset. The @size parameter is
1731 * filled with the data field as encoded in the metadata.
1733 * Returns: the pointer to the resource whose offset is @offset.
1736 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1738 MonoCLIImageInfo *iinfo = image->image_info;
1739 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1742 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1745 data = mono_image_rva_map (image, ch->ch_resources.rva);
1750 *size = read32 (data);
1756 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1758 char *base_dir, *name;
1760 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1764 if (fileidx < 1 || fileidx > t->rows)
1767 mono_loader_lock ();
1768 if (image->files && image->files [fileidx - 1]) {
1769 mono_loader_unlock ();
1770 return image->files [fileidx - 1];
1774 image->files = g_new0 (MonoImage*, t->rows);
1776 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1777 fname = mono_metadata_string_heap (image, fname_id);
1778 base_dir = g_path_get_dirname (image->name);
1779 name = g_build_filename (base_dir, fname, NULL);
1780 res = mono_image_open (name, NULL);
1783 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1784 res->assembly = image->assembly;
1785 for (i = 0; i < res->module_count; ++i) {
1786 if (res->modules [i] && !res->modules [i]->assembly)
1787 res->modules [i]->assembly = image->assembly;
1790 image->files [fileidx - 1] = res;
1791 #ifdef PLATFORM_WIN32
1792 if (res->is_module_handle)
1793 mono_image_fixup_vtable (res);
1796 mono_loader_unlock ();
1803 * mono_image_get_strong_name:
1804 * @image: a MonoImage
1805 * @size: a guint32 pointer, or NULL.
1807 * If the image has a strong name, and @size is not NULL, the value
1808 * pointed to by size will have the size of the strong name.
1810 * Returns: NULL if the image does not have a strong name, or a
1811 * pointer to the public key.
1814 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1816 MonoCLIImageInfo *iinfo = image->image_info;
1817 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1820 if (!de->size || !de->rva)
1822 data = mono_image_rva_map (image, de->rva);
1831 * mono_image_strong_name_position:
1832 * @image: a MonoImage
1833 * @size: a guint32 pointer, or NULL.
1835 * If the image has a strong name, and @size is not NULL, the value
1836 * pointed to by size will have the size of the strong name.
1838 * Returns: the position within the image file where the strong name
1842 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1844 MonoCLIImageInfo *iinfo = image->image_info;
1845 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1850 if (!de->size || !de->rva)
1852 pos = mono_cli_rva_image_map (image, de->rva);
1853 return pos == INVALID_ADDRESS ? 0 : pos;
1857 * mono_image_get_public_key:
1858 * @image: a MonoImage
1859 * @size: a guint32 pointer, or NULL.
1861 * This is used to obtain the public key in the @image.
1863 * If the image has a public key, and @size is not NULL, the value
1864 * pointed to by size will have the size of the public key.
1866 * Returns: NULL if the image does not have a public key, or a pointer
1867 * to the public key.
1870 mono_image_get_public_key (MonoImage *image, guint32 *size)
1875 if (image->dynamic) {
1877 *size = ((MonoDynamicImage*)image)->public_key_len;
1878 return (char*)((MonoDynamicImage*)image)->public_key;
1880 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1882 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1885 pubkey = mono_metadata_blob_heap (image, tok);
1886 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1893 * mono_image_get_name:
1894 * @name: a MonoImage
1896 * Returns: the name of the assembly.
1899 mono_image_get_name (MonoImage *image)
1901 return image->assembly_name;
1905 * mono_image_get_filename:
1906 * @image: a MonoImage
1908 * Used to get the filename that hold the actual MonoImage
1910 * Returns: the filename.
1913 mono_image_get_filename (MonoImage *image)
1919 mono_image_get_guid (MonoImage *image)
1924 const MonoTableInfo*
1925 mono_image_get_table_info (MonoImage *image, int table_id)
1927 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1929 return &image->tables [table_id];
1933 mono_image_get_table_rows (MonoImage *image, int table_id)
1935 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1937 return image->tables [table_id].rows;
1941 mono_table_info_get_rows (const MonoTableInfo *table)
1947 * mono_image_get_assembly:
1948 * @image: the MonoImage.
1950 * Use this routine to get the assembly that owns this image.
1952 * Returns: the assembly that holds this image.
1955 mono_image_get_assembly (MonoImage *image)
1957 return image->assembly;
1961 * mono_image_is_dynamic:
1962 * @image: the MonoImage
1964 * Determines if the given image was created dynamically through the
1965 * System.Reflection.Emit API
1967 * Returns: TRUE if the image was created dynamically, FALSE if not.
1970 mono_image_is_dynamic (MonoImage *image)
1972 return image->dynamic;
1976 * mono_image_has_authenticode_entry:
1977 * @image: the MonoImage
1979 * Use this routine to determine if the image has a Authenticode
1980 * Certificate Table.
1982 * Returns: TRUE if the image contains an authenticode entry in the PE
1986 mono_image_has_authenticode_entry (MonoImage *image)
1988 MonoCLIImageInfo *iinfo = image->image_info;
1989 MonoDotNetHeader *header = &iinfo->cli_header;
1990 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1991 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1992 return ((de->rva != 0) && (de->size > 8));
1996 mono_image_alloc (MonoImage *image, guint size)
1998 mono_perfcounters->loader_bytes += size;
1999 return mono_mempool_alloc (image->mempool, size);
2003 mono_image_alloc0 (MonoImage *image, guint size)
2005 mono_perfcounters->loader_bytes += size;
2006 return mono_mempool_alloc0 (image->mempool, size);
2010 mono_image_strdup (MonoImage *image, const char *s)
2012 mono_perfcounters->loader_bytes += strlen (s);
2013 return mono_mempool_strdup (image->mempool, s);