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 "rawbuffer.h"
21 #include "mono-endian.h"
23 #include "tabledefs.h"
24 #include "tokentype.h"
25 #include <mono/io-layer/io-layer.h>
27 #define INVALID_ADDRESS 0xffffffff
30 * Keeps track of the various assemblies loaded
32 static GHashTable *loaded_images_hash;
33 static GHashTable *loaded_images_guid_hash;
35 static CRITICAL_SECTION images_mutex;
38 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
40 const int top = iinfo->cli_section_count;
41 MonoSectionTable *tables = iinfo->cli_section_tables;
44 for (i = 0; i < top; i++){
45 if ((addr >= tables->st_virtual_address) &&
46 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
47 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
51 return INVALID_ADDRESS;
55 mono_cli_rva_map (MonoCLIImageInfo *iinfo, guint32 addr)
57 const int top = iinfo->cli_section_count;
58 MonoSectionTable *tables = iinfo->cli_section_tables;
61 for (i = 0; i < top; i++){
62 if ((addr >= tables->st_virtual_address) &&
63 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
64 return (char*)iinfo->cli_sections [i] +
65 (addr - tables->st_virtual_address);
75 * Initialize the global variables used by this module.
78 mono_images_init (void)
80 InitializeCriticalSection (&images_mutex);
82 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
83 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
87 * mono_image_ensure_section_idx:
88 * @image: The image we are operating on
89 * @section: section number that we will load/map into memory
91 * This routine makes sure that we have an in-memory copy of
92 * an image section (.text, .rsrc, .data).
94 * Returns: TRUE on success
97 mono_image_ensure_section_idx (MonoImage *image, int section)
99 MonoCLIImageInfo *iinfo = image->image_info;
100 MonoSectionTable *sect;
103 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
105 if (iinfo->cli_sections [section] != NULL)
108 sect = &iinfo->cli_section_tables [section];
110 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
113 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
115 /* FIXME: we ignore the writable flag since we don't patch the binary */
116 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
119 iinfo->cli_sections [section] = mono_raw_buffer_load (
120 fileno (image->f), writable,
121 sect->st_raw_data_ptr, sect->st_raw_data_size);
123 if (iinfo->cli_sections [section] == NULL)
130 * mono_image_ensure_section:
131 * @image: The image we are operating on
132 * @section: section name that we will load/map into memory
134 * This routine makes sure that we have an in-memory copy of
135 * an image section (.text, .rsrc, .data).
137 * Returns: TRUE on success
140 mono_image_ensure_section (MonoImage *image, const char *section)
142 MonoCLIImageInfo *ii = image->image_info;
145 for (i = 0; i < ii->cli_section_count; i++){
146 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
149 return mono_image_ensure_section_idx (image, i);
155 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
157 const int top = iinfo->cli_header.coff.coff_sections;
160 iinfo->cli_section_count = top;
161 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
162 iinfo->cli_sections = g_new0 (void *, top);
164 for (i = 0; i < top; i++){
165 MonoSectionTable *t = &iinfo->cli_section_tables [i];
168 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
170 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
171 offset += sizeof (MonoSectionTable);
173 if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
177 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
178 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
179 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
180 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
181 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
182 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
183 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
184 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
185 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
186 t->st_flags = GUINT32_FROM_LE (t->st_flags);
188 /* consistency checks here */
191 for (i = 0; i < top; i++)
192 if (!mono_image_ensure_section_idx (image, i))
199 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
204 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
205 if (offset == INVALID_ADDRESS)
209 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
211 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
213 if (fseek (image->f, offset, SEEK_SET) != 0)
216 if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
220 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
221 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
222 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
223 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
224 SWAP32 (iinfo->cli_cli_header.ch_size);
225 SWAP32 (iinfo->cli_cli_header.ch_flags);
226 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
227 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
228 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
229 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
230 SWAPPDE (iinfo->cli_cli_header.ch_resources);
231 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
232 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
233 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
234 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
235 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
236 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
237 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
238 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
239 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
240 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
241 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
242 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
243 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
248 /* Catch new uses of the fields that are supposed to be zero */
250 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
251 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
252 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
253 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
254 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
255 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
256 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
257 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
258 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
261 * No need to scare people who are testing this, I am just
262 * labelling this as a LAMESPEC
264 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
272 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
274 guint32 offset, size;
280 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
281 if (offset == INVALID_ADDRESS)
284 size = iinfo->cli_cli_header.ch_metadata.size;
287 if (offset + size > image->raw_data_len)
289 image->raw_metadata = image->raw_data + offset;
291 image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
292 if (image->raw_metadata == NULL)
296 ptr = image->raw_metadata;
298 if (strncmp (ptr, "BSJB", 4) == 0){
299 guint32 version_string_len;
302 version_string_len = read32 (ptr);
304 image->version = g_strndup (ptr, version_string_len);
305 ptr += version_string_len;
306 pad = ptr - image->raw_metadata;
308 ptr += 4 - (pad % 4);
312 /* skip over flags */
315 streams = read16 (ptr);
318 for (i = 0; i < streams; i++){
319 if (strncmp (ptr + 8, "#~", 3) == 0){
320 image->heap_tables.data = image->raw_metadata + read32 (ptr);
321 image->heap_tables.size = read32 (ptr + 4);
323 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
324 image->heap_strings.data = image->raw_metadata + read32 (ptr);
325 image->heap_strings.size = read32 (ptr + 4);
327 } else if (strncmp (ptr + 8, "#US", 4) == 0){
328 image->heap_us.data = image->raw_metadata + read32 (ptr);
329 image->heap_us.size = read32 (ptr + 4);
331 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
332 image->heap_blob.data = image->raw_metadata + read32 (ptr);
333 image->heap_blob.size = read32 (ptr + 4);
335 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
336 image->heap_guid.data = image->raw_metadata + read32 (ptr);
337 image->heap_guid.size = read32 (ptr + 4);
339 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
340 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
343 g_message ("Unknown heap type: %s\n", ptr + 8);
344 ptr += 8 + strlen (ptr + 8) + 1;
346 pad = ptr - image->raw_metadata;
348 ptr += 4 - (pad % 4);
351 g_assert (image->heap_guid.data);
352 g_assert (image->heap_guid.size >= 16);
354 image->guid = mono_guid_to_string (image->heap_guid.data);
360 * Load representation of logical metadata tables, from the "#~" stream
363 load_tables (MonoImage *image)
365 const char *heap_tables = image->heap_tables.data;
367 guint64 valid_mask, sorted_mask;
368 int valid = 0, table;
371 heap_sizes = heap_tables [6];
372 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
373 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
374 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
376 valid_mask = read64 (heap_tables + 8);
377 sorted_mask = read64 (heap_tables + 16);
378 rows = (const guint32 *) (heap_tables + 24);
380 for (table = 0; table < 64; table++){
381 if ((valid_mask & ((guint64) 1 << table)) == 0){
382 image->tables [table].rows = 0;
385 if (table > MONO_TABLE_LAST) {
386 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
388 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
389 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
391 image->tables [table].rows = read32 (rows);
396 image->tables_base = (heap_tables + 24) + (4 * valid);
398 /* They must be the same */
399 g_assert ((const void *) image->tables_base == (const void *) rows);
401 mono_metadata_compute_table_bases (image);
406 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
408 if (!load_metadata_ptrs (image, iinfo))
411 return load_tables (image);
415 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
416 const char *name, guint32 index)
418 GHashTable *nspace_table;
419 GHashTable *name_cache = image->name_cache;
421 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
422 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
423 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
425 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
429 load_modules (MonoImage *image, MonoImageOpenStatus *status)
438 t = &image->tables [MONO_TABLE_MODULEREF];
439 image->modules = g_new0 (MonoImage *, t->rows);
440 base_dir = g_path_get_dirname (image->name);
441 for (i = 0; i < t->rows; i++){
444 guint32 cols [MONO_MODULEREF_SIZE];
446 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
447 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
448 module_ref = g_build_filename (base_dir, name, NULL);
449 image->modules [i] = mono_image_open (module_ref, status);
450 if (image->modules [i]) {
451 //g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly);
454 * FIXME: what do we do here? it could be a native dll...
455 * We should probably do lazy-loading of modules.
458 *status = MONO_IMAGE_OK;
466 load_class_names (MonoImage *image)
468 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
469 guint32 cols [MONO_TYPEDEF_SIZE];
472 guint32 i, visib, nspace_index;
473 GHashTable *name_cache2, *nspace_table;
475 /* Temporary hash table to avoid lookups in the nspace_table */
476 name_cache2 = g_hash_table_new (NULL, NULL);
478 for (i = 1; i <= t->rows; ++i) {
479 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
480 /* nested types are accessed from the nesting name */
481 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
482 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
484 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
485 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
487 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
488 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
490 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
491 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
492 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
495 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
498 /* Load type names from EXPORTEDTYPES table */
500 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
501 guint32 cols [MONO_EXP_TYPE_SIZE];
504 for (i = 0; i < t->rows; ++i) {
505 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
506 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
507 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
509 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
510 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
512 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
513 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
514 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
517 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
521 g_hash_table_destroy (name_cache2);
525 register_guid (gpointer key, gpointer value, gpointer user_data)
527 MonoImage *image = (MonoImage*)value;
529 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
530 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
534 build_guid_table (void)
536 g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
540 mono_image_init (MonoImage *image)
542 image->method_cache = g_hash_table_new (NULL, NULL);
543 image->class_cache = g_hash_table_new (NULL, NULL);
544 image->field_cache = g_hash_table_new (NULL, NULL);
545 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
546 image->array_cache = g_hash_table_new (NULL, NULL);
548 image->delegate_begin_invoke_cache =
549 g_hash_table_new ((GHashFunc)mono_signature_hash,
550 (GCompareFunc)mono_metadata_signature_equal);
551 image->delegate_end_invoke_cache =
552 g_hash_table_new ((GHashFunc)mono_signature_hash,
553 (GCompareFunc)mono_metadata_signature_equal);
554 image->delegate_invoke_cache =
555 g_hash_table_new ((GHashFunc)mono_signature_hash,
556 (GCompareFunc)mono_metadata_signature_equal);
557 image->runtime_invoke_cache =
558 g_hash_table_new ((GHashFunc)mono_signature_hash,
559 (GCompareFunc)mono_metadata_signature_equal);
561 image->managed_wrapper_cache = g_hash_table_new (NULL, NULL);
562 image->native_wrapper_cache = g_hash_table_new (NULL, NULL);
563 image->remoting_invoke_cache = g_hash_table_new (NULL, NULL);
564 image->synchronized_cache = g_hash_table_new (NULL, NULL);
566 image->typespec_cache = g_hash_table_new (NULL, NULL);
568 image->generic_inst_cache =
569 g_hash_table_new ((GHashFunc)mono_metadata_generic_inst_hash,
570 (GCompareFunc)mono_metadata_generic_inst_equal);
574 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
576 MonoCLIImageInfo *iinfo;
577 MonoDotNetHeader *header;
578 MonoMSDOSHeader msdos;
582 mono_image_init (image);
584 iinfo = image->image_info;
585 header = &iinfo->cli_header;
588 *status = MONO_IMAGE_IMAGE_INVALID;
591 if (offset + sizeof (msdos) > image->raw_data_len)
593 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
595 if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
599 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
602 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
604 if (msdos.pe_offset != sizeof (msdos)) {
606 fseek (image->f, msdos.pe_offset, SEEK_SET);
608 offset = msdos.pe_offset;
611 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
613 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
614 offset += sizeof (MonoDotNetHeader);
616 if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
620 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
621 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
622 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
623 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
624 SWAP32 (header->coff.coff_time);
625 SWAP32 (header->coff.coff_symptr);
626 SWAP32 (header->coff.coff_symcount);
627 SWAP16 (header->coff.coff_machine);
628 SWAP16 (header->coff.coff_sections);
629 SWAP16 (header->coff.coff_opt_header_size);
630 SWAP16 (header->coff.coff_attributes);
632 SWAP32 (header->pe.pe_code_size);
633 SWAP32 (header->pe.pe_data_size);
634 SWAP32 (header->pe.pe_uninit_data_size);
635 SWAP32 (header->pe.pe_rva_entry_point);
636 SWAP32 (header->pe.pe_rva_code_base);
637 SWAP32 (header->pe.pe_rva_data_base);
638 SWAP16 (header->pe.pe_magic);
640 /* MonoPEHeaderNT: not used yet */
641 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
642 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
643 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
644 SWAP16 (header->nt.pe_os_major); /* must be 4 */
645 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
646 SWAP16 (header->nt.pe_user_major);
647 SWAP16 (header->nt.pe_user_minor);
648 SWAP16 (header->nt.pe_subsys_major);
649 SWAP16 (header->nt.pe_subsys_minor);
650 SWAP32 (header->nt.pe_reserved_1);
651 SWAP32 (header->nt.pe_image_size);
652 SWAP32 (header->nt.pe_header_size);
653 SWAP32 (header->nt.pe_checksum);
654 SWAP16 (header->nt.pe_subsys_required);
655 SWAP16 (header->nt.pe_dll_flags);
656 SWAP32 (header->nt.pe_stack_reserve);
657 SWAP32 (header->nt.pe_stack_commit);
658 SWAP32 (header->nt.pe_heap_reserve);
659 SWAP32 (header->nt.pe_heap_commit);
660 SWAP32 (header->nt.pe_loader_flags);
661 SWAP32 (header->nt.pe_data_dir_count);
663 /* MonoDotNetHeader: mostly unused */
664 SWAPPDE (header->datadir.pe_export_table);
665 SWAPPDE (header->datadir.pe_import_table);
666 SWAPPDE (header->datadir.pe_resource_table);
667 SWAPPDE (header->datadir.pe_exception_table);
668 SWAPPDE (header->datadir.pe_certificate_table);
669 SWAPPDE (header->datadir.pe_reloc_table);
670 SWAPPDE (header->datadir.pe_debug);
671 SWAPPDE (header->datadir.pe_copyright);
672 SWAPPDE (header->datadir.pe_global_ptr);
673 SWAPPDE (header->datadir.pe_tls_table);
674 SWAPPDE (header->datadir.pe_load_config_table);
675 SWAPPDE (header->datadir.pe_bound_import);
676 SWAPPDE (header->datadir.pe_iat);
677 SWAPPDE (header->datadir.pe_delay_import_desc);
678 SWAPPDE (header->datadir.pe_cli_header);
679 SWAPPDE (header->datadir.pe_reserved);
686 if (header->coff.coff_machine != 0x14c)
689 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
692 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
697 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
698 * which produces binaries with 7.0. From Sergey:
700 * The reason is that MSVC7 uses traditional compile/link
701 * sequence for CIL executables, and VS.NET (and Framework
702 * SDK) includes linker version 7, that puts 7.0 in this
703 * field. That's why it's currently not possible to load VC
704 * binaries with Mono. This field is pretty much meaningless
705 * anyway (what linker?).
707 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
712 * FIXME: byte swap all addresses here for header.
715 if (!load_section_tables (image, iinfo, offset))
718 /* Load the CLI header */
719 if (!load_cli_header (image, iinfo))
722 if (!load_metadata (image, iinfo))
725 load_class_names (image);
727 /* modules don't have an assembly table row */
728 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
729 image->assembly_name = mono_metadata_string_heap (image,
730 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
731 0, MONO_ASSEMBLY_NAME));
733 image->module_name = mono_metadata_string_heap (image,
734 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
735 0, MONO_MODULE_NAME));
737 load_modules (image, status);
740 *status = MONO_IMAGE_OK;
747 mono_image_close (image);
752 do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
754 MonoCLIImageInfo *iinfo;
758 if ((filed = fopen (fname, "rb")) == NULL){
760 *status = MONO_IMAGE_ERROR_ERRNO;
764 image = g_new0 (MonoImage, 1);
765 image->ref_count = 1;
767 iinfo = g_new0 (MonoCLIImageInfo, 1);
768 image->image_info = iinfo;
770 if (g_path_is_absolute (fname))
771 image->name = g_strdup (fname);
773 gchar *path = g_get_current_dir ();
774 image->name = g_build_filename (path, fname, NULL);
778 return do_mono_image_load (image, status);
782 mono_image_loaded (const char *name)
786 EnterCriticalSection (&images_mutex);
787 res = g_hash_table_lookup (loaded_images_hash, name);
788 LeaveCriticalSection (&images_mutex);
793 mono_image_loaded_by_guid (const char *guid)
797 EnterCriticalSection (&images_mutex);
798 res = g_hash_table_lookup (loaded_images_guid_hash, guid);
799 LeaveCriticalSection (&images_mutex);
804 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
806 MonoCLIImageInfo *iinfo;
810 if (!data || !data_len) {
812 *status = MONO_IMAGE_IMAGE_INVALID;
817 datac = g_try_malloc (data_len);
820 *status = MONO_IMAGE_ERROR_ERRNO;
823 memcpy (datac, data, data_len);
826 image = g_new0 (MonoImage, 1);
827 image->ref_count = 1;
828 image->raw_data = datac;
829 image->raw_data_len = data_len;
830 image->raw_data_allocated = need_copy;
831 image->name = g_strdup_printf ("data-%p", datac);
832 iinfo = g_new0 (MonoCLIImageInfo, 1);
833 image->image_info = iinfo;
835 return do_mono_image_load (image, status);
840 * @fname: filename that points to the module we want to open
841 * @status: An error condition is returned in this field
843 * Retuns: An open image of type %MonoImage or NULL on error.
844 * if NULL, then check the value of @status for details on the error
847 mono_image_open (const char *fname, MonoImageOpenStatus *status)
849 MonoImage *image, *image2;
850 const char *absfname;
852 g_return_val_if_fail (fname != NULL, NULL);
854 if (g_path_is_absolute (fname))
857 gchar *path = g_get_current_dir ();
858 absfname = g_build_filename (path, fname, NULL);
863 * The easiest solution would be to do all the loading inside the mutex,
864 * but that would lead to scalability problems. So we let the loading
865 * happen outside the mutex, and if multiple threads happen to load
866 * the same image, we discard all but the first copy.
868 EnterCriticalSection (&images_mutex);
869 image = g_hash_table_lookup (loaded_images_hash, absfname);
871 if (absfname != fname)
876 LeaveCriticalSection (&images_mutex);
879 LeaveCriticalSection (&images_mutex);
881 image = do_mono_image_open (fname, status);
885 EnterCriticalSection (&images_mutex);
886 image2 = g_hash_table_lookup (loaded_images_hash, fname);
888 /* Somebody else beat us to it */
889 image2->ref_count ++;
890 LeaveCriticalSection (&images_mutex);
891 mono_image_close (image);
895 g_hash_table_insert (loaded_images_hash, image->name, image);
896 if (image->assembly_name)
897 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image);
898 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
899 LeaveCriticalSection (&images_mutex);
905 free_hash_table (gpointer key, gpointer val, gpointer user_data)
907 g_hash_table_destroy ((GHashTable*)val);
912 * @image: The image file we wish to add a reference to
914 * Increases the reference count of an image.
917 mono_image_addref (MonoImage *image)
919 InterlockedIncrement (&image->ref_count);
924 * @image: The image file we wish to close
926 * Closes an image file, deallocates all memory consumed and
927 * unmaps all possible sections of the file
930 mono_image_close (MonoImage *image)
934 g_return_if_fail (image != NULL);
936 EnterCriticalSection (&images_mutex);
937 if (--image->ref_count) {
938 LeaveCriticalSection (&images_mutex);
941 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
942 if (image == image2) {
943 /* This is not true if we are called from mono_image_open () */
944 g_hash_table_remove (loaded_images_hash, image->name);
945 if (image->assembly_name)
946 g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);
947 g_hash_table_remove (loaded_images_guid_hash, image->guid);
948 /* Multiple images might have the same guid */
951 LeaveCriticalSection (&images_mutex);
955 if (image->raw_data_allocated)
956 g_free (image->raw_data);
958 g_free (image->name);
959 g_free (image->files);
961 g_hash_table_destroy (image->method_cache);
962 g_hash_table_destroy (image->class_cache);
963 g_hash_table_destroy (image->field_cache);
964 g_hash_table_destroy (image->array_cache);
965 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
966 g_hash_table_destroy (image->name_cache);
967 g_hash_table_destroy (image->native_wrapper_cache);
968 g_hash_table_destroy (image->managed_wrapper_cache);
969 g_hash_table_destroy (image->delegate_begin_invoke_cache);
970 g_hash_table_destroy (image->delegate_end_invoke_cache);
971 g_hash_table_destroy (image->delegate_invoke_cache);
972 g_hash_table_destroy (image->remoting_invoke_cache);
973 g_hash_table_destroy (image->runtime_invoke_cache);
974 g_hash_table_destroy (image->typespec_cache);
975 g_hash_table_destroy (image->generic_inst_cache);
977 if (image->raw_metadata != NULL)
978 mono_raw_buffer_free (image->raw_metadata);
980 if (image->image_info){
981 MonoCLIImageInfo *ii = image->image_info;
984 for (i = 0; i < ii->cli_section_count; i++){
985 if (!ii->cli_sections [i])
987 mono_raw_buffer_free (ii->cli_sections [i]);
989 if (ii->cli_section_tables)
990 g_free (ii->cli_section_tables);
991 if (ii->cli_sections)
992 g_free (ii->cli_sections);
993 g_free (image->image_info);
1000 * mono_image_strerror:
1001 * @status: an code indicating the result from a recent operation
1003 * Returns: a string describing the error
1006 mono_image_strerror (MonoImageOpenStatus status)
1011 case MONO_IMAGE_ERROR_ERRNO:
1012 return strerror (errno);
1013 case MONO_IMAGE_IMAGE_INVALID:
1014 return "File does not contain a valid CIL image";
1015 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1016 return "An assembly was referenced, but could not be found";
1018 return "Internal error";
1022 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1023 guint32 lang_id, gunichar2 *name,
1024 MonoPEResourceDirEntry *entry,
1025 MonoPEResourceDir *root, guint32 level)
1027 gboolean is_string=entry->name_is_string;
1029 /* Level 0 holds a directory entry for each type of resource
1030 * (identified by ID or name).
1032 * Level 1 holds a directory entry for each named resource
1033 * item, and each "anonymous" item of a particular type of
1036 * Level 2 holds a directory entry for each language pointing to
1041 if((is_string==FALSE && entry->name_offset!=res_id) ||
1042 (is_string==TRUE)) {
1045 } else if (level==1) {
1048 is_string==TRUE && name!=lookup (entry->name_offset)) {
1052 } else if (level==2) {
1053 if((is_string==FALSE && entry->name_offset!=lang_id) ||
1054 (is_string==TRUE)) {
1058 g_assert_not_reached ();
1061 if(entry->is_dir==TRUE) {
1062 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1063 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1066 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1068 for(i=0; i<entries; i++) {
1069 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1072 ret=mono_image_walk_resource_tree (info, res_id,
1083 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1090 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1092 MonoCLIImageInfo *info;
1093 MonoDotNetHeader *header;
1094 MonoPEDatadir *datadir;
1095 MonoPEDirEntry *rsrc;
1096 MonoPEResourceDir *resource_dir;
1097 MonoPEResourceDirEntry *res_entries;
1104 info=image->image_info;
1109 header=&info->cli_header;
1114 datadir=&header->datadir;
1119 rsrc=&datadir->pe_resource_table;
1124 resource_dir=(MonoPEResourceDir *)mono_cli_rva_map (info, rsrc->rva);
1125 if(resource_dir==NULL) {
1129 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1130 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1132 for(i=0; i<entries; i++) {
1133 MonoPEResourceDirEntry *entry=&res_entries[i];
1136 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1137 name, entry, resource_dir,
1148 mono_image_get_entry_point (MonoImage *image)
1150 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1154 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1156 MonoCLIImageInfo *iinfo = image->image_info;
1157 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1160 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1163 data = mono_cli_rva_map (iinfo, ch->ch_resources.rva);
1168 *size = read32 (data);
1174 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1176 char *base_dir, *name;
1178 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1182 if (fileidx < 1 || fileidx > t->rows)
1185 if (image->files && image->files [fileidx - 1])
1186 return image->files [fileidx - 1];
1189 image->files = g_new0 (MonoImage*, t->rows);
1191 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1192 fname = mono_metadata_string_heap (image, fname_id);
1193 base_dir = g_path_get_dirname (image->name);
1194 name = g_build_filename (base_dir, fname, NULL);
1195 res = mono_image_open (name, NULL);
1198 t = &res->tables [MONO_TABLE_MODULEREF];
1199 //g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly);
1200 res->assembly = image->assembly;
1201 for (i = 0; i < t->rows; ++i) {
1202 if (res->modules [i] && !res->modules [i]->assembly)
1203 res->modules [i]->assembly = image->assembly;
1206 image->files [fileidx - 1] = res;
1214 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1216 MonoCLIImageInfo *iinfo = image->image_info;
1217 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1220 if (!de->size || !de->rva)
1222 data = mono_cli_rva_map (iinfo, de->rva);
1231 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1233 MonoCLIImageInfo *iinfo = image->image_info;
1234 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1235 const int top = iinfo->cli_section_count;
1236 MonoSectionTable *tables = iinfo->cli_section_tables;
1238 guint32 addr = de->rva;
1242 if (!de->size || !de->rva)
1244 for (i = 0; i < top; i++){
1245 if ((addr >= tables->st_virtual_address) &&
1246 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1247 return tables->st_raw_data_ptr +
1248 (addr - tables->st_virtual_address);
1257 mono_image_get_public_key (MonoImage *image, guint32 *size)
1261 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1263 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1266 pubkey = mono_metadata_blob_heap (image, tok);
1267 len = mono_metadata_decode_blob_size (pubkey, &pubkey);