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 <sys/types.h>
43 #define INVALID_ADDRESS 0xffffffff
46 * Keeps track of the various assemblies loaded
48 static GHashTable *loaded_images_hash;
49 static GHashTable *loaded_images_refonly_hash;
51 static gboolean debug_assembly_unload = FALSE;
53 #define mono_images_lock() EnterCriticalSection (&images_mutex)
54 #define mono_images_unlock() LeaveCriticalSection (&images_mutex)
55 static CRITICAL_SECTION images_mutex;
57 /* returns offset relative to image->raw_data */
59 mono_cli_rva_image_map (MonoImage *image, guint32 addr)
61 MonoCLIImageInfo *iinfo = image->image_info;
62 const int top = iinfo->cli_section_count;
63 MonoSectionTable *tables = iinfo->cli_section_tables;
66 for (i = 0; i < top; i++){
67 if ((addr >= tables->st_virtual_address) &&
68 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
70 if (image->is_module_handle)
73 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
77 return INVALID_ADDRESS;
81 * mono_images_rva_map:
83 * @addr: relative virtual address (RVA)
85 * This is a low-level routine used by the runtime to map relative
86 * virtual address (RVA) into their location in memory.
88 * Returns: the address in memory for the given RVA, or NULL if the
89 * RVA is not valid for this image.
92 mono_image_rva_map (MonoImage *image, guint32 addr)
94 MonoCLIImageInfo *iinfo = image->image_info;
95 const int top = iinfo->cli_section_count;
96 MonoSectionTable *tables = iinfo->cli_section_tables;
99 for (i = 0; i < top; i++){
100 if ((addr >= tables->st_virtual_address) &&
101 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
102 if (!iinfo->cli_sections [i]) {
103 if (!mono_image_ensure_section_idx (image, i))
106 #ifdef PLATFORM_WIN32
107 if (image->is_module_handle)
108 return image->raw_data + addr;
110 return (char*)iinfo->cli_sections [i] +
111 (addr - tables->st_virtual_address);
121 * Initialize the global variables used by this module.
124 mono_images_init (void)
126 InitializeCriticalSection (&images_mutex);
128 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
129 loaded_images_refonly_hash = g_hash_table_new (g_str_hash, g_str_equal);
131 debug_assembly_unload = getenv ("MONO_DEBUG_ASSEMBLY_UNLOAD") != NULL;
135 * mono_images_cleanup:
137 * Free all resources used by this module.
140 mono_images_cleanup (void)
142 DeleteCriticalSection (&images_mutex);
144 g_hash_table_destroy (loaded_images_hash);
145 g_hash_table_destroy (loaded_images_refonly_hash);
149 * mono_image_ensure_section_idx:
150 * @image: The image we are operating on
151 * @section: section number that we will load/map into memory
153 * This routine makes sure that we have an in-memory copy of
154 * an image section (.text, .rsrc, .data).
156 * Returns: TRUE on success
159 mono_image_ensure_section_idx (MonoImage *image, int section)
161 MonoCLIImageInfo *iinfo = image->image_info;
162 MonoSectionTable *sect;
165 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
167 if (iinfo->cli_sections [section] != NULL)
170 sect = &iinfo->cli_section_tables [section];
172 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
174 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
176 #ifdef PLATFORM_WIN32
177 if (image->is_module_handle)
178 iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
181 /* FIXME: we ignore the writable flag since we don't patch the binary */
182 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
187 * mono_image_ensure_section:
188 * @image: The image we are operating on
189 * @section: section name that we will load/map into memory
191 * This routine makes sure that we have an in-memory copy of
192 * an image section (.text, .rsrc, .data).
194 * Returns: TRUE on success
197 mono_image_ensure_section (MonoImage *image, const char *section)
199 MonoCLIImageInfo *ii = image->image_info;
202 for (i = 0; i < ii->cli_section_count; i++){
203 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
206 return mono_image_ensure_section_idx (image, i);
212 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
214 const int top = iinfo->cli_header.coff.coff_sections;
217 iinfo->cli_section_count = top;
218 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
219 iinfo->cli_sections = g_new0 (void *, top);
221 for (i = 0; i < top; i++){
222 MonoSectionTable *t = &iinfo->cli_section_tables [i];
224 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
226 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
227 offset += sizeof (MonoSectionTable);
229 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
230 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
231 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
232 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
233 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
234 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
235 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
236 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
237 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
238 t->st_flags = GUINT32_FROM_LE (t->st_flags);
240 /* consistency checks here */
247 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
251 offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
252 if (offset == INVALID_ADDRESS)
255 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
257 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
259 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
260 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
261 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
262 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
263 SWAP32 (iinfo->cli_cli_header.ch_size);
264 SWAP32 (iinfo->cli_cli_header.ch_flags);
265 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
266 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
267 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
268 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
269 SWAPPDE (iinfo->cli_cli_header.ch_resources);
270 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
271 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
272 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
273 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
274 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
275 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
276 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
277 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
278 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
279 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
280 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
281 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
282 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
287 /* Catch new uses of the fields that are supposed to be zero */
289 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
290 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
291 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
292 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
293 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
294 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
295 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
296 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
297 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
300 * No need to scare people who are testing this, I am just
301 * labelling this as a LAMESPEC
303 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
311 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
313 guint32 offset, size;
319 offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
320 if (offset == INVALID_ADDRESS)
323 size = iinfo->cli_cli_header.ch_metadata.size;
325 if (offset + size > image->raw_data_len)
327 image->raw_metadata = image->raw_data + offset;
329 ptr = image->raw_metadata;
331 if (strncmp (ptr, "BSJB", 4) == 0){
332 guint32 version_string_len;
335 image->md_version_major = read16 (ptr);
337 image->md_version_minor = read16 (ptr);
340 version_string_len = read32 (ptr);
342 image->version = g_strndup (ptr, version_string_len);
343 ptr += version_string_len;
344 pad = ptr - image->raw_metadata;
346 ptr += 4 - (pad % 4);
350 /* skip over flags */
353 streams = read16 (ptr);
356 for (i = 0; i < streams; i++){
357 if (strncmp (ptr + 8, "#~", 3) == 0){
358 image->heap_tables.data = image->raw_metadata + read32 (ptr);
359 image->heap_tables.size = read32 (ptr + 4);
361 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
362 image->heap_strings.data = image->raw_metadata + read32 (ptr);
363 image->heap_strings.size = read32 (ptr + 4);
365 } else if (strncmp (ptr + 8, "#US", 4) == 0){
366 image->heap_us.data = image->raw_metadata + read32 (ptr);
367 image->heap_us.size = read32 (ptr + 4);
369 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
370 image->heap_blob.data = image->raw_metadata + read32 (ptr);
371 image->heap_blob.size = read32 (ptr + 4);
373 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
374 image->heap_guid.data = image->raw_metadata + read32 (ptr);
375 image->heap_guid.size = read32 (ptr + 4);
377 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
378 image->heap_tables.data = image->raw_metadata + read32 (ptr);
379 image->heap_tables.size = read32 (ptr + 4);
381 image->uncompressed_metadata = TRUE;
382 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);
384 g_message ("Unknown heap type: %s\n", ptr + 8);
385 ptr += 8 + strlen (ptr + 8) + 1;
387 pad = ptr - image->raw_metadata;
389 ptr += 4 - (pad % 4);
392 g_assert (image->heap_guid.data);
393 g_assert (image->heap_guid.size >= 16);
395 image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
401 * Load representation of logical metadata tables, from the "#~" stream
404 load_tables (MonoImage *image)
406 const char *heap_tables = image->heap_tables.data;
408 guint64 valid_mask, sorted_mask;
409 int valid = 0, table;
412 heap_sizes = heap_tables [6];
413 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
414 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
415 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
417 valid_mask = read64 (heap_tables + 8);
418 sorted_mask = read64 (heap_tables + 16);
419 rows = (const guint32 *) (heap_tables + 24);
421 for (table = 0; table < 64; table++){
422 if ((valid_mask & ((guint64) 1 << table)) == 0){
423 if (table > MONO_TABLE_LAST)
425 image->tables [table].rows = 0;
428 if (table > MONO_TABLE_LAST) {
429 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
431 image->tables [table].rows = read32 (rows);
433 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
434 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
440 image->tables_base = (heap_tables + 24) + (4 * valid);
442 /* They must be the same */
443 g_assert ((const void *) image->tables_base == (const void *) rows);
445 mono_metadata_compute_table_bases (image);
450 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
452 if (!load_metadata_ptrs (image, iinfo))
455 return load_tables (image);
459 mono_image_check_for_module_cctor (MonoImage *image)
461 MonoTableInfo *t, *mt;
462 t = &image->tables [MONO_TABLE_TYPEDEF];
463 mt = &image->tables [MONO_TABLE_METHOD];
464 if (mono_framework_version () == 1) {
465 image->checked_module_cctor = TRUE;
468 if (image->dynamic) {
470 image->checked_module_cctor = TRUE;
474 guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
475 const char *name = mono_metadata_string_heap (image, nameidx);
476 if (strcmp (name, "<Module>") == 0) {
477 guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
480 last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
482 last_method = mt->rows;
483 for (; first_method < last_method; first_method++) {
484 nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
485 name = mono_metadata_string_heap (image, nameidx);
486 if (strcmp (name, ".cctor") == 0) {
487 image->has_module_cctor = TRUE;
488 image->checked_module_cctor = TRUE;
494 image->has_module_cctor = FALSE;
495 image->checked_module_cctor = TRUE;
499 load_modules (MonoImage *image)
506 t = &image->tables [MONO_TABLE_MODULEREF];
507 image->modules = g_new0 (MonoImage *, t->rows);
508 image->modules_loaded = g_new0 (gboolean, t->rows);
509 image->module_count = t->rows;
513 * mono_image_load_module:
515 * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
516 * it cannot be loaded.
519 mono_image_load_module (MonoImage *image, int idx)
522 MonoTableInfo *file_table;
525 gboolean refonly = image->ref_only;
526 GList *list_iter, *valid_modules = NULL;
527 MonoImageOpenStatus status;
529 g_assert (idx <= image->module_count);
530 if (image->modules_loaded [idx - 1])
531 return image->modules [idx - 1];
533 file_table = &image->tables [MONO_TABLE_FILE];
534 for (i = 0; i < file_table->rows; i++) {
535 guint32 cols [MONO_FILE_SIZE];
536 mono_metadata_decode_row (file_table, i, cols, MONO_FILE_SIZE);
537 if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
539 valid_modules = g_list_prepend (valid_modules, (char*)mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
542 t = &image->tables [MONO_TABLE_MODULEREF];
543 base_dir = g_path_get_dirname (image->name);
548 guint32 cols [MONO_MODULEREF_SIZE];
549 /* if there is no file table, we try to load the module... */
550 int valid = file_table->rows == 0;
552 mono_metadata_decode_row (t, idx - 1, cols, MONO_MODULEREF_SIZE);
553 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
554 for (list_iter = valid_modules; list_iter; list_iter = list_iter->next) {
555 /* be safe with string dups, but we could just compare string indexes */
556 if (strcmp (list_iter->data, name) == 0) {
562 module_ref = g_build_filename (base_dir, name, NULL);
563 image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
564 if (image->modules [idx - 1]) {
565 mono_image_addref (image->modules [idx - 1]);
566 image->modules [idx - 1]->assembly = image->assembly;
567 #ifdef PLATFORM_WIN32
568 if (image->modules [idx - 1]->is_module_handle)
569 mono_image_fixup_vtable (image->modules [idx - 1]);
571 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
577 image->modules_loaded [idx - 1] = TRUE;
580 g_list_free (valid_modules);
582 return image->modules [idx - 1];
586 class_key_extract (gpointer value)
588 MonoClass *class = value;
590 return GUINT_TO_POINTER (class->type_token);
594 class_next_value (gpointer value)
596 MonoClass *class = value;
598 return (gpointer*)&class->next_class_cache;
602 mono_image_init (MonoImage *image)
604 image->mempool = mono_mempool_new_size (512);
605 mono_internal_hash_table_init (&image->class_cache,
609 image->field_cache = g_hash_table_new (NULL, NULL);
611 image->typespec_cache = g_hash_table_new (NULL, NULL);
612 image->memberref_signatures = g_hash_table_new (NULL, NULL);
613 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
614 image->method_signatures = g_hash_table_new (NULL, NULL);
616 image->property_hash = mono_property_hash_new ();
617 InitializeCriticalSection (&image->lock);
618 InitializeCriticalSection (&image->szarray_cache_lock);
621 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
622 #define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
623 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
624 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
625 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
634 * Returns < 0 to indicate an error.
637 do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
639 MonoDotNetHeader64 header64;
641 #ifdef PLATFORM_WIN32
642 if (!image->is_module_handle)
644 if (offset + sizeof (MonoDotNetHeader32) > image->raw_data_len)
647 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
649 if (header->pesig [0] != 'P' || header->pesig [1] != 'E')
652 /* endian swap the fields common between PE and PE+ */
653 SWAP32 (header->coff.coff_time);
654 SWAP32 (header->coff.coff_symptr);
655 SWAP32 (header->coff.coff_symcount);
656 SWAP16 (header->coff.coff_machine);
657 SWAP16 (header->coff.coff_sections);
658 SWAP16 (header->coff.coff_opt_header_size);
659 SWAP16 (header->coff.coff_attributes);
661 SWAP32 (header->pe.pe_code_size);
662 SWAP32 (header->pe.pe_uninit_data_size);
663 SWAP32 (header->pe.pe_rva_entry_point);
664 SWAP32 (header->pe.pe_rva_code_base);
665 SWAP32 (header->pe.pe_rva_data_base);
666 SWAP16 (header->pe.pe_magic);
668 /* now we are ready for the basic tests */
670 if (header->pe.pe_magic == 0x10B) {
671 offset += sizeof (MonoDotNetHeader);
672 SWAP32 (header->pe.pe_data_size);
673 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
676 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
677 SWAP32 (header->nt.pe_stack_reserve);
678 SWAP32 (header->nt.pe_stack_commit);
679 SWAP32 (header->nt.pe_heap_reserve);
680 SWAP32 (header->nt.pe_heap_commit);
681 } else if (header->pe.pe_magic == 0x20B) {
682 /* PE32+ file format */
683 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
685 memcpy (&header64, image->raw_data + offset, sizeof (MonoDotNetHeader64));
686 offset += sizeof (MonoDotNetHeader64);
687 /* copy the fields already swapped. the last field, pe_data_size, is missing */
688 memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
689 /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
690 * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
692 SWAP64 (header64.nt.pe_image_base);
693 header->nt.pe_image_base = header64.nt.pe_image_base;
694 SWAP64 (header64.nt.pe_stack_reserve);
695 header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
696 SWAP64 (header64.nt.pe_stack_commit);
697 header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
698 SWAP64 (header64.nt.pe_heap_reserve);
699 header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
700 SWAP64 (header64.nt.pe_heap_commit);
701 header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
703 header->nt.pe_section_align = header64.nt.pe_section_align;
704 header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
705 header->nt.pe_os_major = header64.nt.pe_os_major;
706 header->nt.pe_os_minor = header64.nt.pe_os_minor;
707 header->nt.pe_user_major = header64.nt.pe_user_major;
708 header->nt.pe_user_minor = header64.nt.pe_user_minor;
709 header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
710 header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
711 header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
712 header->nt.pe_image_size = header64.nt.pe_image_size;
713 header->nt.pe_header_size = header64.nt.pe_header_size;
714 header->nt.pe_checksum = header64.nt.pe_checksum;
715 header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
716 header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
717 header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
718 header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
720 /* copy the datadir */
721 memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
726 /* MonoPEHeaderNT: not used yet */
727 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
728 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
729 SWAP16 (header->nt.pe_os_major); /* must be 4 */
730 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
731 SWAP16 (header->nt.pe_user_major);
732 SWAP16 (header->nt.pe_user_minor);
733 SWAP16 (header->nt.pe_subsys_major);
734 SWAP16 (header->nt.pe_subsys_minor);
735 SWAP32 (header->nt.pe_reserved_1);
736 SWAP32 (header->nt.pe_image_size);
737 SWAP32 (header->nt.pe_header_size);
738 SWAP32 (header->nt.pe_checksum);
739 SWAP16 (header->nt.pe_subsys_required);
740 SWAP16 (header->nt.pe_dll_flags);
741 SWAP32 (header->nt.pe_loader_flags);
742 SWAP32 (header->nt.pe_data_dir_count);
744 /* MonoDotNetHeader: mostly unused */
745 SWAPPDE (header->datadir.pe_export_table);
746 SWAPPDE (header->datadir.pe_import_table);
747 SWAPPDE (header->datadir.pe_resource_table);
748 SWAPPDE (header->datadir.pe_exception_table);
749 SWAPPDE (header->datadir.pe_certificate_table);
750 SWAPPDE (header->datadir.pe_reloc_table);
751 SWAPPDE (header->datadir.pe_debug);
752 SWAPPDE (header->datadir.pe_copyright);
753 SWAPPDE (header->datadir.pe_global_ptr);
754 SWAPPDE (header->datadir.pe_tls_table);
755 SWAPPDE (header->datadir.pe_load_config_table);
756 SWAPPDE (header->datadir.pe_bound_import);
757 SWAPPDE (header->datadir.pe_iat);
758 SWAPPDE (header->datadir.pe_delay_import_desc);
759 SWAPPDE (header->datadir.pe_cli_header);
760 SWAPPDE (header->datadir.pe_reserved);
762 #ifdef PLATFORM_WIN32
763 if (image->is_module_handle)
764 image->raw_data_len = header->nt.pe_image_size;
771 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
772 gboolean care_about_cli)
774 MonoCLIImageInfo *iinfo;
775 MonoDotNetHeader *header;
776 MonoMSDOSHeader msdos;
779 mono_profiler_module_event (image, MONO_PROFILE_START_LOAD);
781 mono_image_init (image);
783 iinfo = image->image_info;
784 header = &iinfo->cli_header;
787 *status = MONO_IMAGE_IMAGE_INVALID;
789 #ifdef PLATFORM_WIN32
790 if (!image->is_module_handle)
792 if (offset + sizeof (msdos) > image->raw_data_len)
794 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
796 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
799 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
801 offset = msdos.pe_offset;
803 offset = do_load_header (image, header, offset);
808 * this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
810 if (header->coff.coff_machine != 0x14c)
816 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
817 * which produces binaries with 7.0. From Sergey:
819 * The reason is that MSVC7 uses traditional compile/link
820 * sequence for CIL executables, and VS.NET (and Framework
821 * SDK) includes linker version 7, that puts 7.0 in this
822 * field. That's why it's currently not possible to load VC
823 * binaries with Mono. This field is pretty much meaningless
824 * anyway (what linker?).
826 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
831 * FIXME: byte swap all addresses here for header.
834 if (!load_section_tables (image, iinfo, offset))
837 if (care_about_cli == FALSE) {
841 /* Load the CLI header */
842 if (!load_cli_header (image, iinfo))
845 if (!load_metadata (image, iinfo))
848 /* modules don't have an assembly table row */
849 if (image->tables [MONO_TABLE_ASSEMBLY].rows) {
850 image->assembly_name = mono_metadata_string_heap (image,
851 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
852 0, MONO_ASSEMBLY_NAME));
855 image->module_name = mono_metadata_string_heap (image,
856 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
857 0, MONO_MODULE_NAME));
859 load_modules (image);
862 mono_profiler_module_loaded (image, MONO_PROFILE_OK);
864 *status = MONO_IMAGE_OK;
869 mono_profiler_module_loaded (image, MONO_PROFILE_FAILED);
870 mono_image_close (image);
875 do_mono_image_open (const char *fname, MonoImageOpenStatus *status,
876 gboolean care_about_cli, gboolean refonly)
878 MonoCLIImageInfo *iinfo;
882 if ((filed = mono_file_map_open (fname)) == NULL){
883 if (IS_PORTABILITY_SET) {
884 gchar *ffname = mono_portability_find_file (fname, TRUE);
886 filed = mono_file_map_open (ffname);
893 *status = MONO_IMAGE_ERROR_ERRNO;
898 image = g_new0 (MonoImage, 1);
899 image->raw_buffer_used = TRUE;
900 image->raw_data_len = mono_file_map_size (filed);
901 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);
902 if (!image->raw_data) {
903 mono_file_map_close (filed);
906 *status = MONO_IMAGE_IMAGE_INVALID;
909 iinfo = g_new0 (MonoCLIImageInfo, 1);
910 image->image_info = iinfo;
911 image->name = mono_path_resolve_symlinks (fname);
912 image->ref_only = refonly;
913 image->ref_count = 1;
915 mono_file_map_close (filed);
916 return do_mono_image_load (image, status, care_about_cli);
920 mono_image_loaded_full (const char *name, gboolean refonly)
923 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
926 res = g_hash_table_lookup (loaded_images, name);
927 mono_images_unlock ();
933 * @name: name of the image to load
935 * This routine ensures that the given image is loaded.
937 * Returns: the loaded MonoImage, or NULL on failure.
940 mono_image_loaded (const char *name)
942 return mono_image_loaded_full (name, FALSE);
951 find_by_guid (gpointer key, gpointer val, gpointer user_data)
953 GuidData *data = user_data;
959 if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
964 mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
967 GHashTable *loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
972 g_hash_table_foreach (loaded_images, find_by_guid, &data);
973 mono_images_unlock ();
978 mono_image_loaded_by_guid (const char *guid)
980 return mono_image_loaded_by_guid_full (guid, FALSE);
984 register_image (MonoImage *image)
987 GHashTable *loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
990 image2 = g_hash_table_lookup (loaded_images, image->name);
993 /* Somebody else beat us to it */
994 mono_image_addref (image2);
995 mono_images_unlock ();
996 mono_image_close (image);
999 g_hash_table_insert (loaded_images, image->name, image);
1000 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == NULL))
1001 g_hash_table_insert (loaded_images, (char *) image->assembly_name, image);
1002 mono_images_unlock ();
1008 mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
1010 MonoCLIImageInfo *iinfo;
1014 if (!data || !data_len) {
1016 *status = MONO_IMAGE_IMAGE_INVALID;
1021 datac = g_try_malloc (data_len);
1024 *status = MONO_IMAGE_ERROR_ERRNO;
1027 memcpy (datac, data, data_len);
1030 image = g_new0 (MonoImage, 1);
1031 image->raw_data = datac;
1032 image->raw_data_len = data_len;
1033 image->raw_data_allocated = need_copy;
1034 image->name = g_strdup_printf ("data-%p", datac);
1035 iinfo = g_new0 (MonoCLIImageInfo, 1);
1036 image->image_info = iinfo;
1037 image->ref_only = refonly;
1039 image = do_mono_image_load (image, status, TRUE);
1043 return register_image (image);
1047 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
1049 return mono_image_open_from_data_full (data, data_len, need_copy, status, FALSE);
1052 #ifdef PLATFORM_WIN32
1053 /* fname is not duplicated. */
1055 mono_image_open_from_module_handle (HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
1058 MonoCLIImageInfo* iinfo;
1060 image = g_new0 (MonoImage, 1);
1061 image->raw_data = (char*) module_handle;
1062 image->is_module_handle = TRUE;
1063 iinfo = g_new0 (MonoCLIImageInfo, 1);
1064 image->image_info = iinfo;
1065 image->name = fname;
1066 image->ref_count = has_entry_point ? 0 : 1;
1067 image->has_entry_point = has_entry_point;
1069 image = do_mono_image_load (image, status, TRUE);
1073 return register_image (image);
1078 mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
1081 GHashTable *loaded_images;
1084 g_return_val_if_fail (fname != NULL, NULL);
1086 #ifdef PLATFORM_WIN32
1087 /* Load modules using LoadLibrary. */
1088 if (!refonly && coree_module_handle) {
1089 HMODULE module_handle;
1090 guint16 *fname_utf16;
1093 absfname = mono_path_resolve_symlinks (fname);
1096 /* There is little overhead because the OS loader lock is held by LoadLibrary. */
1097 mono_images_lock ();
1098 image = g_hash_table_lookup (loaded_images_hash, absfname);
1100 g_assert (image->is_module_handle);
1101 if (image->has_entry_point && image->ref_count == 0) {
1102 /* Increment reference count on images loaded outside of the runtime. */
1103 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1104 /* The image is already loaded because _CorDllMain removes images from the hash. */
1105 module_handle = LoadLibrary (fname_utf16);
1106 g_assert (module_handle == (HMODULE) image->raw_data);
1108 mono_image_addref (image);
1109 mono_images_unlock ();
1111 g_free (fname_utf16);
1116 fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
1117 module_handle = MonoLoadImage (fname_utf16);
1118 if (status && module_handle == NULL)
1119 last_error = GetLastError ();
1121 /* mono_image_open_from_module_handle is called by _CorDllMain. */
1122 image = g_hash_table_lookup (loaded_images_hash, absfname);
1124 mono_image_addref (image);
1125 mono_images_unlock ();
1127 g_free (fname_utf16);
1129 if (module_handle == NULL) {
1133 if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT)
1134 *status = MONO_IMAGE_IMAGE_INVALID;
1136 *status = MONO_IMAGE_ERROR_ERRNO;
1142 g_assert (image->is_module_handle);
1143 g_assert (image->has_entry_point);
1148 return mono_image_open_from_module_handle (module_handle, absfname, FALSE, status);
1152 absfname = mono_path_canonicalize (fname);
1155 * The easiest solution would be to do all the loading inside the mutex,
1156 * but that would lead to scalability problems. So we let the loading
1157 * happen outside the mutex, and if multiple threads happen to load
1158 * the same image, we discard all but the first copy.
1160 mono_images_lock ();
1161 loaded_images = refonly ? loaded_images_refonly_hash : loaded_images_hash;
1162 image = g_hash_table_lookup (loaded_images, absfname);
1166 mono_image_addref (image);
1167 mono_images_unlock ();
1170 mono_images_unlock ();
1172 image = do_mono_image_open (fname, status, TRUE, refonly);
1176 return register_image (image);
1181 * @fname: filename that points to the module we want to open
1182 * @status: An error condition is returned in this field
1184 * Returns: An open image of type %MonoImage or NULL on error.
1185 * The caller holds a temporary reference to the returned image which should be cleared
1186 * when no longer needed by calling mono_image_close ().
1187 * if NULL, then check the value of @status for details on the error
1190 mono_image_open (const char *fname, MonoImageOpenStatus *status)
1192 return mono_image_open_full (fname, status, FALSE);
1196 * mono_pe_file_open:
1197 * @fname: filename that points to the module we want to open
1198 * @status: An error condition is returned in this field
1200 * Returns: An open image of type %MonoImage or NULL on error. if
1201 * NULL, then check the value of @status for details on the error.
1202 * This variant for mono_image_open DOES NOT SET UP CLI METADATA.
1203 * It's just a PE file loader, used for FileVersionInfo. It also does
1204 * not use the image cache.
1207 mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
1209 g_return_val_if_fail (fname != NULL, NULL);
1211 return(do_mono_image_open (fname, status, FALSE, FALSE));
1215 mono_image_fixup_vtable (MonoImage *image)
1217 #ifdef PLATFORM_WIN32
1218 MonoCLIImageInfo *iinfo;
1220 MonoVTableFixup *vtfixup;
1226 g_assert (image->is_module_handle);
1228 iinfo = image->image_info;
1229 de = &iinfo->cli_cli_header.ch_vtable_fixups;
1230 if (!de->rva || !de->size)
1232 vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
1236 count = de->size / sizeof (MonoVTableFixup);
1238 if (!vtfixup->rva || !vtfixup->count)
1241 slot = mono_image_rva_map (image, vtfixup->rva);
1243 slot_type = vtfixup->type;
1244 slot_count = vtfixup->count;
1245 if (slot_type & VTFIXUP_TYPE_32BIT)
1246 while (slot_count--) {
1247 *((guint32*) slot) = (guint32) mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
1248 ((guint32*) slot)++;
1250 else if (slot_type & VTFIXUP_TYPE_64BIT)
1251 while (slot_count--) {
1252 *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
1253 ((guint64*) slot)++;
1256 g_assert_not_reached();
1261 g_assert_not_reached();
1266 free_hash_table (gpointer key, gpointer val, gpointer user_data)
1268 g_hash_table_destroy ((GHashTable*)val);
1273 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
1275 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
1280 free_remoting_wrappers (gpointer key, gpointer val, gpointer user_data)
1286 free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
1288 g_slist_free ((GSList*)val);
1292 * mono_image_addref:
1293 * @image: The image file we wish to add a reference to
1295 * Increases the reference count of an image.
1298 mono_image_addref (MonoImage *image)
1300 InterlockedIncrement (&image->ref_count);
1304 mono_dynamic_stream_reset (MonoDynamicStream* stream)
1306 stream->alloc_size = stream->index = stream->offset = 0;
1307 g_free (stream->data);
1308 stream->data = NULL;
1310 g_hash_table_destroy (stream->hash);
1311 stream->hash = NULL;
1316 free_hash (GHashTable *hash)
1319 g_hash_table_destroy (hash);
1324 * @image: The image file we wish to close
1326 * Closes an image file, deallocates all memory consumed and
1327 * unmaps all possible sections of the file
1330 mono_image_close (MonoImage *image)
1333 GHashTable *loaded_images;
1336 g_return_if_fail (image != NULL);
1338 if (InterlockedDecrement (&image->ref_count) > 0)
1341 #ifdef PLATFORM_WIN32
1342 if (image->is_module_handle && image->has_entry_point) {
1343 mono_images_lock ();
1344 if (image->ref_count == 0) {
1345 /* Image will be closed by _CorDllMain. */
1346 FreeLibrary ((HMODULE) image->raw_data);
1347 mono_images_unlock ();
1350 mono_images_unlock ();
1354 mono_profiler_module_event (image, MONO_PROFILE_START_UNLOAD);
1356 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
1358 mono_metadata_clean_for_image (image);
1361 * The caches inside a MonoImage might refer to metadata which is stored in referenced
1362 * assemblies, so we can't release these references in mono_assembly_close () since the
1363 * MonoImage might outlive its associated MonoAssembly.
1365 if (image->references && !image->dynamic) {
1366 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1369 for (i = 0; i < t->rows; i++) {
1370 if (image->references [i])
1371 mono_assembly_close (image->references [i]);
1374 g_free (image->references);
1375 image->references = NULL;
1378 mono_images_lock ();
1379 loaded_images = image->ref_only ? loaded_images_refonly_hash : loaded_images_hash;
1380 image2 = g_hash_table_lookup (loaded_images, image->name);
1381 if (image == image2) {
1382 /* This is not true if we are called from mono_image_open () */
1383 g_hash_table_remove (loaded_images, image->name);
1385 if (image->assembly_name && (g_hash_table_lookup (loaded_images, image->assembly_name) == image))
1386 g_hash_table_remove (loaded_images, (char *) image->assembly_name);
1388 #ifdef PLATFORM_WIN32
1389 if (image->is_module_handle && !image->has_entry_point)
1390 FreeLibrary ((HMODULE) image->raw_data);
1393 mono_images_unlock ();
1395 if (image->raw_buffer_used) {
1396 if (image->raw_data != NULL)
1397 mono_file_unmap (image->raw_data, image->raw_data_handle);
1400 if (image->raw_data_allocated) {
1401 /* FIXME: do we need this? (image is disposed anyway) */
1402 /* image->raw_metadata and cli_sections might lie inside image->raw_data */
1403 MonoCLIImageInfo *ii = image->image_info;
1405 if ((image->raw_metadata > image->raw_data) &&
1406 (image->raw_metadata <= (image->raw_data + image->raw_data_len)))
1407 image->raw_metadata = NULL;
1409 for (i = 0; i < ii->cli_section_count; i++)
1410 if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
1411 ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
1412 ii->cli_sections [i] = NULL;
1414 g_free (image->raw_data);
1417 if (debug_assembly_unload) {
1418 image->name = g_strdup_printf ("%s - UNLOADED", image->name);
1420 g_free (image->name);
1421 g_free (image->guid);
1422 g_free (image->version);
1423 g_free (image->files);
1426 if (image->method_cache)
1427 mono_value_hash_table_destroy (image->method_cache);
1428 if (image->methodref_cache)
1429 g_hash_table_destroy (image->methodref_cache);
1430 mono_internal_hash_table_destroy (&image->class_cache);
1431 g_hash_table_destroy (image->field_cache);
1432 if (image->array_cache) {
1433 g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
1434 g_hash_table_destroy (image->array_cache);
1436 if (image->szarray_cache)
1437 g_hash_table_destroy (image->szarray_cache);
1438 if (image->ptr_cache)
1439 g_hash_table_destroy (image->ptr_cache);
1440 if (image->name_cache) {
1441 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
1442 g_hash_table_destroy (image->name_cache);
1445 free_hash (image->native_wrapper_cache);
1446 free_hash (image->managed_wrapper_cache);
1447 free_hash (image->delegate_begin_invoke_cache);
1448 free_hash (image->delegate_end_invoke_cache);
1449 free_hash (image->delegate_invoke_cache);
1450 free_hash (image->delegate_abstract_invoke_cache);
1451 if (image->remoting_invoke_cache)
1452 g_hash_table_foreach (image->remoting_invoke_cache, free_remoting_wrappers, NULL);
1453 free_hash (image->remoting_invoke_cache);
1454 free_hash (image->runtime_invoke_cache);
1455 free_hash (image->runtime_invoke_direct_cache);
1456 free_hash (image->synchronized_cache);
1457 free_hash (image->unbox_wrapper_cache);
1458 free_hash (image->cominterop_invoke_cache);
1459 free_hash (image->cominterop_wrapper_cache);
1460 free_hash (image->typespec_cache);
1461 free_hash (image->ldfld_wrapper_cache);
1462 free_hash (image->ldflda_wrapper_cache);
1463 free_hash (image->stfld_wrapper_cache);
1464 free_hash (image->isinst_cache);
1465 free_hash (image->castclass_cache);
1466 free_hash (image->proxy_isinst_cache);
1467 free_hash (image->thunk_invoke_cache);
1468 free_hash (image->static_rgctx_invoke_cache);
1470 /* The ownership of signatures is not well defined */
1471 //g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
1472 g_hash_table_destroy (image->memberref_signatures);
1473 //g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
1474 g_hash_table_destroy (image->helper_signatures);
1475 g_hash_table_destroy (image->method_signatures);
1477 if (image->generic_class_cache)
1478 g_hash_table_destroy (image->generic_class_cache);
1480 if (image->rgctx_template_hash)
1481 g_hash_table_destroy (image->rgctx_template_hash);
1483 if (image->property_hash)
1484 mono_property_hash_destroy (image->property_hash);
1486 if (image->interface_bitset) {
1487 mono_unload_interface_ids (image->interface_bitset);
1488 mono_bitset_free (image->interface_bitset);
1490 if (image->image_info){
1491 MonoCLIImageInfo *ii = image->image_info;
1493 if (ii->cli_section_tables)
1494 g_free (ii->cli_section_tables);
1495 if (ii->cli_sections)
1496 g_free (ii->cli_sections);
1497 g_free (image->image_info);
1500 for (i = 0; i < image->module_count; ++i) {
1501 if (image->modules [i])
1502 mono_image_close (image->modules [i]);
1505 g_free (image->modules);
1506 if (image->modules_loaded)
1507 g_free (image->modules_loaded);
1508 if (image->references)
1509 g_free (image->references);
1510 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
1512 DeleteCriticalSection (&image->szarray_cache_lock);
1513 DeleteCriticalSection (&image->lock);
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);
1583 } else if (level==1) {
1584 if (res_id != name_offset)
1588 is_string==TRUE && name!=lookup (name_offset)) {
1592 } else if (level==2) {
1593 if (is_string == TRUE || (is_string == FALSE && lang_id != 0 && name_offset != lang_id))
1596 g_assert_not_reached ();
1600 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
1601 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1604 entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
1606 for(i=0; i<entries; i++) {
1607 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1610 ret=mono_image_walk_resource_tree (info, res_id,
1621 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
1622 MonoPEResourceDataEntry *res;
1624 res = g_new0 (MonoPEResourceDataEntry, 1);
1626 res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
1627 res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
1628 res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
1629 res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
1636 * mono_image_lookup_resource:
1637 * @image: the image to look up the resource in
1638 * @res_id: A MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
1639 * @lang_id: The language id.
1640 * @name: the resource name to lookup.
1642 * Returns: NULL if not found, otherwise a pointer to the in-memory representation
1643 * of the given resource. The caller should free it using g_free () when no longer
1647 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1649 MonoCLIImageInfo *info;
1650 MonoDotNetHeader *header;
1651 MonoPEDatadir *datadir;
1652 MonoPEDirEntry *rsrc;
1653 MonoPEResourceDir *resource_dir;
1654 MonoPEResourceDirEntry *res_entries;
1661 mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
1663 info=image->image_info;
1668 header=&info->cli_header;
1673 datadir=&header->datadir;
1678 rsrc=&datadir->pe_resource_table;
1683 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1684 if(resource_dir==NULL) {
1688 entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
1689 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1691 for(i=0; i<entries; i++) {
1692 MonoPEResourceDirEntry *entry=&res_entries[i];
1695 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1696 name, entry, resource_dir,
1707 * mono_image_get_entry_point:
1708 * @image: the image where the entry point will be looked up.
1710 * Use this routine to determine the metadata token for method that
1711 * has been flagged as the entry point.
1713 * Returns: the token for the entry point method in the image
1716 mono_image_get_entry_point (MonoImage *image)
1718 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1722 * mono_image_get_resource:
1723 * @image: the image where the resource will be looked up.
1724 * @offset: The offset to add to the resource
1725 * @size: a pointer to an int where the size of the resource will be stored
1727 * This is a low-level routine that fetches a resource from the
1728 * metadata that starts at a given @offset. The @size parameter is
1729 * filled with the data field as encoded in the metadata.
1731 * Returns: the pointer to the resource whose offset is @offset.
1734 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1736 MonoCLIImageInfo *iinfo = image->image_info;
1737 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1740 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1743 data = mono_image_rva_map (image, ch->ch_resources.rva);
1748 *size = read32 (data);
1754 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1756 char *base_dir, *name;
1758 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1762 if (fileidx < 1 || fileidx > t->rows)
1765 mono_loader_lock ();
1766 if (image->files && image->files [fileidx - 1]) {
1767 mono_loader_unlock ();
1768 return image->files [fileidx - 1];
1772 image->files = g_new0 (MonoImage*, t->rows);
1774 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1775 fname = mono_metadata_string_heap (image, fname_id);
1776 base_dir = g_path_get_dirname (image->name);
1777 name = g_build_filename (base_dir, fname, NULL);
1778 res = mono_image_open (name, NULL);
1781 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1782 res->assembly = image->assembly;
1783 for (i = 0; i < res->module_count; ++i) {
1784 if (res->modules [i] && !res->modules [i]->assembly)
1785 res->modules [i]->assembly = image->assembly;
1788 image->files [fileidx - 1] = res;
1789 #ifdef PLATFORM_WIN32
1790 if (res->is_module_handle)
1791 mono_image_fixup_vtable (res);
1794 mono_loader_unlock ();
1801 * mono_image_get_strong_name:
1802 * @image: a MonoImage
1803 * @size: a guint32 pointer, or NULL.
1805 * If the image has a strong name, and @size is not NULL, the value
1806 * pointed to by size will have the size of the strong name.
1808 * Returns: NULL if the image does not have a strong name, or a
1809 * pointer to the public key.
1812 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1814 MonoCLIImageInfo *iinfo = image->image_info;
1815 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1818 if (!de->size || !de->rva)
1820 data = mono_image_rva_map (image, de->rva);
1829 * mono_image_strong_name_position:
1830 * @image: a MonoImage
1831 * @size: a guint32 pointer, or NULL.
1833 * If the image has a strong name, and @size is not NULL, the value
1834 * pointed to by size will have the size of the strong name.
1836 * Returns: the position within the image file where the strong name
1840 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1842 MonoCLIImageInfo *iinfo = image->image_info;
1843 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1848 if (!de->size || !de->rva)
1850 pos = mono_cli_rva_image_map (image, de->rva);
1851 return pos == INVALID_ADDRESS ? 0 : pos;
1855 * mono_image_get_public_key:
1856 * @image: a MonoImage
1857 * @size: a guint32 pointer, or NULL.
1859 * This is used to obtain the public key in the @image.
1861 * If the image has a public key, and @size is not NULL, the value
1862 * pointed to by size will have the size of the public key.
1864 * Returns: NULL if the image does not have a public key, or a pointer
1865 * to the public key.
1868 mono_image_get_public_key (MonoImage *image, guint32 *size)
1873 if (image->dynamic) {
1875 *size = ((MonoDynamicImage*)image)->public_key_len;
1876 return (char*)((MonoDynamicImage*)image)->public_key;
1878 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1880 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1883 pubkey = mono_metadata_blob_heap (image, tok);
1884 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1891 * mono_image_get_name:
1892 * @name: a MonoImage
1894 * Returns: the name of the assembly.
1897 mono_image_get_name (MonoImage *image)
1899 return image->assembly_name;
1903 * mono_image_get_filename:
1904 * @image: a MonoImage
1906 * Used to get the filename that hold the actual MonoImage
1908 * Returns: the filename.
1911 mono_image_get_filename (MonoImage *image)
1917 mono_image_get_guid (MonoImage *image)
1922 const MonoTableInfo*
1923 mono_image_get_table_info (MonoImage *image, int table_id)
1925 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1927 return &image->tables [table_id];
1931 mono_image_get_table_rows (MonoImage *image, int table_id)
1933 if (table_id < 0 || table_id >= MONO_TABLE_NUM)
1935 return image->tables [table_id].rows;
1939 mono_table_info_get_rows (const MonoTableInfo *table)
1945 * mono_image_get_assembly:
1946 * @image: the MonoImage.
1948 * Use this routine to get the assembly that owns this image.
1950 * Returns: the assembly that holds this image.
1953 mono_image_get_assembly (MonoImage *image)
1955 return image->assembly;
1959 * mono_image_is_dynamic:
1960 * @image: the MonoImage
1962 * Determines if the given image was created dynamically through the
1963 * System.Reflection.Emit API
1965 * Returns: TRUE if the image was created dynamically, FALSE if not.
1968 mono_image_is_dynamic (MonoImage *image)
1970 return image->dynamic;
1974 * mono_image_has_authenticode_entry:
1975 * @image: the MonoImage
1977 * Use this routine to determine if the image has a Authenticode
1978 * Certificate Table.
1980 * Returns: TRUE if the image contains an authenticode entry in the PE
1984 mono_image_has_authenticode_entry (MonoImage *image)
1986 MonoCLIImageInfo *iinfo = image->image_info;
1987 MonoDotNetHeader *header = &iinfo->cli_header;
1988 MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
1989 // the Authenticode "pre" (non ASN.1) header is 8 bytes long
1990 return ((de->rva != 0) && (de->size > 8));
1994 mono_image_alloc (MonoImage *image, guint size)
1998 mono_perfcounters->loader_bytes += size;
1999 mono_image_lock (image);
2000 res = mono_mempool_alloc (image->mempool, size);
2001 mono_image_unlock (image);
2007 mono_image_alloc0 (MonoImage *image, guint size)
2011 mono_perfcounters->loader_bytes += size;
2012 mono_image_lock (image);
2013 res = mono_mempool_alloc0 (image->mempool, size);
2014 mono_image_unlock (image);
2020 mono_image_strdup (MonoImage *image, const char *s)
2024 mono_perfcounters->loader_bytes += strlen (s);
2025 mono_image_lock (image);
2026 res = mono_mempool_strdup (image->mempool, s);
2027 mono_image_unlock (image);
2033 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
2037 new_list = mono_image_alloc (image, sizeof (GList));
2038 new_list->data = data;
2039 new_list->prev = list ? list->prev : NULL;
2040 new_list->next = list;
2043 new_list->prev->next = new_list;
2045 list->prev = new_list;
2051 g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
2055 new_list = mono_image_alloc (image, sizeof (GSList));
2056 new_list->data = data;
2057 new_list->next = NULL;
2059 return g_slist_concat (list, new_list);
2063 mono_image_lock (MonoImage *image)
2065 mono_locks_acquire (&image->lock, ImageDataLock);
2069 mono_image_unlock (MonoImage *image)
2071 mono_locks_release (&image->lock, ImageDataLock);
2076 * mono_image_property_lookup:
2078 * Lookup a property on @image. Used to store very rare fields of MonoClass and MonoMethod.
2080 * LOCKING: Takes the image lock
2083 mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
2087 mono_image_lock (image);
2088 res = mono_property_hash_lookup (image->property_hash, subject, property);
2089 mono_image_unlock (image);
2095 * mono_image_property_insert:
2097 * Insert a new property @property with value @value on @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2099 * LOCKING: Takes the image lock
2102 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
2104 mono_image_lock (image);
2105 mono_property_hash_insert (image->property_hash, subject, property, value);
2106 mono_image_unlock (image);
2110 * mono_image_property_remove:
2112 * Remove all properties associated with @subject in @image. Used to store very rare fields of MonoClass and MonoMethod.
2114 * LOCKING: Takes the image lock
2117 mono_image_property_remove (MonoImage *image, gpointer subject)
2119 mono_image_lock (image);
2120 mono_property_hash_remove_object (image->property_hash, subject);
2121 mono_image_unlock (image);