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 "metadata-internals.h"
26 #include <mono/io-layer/io-layer.h>
28 #define INVALID_ADDRESS 0xffffffff
31 * Keeps track of the various assemblies loaded
33 static GHashTable *loaded_images_hash;
34 static GHashTable *loaded_images_guid_hash;
36 static CRITICAL_SECTION images_mutex;
39 mono_cli_rva_image_map (MonoCLIImageInfo *iinfo, guint32 addr)
41 const int top = iinfo->cli_section_count;
42 MonoSectionTable *tables = iinfo->cli_section_tables;
45 for (i = 0; i < top; i++){
46 if ((addr >= tables->st_virtual_address) &&
47 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
48 return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
52 return INVALID_ADDRESS;
56 mono_image_rva_map (MonoImage *image, guint32 addr)
58 MonoCLIImageInfo *iinfo = image->image_info;
59 const int top = iinfo->cli_section_count;
60 MonoSectionTable *tables = iinfo->cli_section_tables;
63 for (i = 0; i < top; i++){
64 if ((addr >= tables->st_virtual_address) &&
65 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
66 if (!iinfo->cli_sections [i]) {
67 if (!mono_image_ensure_section_idx (image, i))
70 return (char*)iinfo->cli_sections [i] +
71 (addr - tables->st_virtual_address);
81 * Initialize the global variables used by this module.
84 mono_images_init (void)
86 InitializeCriticalSection (&images_mutex);
88 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
89 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
93 * mono_image_ensure_section_idx:
94 * @image: The image we are operating on
95 * @section: section number that we will load/map into memory
97 * This routine makes sure that we have an in-memory copy of
98 * an image section (.text, .rsrc, .data).
100 * Returns: TRUE on success
103 mono_image_ensure_section_idx (MonoImage *image, int section)
105 MonoCLIImageInfo *iinfo = image->image_info;
106 MonoSectionTable *sect;
109 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
111 if (iinfo->cli_sections [section] != NULL)
114 sect = &iinfo->cli_section_tables [section];
116 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
119 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
121 /* FIXME: we ignore the writable flag since we don't patch the binary */
122 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
125 iinfo->cli_sections [section] = mono_raw_buffer_load (
126 fileno (image->f), writable,
127 sect->st_raw_data_ptr, sect->st_raw_data_size);
129 if (iinfo->cli_sections [section] == NULL)
136 * mono_image_ensure_section:
137 * @image: The image we are operating on
138 * @section: section name that we will load/map into memory
140 * This routine makes sure that we have an in-memory copy of
141 * an image section (.text, .rsrc, .data).
143 * Returns: TRUE on success
146 mono_image_ensure_section (MonoImage *image, const char *section)
148 MonoCLIImageInfo *ii = image->image_info;
151 for (i = 0; i < ii->cli_section_count; i++){
152 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
155 return mono_image_ensure_section_idx (image, i);
161 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
163 const int top = iinfo->cli_header.coff.coff_sections;
166 iinfo->cli_section_count = top;
167 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
168 iinfo->cli_sections = g_new0 (void *, top);
170 for (i = 0; i < top; i++){
171 MonoSectionTable *t = &iinfo->cli_section_tables [i];
174 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
176 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
177 offset += sizeof (MonoSectionTable);
179 if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
183 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
184 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
185 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
186 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
187 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
188 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
189 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
190 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
191 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
192 t->st_flags = GUINT32_FROM_LE (t->st_flags);
194 /* consistency checks here */
201 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
206 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
207 if (offset == INVALID_ADDRESS)
211 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
213 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
215 if (fseek (image->f, offset, SEEK_SET) != 0)
218 if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
222 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
223 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
224 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
225 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
226 SWAP32 (iinfo->cli_cli_header.ch_size);
227 SWAP32 (iinfo->cli_cli_header.ch_flags);
228 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
229 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
230 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
231 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
232 SWAPPDE (iinfo->cli_cli_header.ch_resources);
233 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
234 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
235 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
236 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
237 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
238 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
239 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
240 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
241 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
242 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
243 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
244 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
245 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
250 /* Catch new uses of the fields that are supposed to be zero */
252 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
253 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
254 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
255 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
256 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
257 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
258 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
259 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
260 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
263 * No need to scare people who are testing this, I am just
264 * labelling this as a LAMESPEC
266 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
274 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
276 guint32 offset, size;
282 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
283 if (offset == INVALID_ADDRESS)
286 size = iinfo->cli_cli_header.ch_metadata.size;
289 if (offset + size > image->raw_data_len)
291 image->raw_metadata = image->raw_data + offset;
293 image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
294 if (image->raw_metadata == NULL)
298 ptr = image->raw_metadata;
300 if (strncmp (ptr, "BSJB", 4) == 0){
301 guint32 version_string_len;
304 version_string_len = read32 (ptr);
306 image->version = g_strndup (ptr, version_string_len);
307 ptr += version_string_len;
308 pad = ptr - image->raw_metadata;
310 ptr += 4 - (pad % 4);
314 /* skip over flags */
317 streams = read16 (ptr);
320 for (i = 0; i < streams; i++){
321 if (strncmp (ptr + 8, "#~", 3) == 0){
322 image->heap_tables.data = image->raw_metadata + read32 (ptr);
323 image->heap_tables.size = read32 (ptr + 4);
325 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
326 image->heap_strings.data = image->raw_metadata + read32 (ptr);
327 image->heap_strings.size = read32 (ptr + 4);
329 } else if (strncmp (ptr + 8, "#US", 4) == 0){
330 image->heap_us.data = image->raw_metadata + read32 (ptr);
331 image->heap_us.size = read32 (ptr + 4);
333 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
334 image->heap_blob.data = image->raw_metadata + read32 (ptr);
335 image->heap_blob.size = read32 (ptr + 4);
337 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
338 image->heap_guid.data = image->raw_metadata + read32 (ptr);
339 image->heap_guid.size = read32 (ptr + 4);
341 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
342 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
345 g_message ("Unknown heap type: %s\n", ptr + 8);
346 ptr += 8 + strlen (ptr + 8) + 1;
348 pad = ptr - image->raw_metadata;
350 ptr += 4 - (pad % 4);
353 g_assert (image->heap_guid.data);
354 g_assert (image->heap_guid.size >= 16);
356 image->guid = mono_guid_to_string (image->heap_guid.data);
362 * Load representation of logical metadata tables, from the "#~" stream
365 load_tables (MonoImage *image)
367 const char *heap_tables = image->heap_tables.data;
369 guint64 valid_mask, sorted_mask;
370 int valid = 0, table;
373 heap_sizes = heap_tables [6];
374 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
375 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
376 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
378 valid_mask = read64 (heap_tables + 8);
379 sorted_mask = read64 (heap_tables + 16);
380 rows = (const guint32 *) (heap_tables + 24);
382 for (table = 0; table < 64; table++){
383 if ((valid_mask & ((guint64) 1 << table)) == 0){
384 image->tables [table].rows = 0;
387 if (table > MONO_TABLE_LAST) {
388 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
390 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
391 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
393 image->tables [table].rows = read32 (rows);
398 image->tables_base = (heap_tables + 24) + (4 * valid);
400 /* They must be the same */
401 g_assert ((const void *) image->tables_base == (const void *) rows);
403 mono_metadata_compute_table_bases (image);
408 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
410 if (!load_metadata_ptrs (image, iinfo))
413 return load_tables (image);
417 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
418 const char *name, guint32 index)
420 GHashTable *nspace_table;
421 GHashTable *name_cache = image->name_cache;
423 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
424 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
425 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
427 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
431 load_modules (MonoImage *image, MonoImageOpenStatus *status)
440 t = &image->tables [MONO_TABLE_MODULEREF];
441 image->modules = g_new0 (MonoImage *, t->rows);
442 base_dir = g_path_get_dirname (image->name);
443 for (i = 0; i < t->rows; i++){
446 guint32 cols [MONO_MODULEREF_SIZE];
448 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
449 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
450 module_ref = g_build_filename (base_dir, name, NULL);
451 image->modules [i] = mono_image_open (module_ref, status);
452 if (image->modules [i]) {
453 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
456 * FIXME: what do we do here? it could be a native dll...
457 * We should probably do lazy-loading of modules.
460 *status = MONO_IMAGE_OK;
468 load_class_names (MonoImage *image)
470 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
471 guint32 cols [MONO_TYPEDEF_SIZE];
474 guint32 i, visib, nspace_index;
475 GHashTable *name_cache2, *nspace_table;
477 /* Temporary hash table to avoid lookups in the nspace_table */
478 name_cache2 = g_hash_table_new (NULL, NULL);
480 for (i = 1; i <= t->rows; ++i) {
481 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
482 /* nested types are accessed from the nesting name */
483 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
484 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
486 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
487 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
489 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
490 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
492 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
493 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
494 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
497 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
500 /* Load type names from EXPORTEDTYPES table */
502 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
503 guint32 cols [MONO_EXP_TYPE_SIZE];
506 for (i = 0; i < t->rows; ++i) {
507 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
508 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
509 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
511 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
512 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
514 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
515 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
516 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
519 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
523 g_hash_table_destroy (name_cache2);
527 register_guid (gpointer key, gpointer value, gpointer user_data)
529 MonoImage *image = (MonoImage*)value;
531 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
532 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
536 build_guid_table (void)
538 g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
542 mono_image_init (MonoImage *image)
544 image->method_cache = g_hash_table_new (NULL, NULL);
545 image->class_cache = g_hash_table_new (NULL, NULL);
546 image->field_cache = g_hash_table_new (NULL, NULL);
547 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
548 image->array_cache = g_hash_table_new (NULL, NULL);
550 image->delegate_begin_invoke_cache =
551 g_hash_table_new ((GHashFunc)mono_signature_hash,
552 (GCompareFunc)mono_metadata_signature_equal);
553 image->delegate_end_invoke_cache =
554 g_hash_table_new ((GHashFunc)mono_signature_hash,
555 (GCompareFunc)mono_metadata_signature_equal);
556 image->delegate_invoke_cache =
557 g_hash_table_new ((GHashFunc)mono_signature_hash,
558 (GCompareFunc)mono_metadata_signature_equal);
559 image->runtime_invoke_cache =
560 g_hash_table_new ((GHashFunc)mono_signature_hash,
561 (GCompareFunc)mono_metadata_signature_equal);
563 image->managed_wrapper_cache = g_hash_table_new (NULL, NULL);
564 image->native_wrapper_cache = g_hash_table_new (NULL, NULL);
565 image->remoting_invoke_cache = g_hash_table_new (NULL, NULL);
566 image->synchronized_cache = g_hash_table_new (NULL, NULL);
568 image->typespec_cache = g_hash_table_new (NULL, NULL);
569 image->memberref_signatures = g_hash_table_new (NULL, NULL);
570 image->helper_signatures = g_hash_table_new (g_str_hash, g_str_equal);
572 image->generic_inst_cache =
573 g_hash_table_new ((GHashFunc)mono_metadata_generic_inst_hash,
574 (GCompareFunc)mono_metadata_generic_inst_equal);
578 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
580 MonoCLIImageInfo *iinfo;
581 MonoDotNetHeader *header;
582 MonoMSDOSHeader msdos;
586 mono_image_init (image);
588 iinfo = image->image_info;
589 header = &iinfo->cli_header;
592 *status = MONO_IMAGE_IMAGE_INVALID;
595 if (offset + sizeof (msdos) > image->raw_data_len)
597 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
599 if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
603 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
606 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
608 if (msdos.pe_offset != sizeof (msdos)) {
610 fseek (image->f, msdos.pe_offset, SEEK_SET);
612 offset = msdos.pe_offset;
615 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
617 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
618 offset += sizeof (MonoDotNetHeader);
620 if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
624 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
625 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
626 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
627 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
628 SWAP32 (header->coff.coff_time);
629 SWAP32 (header->coff.coff_symptr);
630 SWAP32 (header->coff.coff_symcount);
631 SWAP16 (header->coff.coff_machine);
632 SWAP16 (header->coff.coff_sections);
633 SWAP16 (header->coff.coff_opt_header_size);
634 SWAP16 (header->coff.coff_attributes);
636 SWAP32 (header->pe.pe_code_size);
637 SWAP32 (header->pe.pe_data_size);
638 SWAP32 (header->pe.pe_uninit_data_size);
639 SWAP32 (header->pe.pe_rva_entry_point);
640 SWAP32 (header->pe.pe_rva_code_base);
641 SWAP32 (header->pe.pe_rva_data_base);
642 SWAP16 (header->pe.pe_magic);
644 /* MonoPEHeaderNT: not used yet */
645 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
646 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
647 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
648 SWAP16 (header->nt.pe_os_major); /* must be 4 */
649 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
650 SWAP16 (header->nt.pe_user_major);
651 SWAP16 (header->nt.pe_user_minor);
652 SWAP16 (header->nt.pe_subsys_major);
653 SWAP16 (header->nt.pe_subsys_minor);
654 SWAP32 (header->nt.pe_reserved_1);
655 SWAP32 (header->nt.pe_image_size);
656 SWAP32 (header->nt.pe_header_size);
657 SWAP32 (header->nt.pe_checksum);
658 SWAP16 (header->nt.pe_subsys_required);
659 SWAP16 (header->nt.pe_dll_flags);
660 SWAP32 (header->nt.pe_stack_reserve);
661 SWAP32 (header->nt.pe_stack_commit);
662 SWAP32 (header->nt.pe_heap_reserve);
663 SWAP32 (header->nt.pe_heap_commit);
664 SWAP32 (header->nt.pe_loader_flags);
665 SWAP32 (header->nt.pe_data_dir_count);
667 /* MonoDotNetHeader: mostly unused */
668 SWAPPDE (header->datadir.pe_export_table);
669 SWAPPDE (header->datadir.pe_import_table);
670 SWAPPDE (header->datadir.pe_resource_table);
671 SWAPPDE (header->datadir.pe_exception_table);
672 SWAPPDE (header->datadir.pe_certificate_table);
673 SWAPPDE (header->datadir.pe_reloc_table);
674 SWAPPDE (header->datadir.pe_debug);
675 SWAPPDE (header->datadir.pe_copyright);
676 SWAPPDE (header->datadir.pe_global_ptr);
677 SWAPPDE (header->datadir.pe_tls_table);
678 SWAPPDE (header->datadir.pe_load_config_table);
679 SWAPPDE (header->datadir.pe_bound_import);
680 SWAPPDE (header->datadir.pe_iat);
681 SWAPPDE (header->datadir.pe_delay_import_desc);
682 SWAPPDE (header->datadir.pe_cli_header);
683 SWAPPDE (header->datadir.pe_reserved);
690 if (header->coff.coff_machine != 0x14c)
693 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
696 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
701 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
702 * which produces binaries with 7.0. From Sergey:
704 * The reason is that MSVC7 uses traditional compile/link
705 * sequence for CIL executables, and VS.NET (and Framework
706 * SDK) includes linker version 7, that puts 7.0 in this
707 * field. That's why it's currently not possible to load VC
708 * binaries with Mono. This field is pretty much meaningless
709 * anyway (what linker?).
711 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
716 * FIXME: byte swap all addresses here for header.
719 if (!load_section_tables (image, iinfo, offset))
722 /* Load the CLI header */
723 if (!load_cli_header (image, iinfo))
726 if (!load_metadata (image, iinfo))
729 load_class_names (image);
731 /* modules don't have an assembly table row */
732 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
733 image->assembly_name = mono_metadata_string_heap (image,
734 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
735 0, MONO_ASSEMBLY_NAME));
737 image->module_name = mono_metadata_string_heap (image,
738 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
739 0, MONO_MODULE_NAME));
741 load_modules (image, status);
744 *status = MONO_IMAGE_OK;
751 mono_image_close (image);
756 do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
758 MonoCLIImageInfo *iinfo;
762 if ((filed = fopen (fname, "rb")) == NULL){
764 *status = MONO_IMAGE_ERROR_ERRNO;
768 image = g_new0 (MonoImage, 1);
769 image->ref_count = 1;
771 iinfo = g_new0 (MonoCLIImageInfo, 1);
772 image->image_info = iinfo;
774 if (g_path_is_absolute (fname))
775 image->name = g_strdup (fname);
777 gchar *path = g_get_current_dir ();
778 image->name = g_build_filename (path, fname, NULL);
782 return do_mono_image_load (image, status);
786 mono_image_loaded (const char *name)
790 EnterCriticalSection (&images_mutex);
791 res = g_hash_table_lookup (loaded_images_hash, name);
792 LeaveCriticalSection (&images_mutex);
797 mono_image_loaded_by_guid (const char *guid)
801 EnterCriticalSection (&images_mutex);
802 res = g_hash_table_lookup (loaded_images_guid_hash, guid);
803 LeaveCriticalSection (&images_mutex);
808 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
810 MonoCLIImageInfo *iinfo;
814 if (!data || !data_len) {
816 *status = MONO_IMAGE_IMAGE_INVALID;
821 datac = g_try_malloc (data_len);
824 *status = MONO_IMAGE_ERROR_ERRNO;
827 memcpy (datac, data, data_len);
830 image = g_new0 (MonoImage, 1);
831 image->ref_count = 1;
832 image->raw_data = datac;
833 image->raw_data_len = data_len;
834 image->raw_data_allocated = need_copy;
835 image->name = g_strdup_printf ("data-%p", datac);
836 iinfo = g_new0 (MonoCLIImageInfo, 1);
837 image->image_info = iinfo;
839 return do_mono_image_load (image, status);
844 * @fname: filename that points to the module we want to open
845 * @status: An error condition is returned in this field
847 * Retuns: An open image of type %MonoImage or NULL on error.
848 * if NULL, then check the value of @status for details on the error
851 mono_image_open (const char *fname, MonoImageOpenStatus *status)
853 MonoImage *image, *image2;
854 const char *absfname;
856 g_return_val_if_fail (fname != NULL, NULL);
858 if (g_path_is_absolute (fname))
861 gchar *path = g_get_current_dir ();
862 absfname = g_build_filename (path, fname, NULL);
867 * The easiest solution would be to do all the loading inside the mutex,
868 * but that would lead to scalability problems. So we let the loading
869 * happen outside the mutex, and if multiple threads happen to load
870 * the same image, we discard all but the first copy.
872 EnterCriticalSection (&images_mutex);
873 image = g_hash_table_lookup (loaded_images_hash, absfname);
875 if (absfname != fname)
880 LeaveCriticalSection (&images_mutex);
883 LeaveCriticalSection (&images_mutex);
885 image = do_mono_image_open (fname, status);
889 EnterCriticalSection (&images_mutex);
890 image2 = g_hash_table_lookup (loaded_images_hash, fname);
892 /* Somebody else beat us to it */
893 image2->ref_count ++;
894 LeaveCriticalSection (&images_mutex);
895 mono_image_close (image);
899 g_hash_table_insert (loaded_images_hash, image->name, image);
900 if (image->assembly_name)
901 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image);
902 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
903 LeaveCriticalSection (&images_mutex);
909 free_hash_table (gpointer key, gpointer val, gpointer user_data)
911 g_hash_table_destroy ((GHashTable*)val);
915 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
917 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
922 * @image: The image file we wish to add a reference to
924 * Increases the reference count of an image.
927 mono_image_addref (MonoImage *image)
929 InterlockedIncrement (&image->ref_count);
934 * @image: The image file we wish to close
936 * Closes an image file, deallocates all memory consumed and
937 * unmaps all possible sections of the file
940 mono_image_close (MonoImage *image)
944 g_return_if_fail (image != NULL);
946 EnterCriticalSection (&images_mutex);
947 if (--image->ref_count) {
948 LeaveCriticalSection (&images_mutex);
951 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
952 if (image == image2) {
953 /* This is not true if we are called from mono_image_open () */
954 g_hash_table_remove (loaded_images_hash, image->name);
955 if (image->assembly_name)
956 g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);
957 g_hash_table_remove (loaded_images_guid_hash, image->guid);
958 /* Multiple images might have the same guid */
961 LeaveCriticalSection (&images_mutex);
965 if (image->raw_data_allocated)
966 g_free (image->raw_data);
968 g_free (image->name);
969 g_free (image->files);
971 g_hash_table_destroy (image->method_cache);
972 g_hash_table_destroy (image->class_cache);
973 g_hash_table_destroy (image->field_cache);
974 g_hash_table_destroy (image->array_cache);
975 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
976 g_hash_table_destroy (image->name_cache);
977 g_hash_table_destroy (image->native_wrapper_cache);
978 g_hash_table_destroy (image->managed_wrapper_cache);
979 g_hash_table_destroy (image->delegate_begin_invoke_cache);
980 g_hash_table_destroy (image->delegate_end_invoke_cache);
981 g_hash_table_destroy (image->delegate_invoke_cache);
982 g_hash_table_destroy (image->remoting_invoke_cache);
983 g_hash_table_destroy (image->runtime_invoke_cache);
984 g_hash_table_destroy (image->typespec_cache);
985 g_hash_table_destroy (image->generic_inst_cache);
986 g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
987 g_hash_table_destroy (image->memberref_signatures);
988 g_hash_table_foreach (image->helper_signatures, free_mr_signatures, NULL);
989 g_hash_table_destroy (image->helper_signatures);
991 if (image->raw_metadata != NULL)
992 mono_raw_buffer_free (image->raw_metadata);
994 if (image->image_info){
995 MonoCLIImageInfo *ii = image->image_info;
998 for (i = 0; i < ii->cli_section_count; i++){
999 if (!ii->cli_sections [i])
1001 mono_raw_buffer_free (ii->cli_sections [i]);
1003 if (ii->cli_section_tables)
1004 g_free (ii->cli_section_tables);
1005 if (ii->cli_sections)
1006 g_free (ii->cli_sections);
1007 g_free (image->image_info);
1014 * mono_image_strerror:
1015 * @status: an code indicating the result from a recent operation
1017 * Returns: a string describing the error
1020 mono_image_strerror (MonoImageOpenStatus status)
1025 case MONO_IMAGE_ERROR_ERRNO:
1026 return strerror (errno);
1027 case MONO_IMAGE_IMAGE_INVALID:
1028 return "File does not contain a valid CIL image";
1029 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1030 return "An assembly was referenced, but could not be found";
1032 return "Internal error";
1036 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1037 guint32 lang_id, gunichar2 *name,
1038 MonoPEResourceDirEntry *entry,
1039 MonoPEResourceDir *root, guint32 level)
1041 gboolean is_string=entry->name_is_string;
1043 /* Level 0 holds a directory entry for each type of resource
1044 * (identified by ID or name).
1046 * Level 1 holds a directory entry for each named resource
1047 * item, and each "anonymous" item of a particular type of
1050 * Level 2 holds a directory entry for each language pointing to
1055 if((is_string==FALSE && entry->name_offset!=res_id) ||
1056 (is_string==TRUE)) {
1059 } else if (level==1) {
1062 is_string==TRUE && name!=lookup (entry->name_offset)) {
1066 } else if (level==2) {
1067 if((is_string==FALSE && entry->name_offset!=lang_id) ||
1068 (is_string==TRUE)) {
1072 g_assert_not_reached ();
1075 if(entry->is_dir==TRUE) {
1076 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1077 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1080 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1082 for(i=0; i<entries; i++) {
1083 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1086 ret=mono_image_walk_resource_tree (info, res_id,
1097 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1104 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1106 MonoCLIImageInfo *info;
1107 MonoDotNetHeader *header;
1108 MonoPEDatadir *datadir;
1109 MonoPEDirEntry *rsrc;
1110 MonoPEResourceDir *resource_dir;
1111 MonoPEResourceDirEntry *res_entries;
1118 info=image->image_info;
1123 header=&info->cli_header;
1128 datadir=&header->datadir;
1133 rsrc=&datadir->pe_resource_table;
1138 resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
1139 if(resource_dir==NULL) {
1143 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1144 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1146 for(i=0; i<entries; i++) {
1147 MonoPEResourceDirEntry *entry=&res_entries[i];
1150 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1151 name, entry, resource_dir,
1162 mono_image_get_entry_point (MonoImage *image)
1164 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1168 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1170 MonoCLIImageInfo *iinfo = image->image_info;
1171 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1174 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1177 data = mono_image_rva_map (image, ch->ch_resources.rva);
1182 *size = read32 (data);
1188 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1190 char *base_dir, *name;
1192 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1196 if (fileidx < 1 || fileidx > t->rows)
1199 if (image->files && image->files [fileidx - 1])
1200 return image->files [fileidx - 1];
1203 image->files = g_new0 (MonoImage*, t->rows);
1205 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1206 fname = mono_metadata_string_heap (image, fname_id);
1207 base_dir = g_path_get_dirname (image->name);
1208 name = g_build_filename (base_dir, fname, NULL);
1209 res = mono_image_open (name, NULL);
1212 t = &res->tables [MONO_TABLE_MODULEREF];
1213 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1214 res->assembly = image->assembly;
1215 for (i = 0; i < t->rows; ++i) {
1216 if (res->modules [i] && !res->modules [i]->assembly)
1217 res->modules [i]->assembly = image->assembly;
1220 image->files [fileidx - 1] = res;
1228 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1230 MonoCLIImageInfo *iinfo = image->image_info;
1231 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1234 if (!de->size || !de->rva)
1236 data = mono_image_rva_map (image, de->rva);
1245 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1247 MonoCLIImageInfo *iinfo = image->image_info;
1248 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1249 const int top = iinfo->cli_section_count;
1250 MonoSectionTable *tables = iinfo->cli_section_tables;
1252 guint32 addr = de->rva;
1256 if (!de->size || !de->rva)
1258 for (i = 0; i < top; i++){
1259 if ((addr >= tables->st_virtual_address) &&
1260 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1261 return tables->st_raw_data_ptr +
1262 (addr - tables->st_virtual_address);
1271 mono_image_get_public_key (MonoImage *image, guint32 *size)
1275 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1277 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1280 pubkey = mono_metadata_blob_heap (image, tok);
1281 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1288 mono_image_get_name (MonoImage *image)
1290 return image->assembly_name;
1294 mono_image_get_filename (MonoImage *image)
1299 const MonoTableInfo*
1300 mono_image_get_table_info (MonoImage *image, int table_id)
1302 if (table_id < 0 || table_id >= 64)
1304 return &image->tables [table_id];
1308 mono_image_get_table_rows (MonoImage *image, int table_id)
1310 if (table_id < 0 || table_id >= 64)
1312 return image->tables [table_id].rows;
1316 mono_table_info_get_rows (MonoTableInfo *table)
1322 mono_image_get_assembly (MonoImage *image)
1324 return image->assembly;
1328 mono_image_is_dynamic (MonoImage *image)
1330 return image->dynamic;