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_cli_rva_map (MonoCLIImageInfo *iinfo, guint32 addr)
58 const int top = iinfo->cli_section_count;
59 MonoSectionTable *tables = iinfo->cli_section_tables;
62 for (i = 0; i < top; i++){
63 if ((addr >= tables->st_virtual_address) &&
64 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
65 return (char*)iinfo->cli_sections [i] +
66 (addr - tables->st_virtual_address);
76 * Initialize the global variables used by this module.
79 mono_images_init (void)
81 InitializeCriticalSection (&images_mutex);
83 loaded_images_hash = g_hash_table_new (g_str_hash, g_str_equal);
84 loaded_images_guid_hash = g_hash_table_new (g_str_hash, g_str_equal);
88 * mono_image_ensure_section_idx:
89 * @image: The image we are operating on
90 * @section: section number that we will load/map into memory
92 * This routine makes sure that we have an in-memory copy of
93 * an image section (.text, .rsrc, .data).
95 * Returns: TRUE on success
98 mono_image_ensure_section_idx (MonoImage *image, int section)
100 MonoCLIImageInfo *iinfo = image->image_info;
101 MonoSectionTable *sect;
104 g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
106 if (iinfo->cli_sections [section] != NULL)
109 sect = &iinfo->cli_section_tables [section];
111 writable = sect->st_flags & SECT_FLAGS_MEM_WRITE;
114 if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
116 /* FIXME: we ignore the writable flag since we don't patch the binary */
117 iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
120 iinfo->cli_sections [section] = mono_raw_buffer_load (
121 fileno (image->f), writable,
122 sect->st_raw_data_ptr, sect->st_raw_data_size);
124 if (iinfo->cli_sections [section] == NULL)
131 * mono_image_ensure_section:
132 * @image: The image we are operating on
133 * @section: section name that we will load/map into memory
135 * This routine makes sure that we have an in-memory copy of
136 * an image section (.text, .rsrc, .data).
138 * Returns: TRUE on success
141 mono_image_ensure_section (MonoImage *image, const char *section)
143 MonoCLIImageInfo *ii = image->image_info;
146 for (i = 0; i < ii->cli_section_count; i++){
147 if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
150 return mono_image_ensure_section_idx (image, i);
156 load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
158 const int top = iinfo->cli_header.coff.coff_sections;
161 iinfo->cli_section_count = top;
162 iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
163 iinfo->cli_sections = g_new0 (void *, top);
165 for (i = 0; i < top; i++){
166 MonoSectionTable *t = &iinfo->cli_section_tables [i];
169 if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
171 memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
172 offset += sizeof (MonoSectionTable);
174 if (fread (t, sizeof (MonoSectionTable), 1, image->f) != 1)
178 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
179 t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
180 t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
181 t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
182 t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
183 t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
184 t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
185 t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
186 t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
187 t->st_flags = GUINT32_FROM_LE (t->st_flags);
189 /* consistency checks here */
192 for (i = 0; i < top; i++)
193 if (!mono_image_ensure_section_idx (image, i))
200 load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
205 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_header.datadir.pe_cli_header.rva);
206 if (offset == INVALID_ADDRESS)
210 if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
212 memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
214 if (fseek (image->f, offset, SEEK_SET) != 0)
217 if ((n = fread (&iinfo->cli_cli_header, sizeof (MonoCLIHeader), 1, image->f)) != 1)
221 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
222 #define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
223 #define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
224 #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
225 SWAP32 (iinfo->cli_cli_header.ch_size);
226 SWAP32 (iinfo->cli_cli_header.ch_flags);
227 SWAP32 (iinfo->cli_cli_header.ch_entry_point);
228 SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
229 SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
230 SWAPPDE (iinfo->cli_cli_header.ch_metadata);
231 SWAPPDE (iinfo->cli_cli_header.ch_resources);
232 SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
233 SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
234 SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
235 SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
236 SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
237 SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
238 SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
239 SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
240 SWAPPDE (iinfo->cli_cli_header.ch_module_image);
241 SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
242 SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
243 SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
244 SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
249 /* Catch new uses of the fields that are supposed to be zero */
251 if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
252 (iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
253 (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
254 (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
255 (iinfo->cli_cli_header.ch_module_image.rva != 0) ||
256 (iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
257 (iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
258 (iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
259 (iinfo->cli_cli_header.ch_ip_map.rva != 0)){
262 * No need to scare people who are testing this, I am just
263 * labelling this as a LAMESPEC
265 /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
273 load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
275 guint32 offset, size;
281 offset = mono_cli_rva_image_map (iinfo, iinfo->cli_cli_header.ch_metadata.rva);
282 if (offset == INVALID_ADDRESS)
285 size = iinfo->cli_cli_header.ch_metadata.size;
288 if (offset + size > image->raw_data_len)
290 image->raw_metadata = image->raw_data + offset;
292 image->raw_metadata = mono_raw_buffer_load (fileno (image->f), FALSE, offset, size);
293 if (image->raw_metadata == NULL)
297 ptr = image->raw_metadata;
299 if (strncmp (ptr, "BSJB", 4) == 0){
300 guint32 version_string_len;
303 version_string_len = read32 (ptr);
305 image->version = g_strndup (ptr, version_string_len);
306 ptr += version_string_len;
307 pad = ptr - image->raw_metadata;
309 ptr += 4 - (pad % 4);
313 /* skip over flags */
316 streams = read16 (ptr);
319 for (i = 0; i < streams; i++){
320 if (strncmp (ptr + 8, "#~", 3) == 0){
321 image->heap_tables.data = image->raw_metadata + read32 (ptr);
322 image->heap_tables.size = read32 (ptr + 4);
324 } else if (strncmp (ptr + 8, "#Strings", 9) == 0){
325 image->heap_strings.data = image->raw_metadata + read32 (ptr);
326 image->heap_strings.size = read32 (ptr + 4);
328 } else if (strncmp (ptr + 8, "#US", 4) == 0){
329 image->heap_us.data = image->raw_metadata + read32 (ptr);
330 image->heap_us.size = read32 (ptr + 4);
332 } else if (strncmp (ptr + 8, "#Blob", 6) == 0){
333 image->heap_blob.data = image->raw_metadata + read32 (ptr);
334 image->heap_blob.size = read32 (ptr + 4);
336 } else if (strncmp (ptr + 8, "#GUID", 6) == 0){
337 image->heap_guid.data = image->raw_metadata + read32 (ptr);
338 image->heap_guid.size = read32 (ptr + 4);
340 } else if (strncmp (ptr + 8, "#-", 3) == 0) {
341 g_print ("Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
344 g_message ("Unknown heap type: %s\n", ptr + 8);
345 ptr += 8 + strlen (ptr + 8) + 1;
347 pad = ptr - image->raw_metadata;
349 ptr += 4 - (pad % 4);
352 g_assert (image->heap_guid.data);
353 g_assert (image->heap_guid.size >= 16);
355 image->guid = mono_guid_to_string (image->heap_guid.data);
361 * Load representation of logical metadata tables, from the "#~" stream
364 load_tables (MonoImage *image)
366 const char *heap_tables = image->heap_tables.data;
368 guint64 valid_mask, sorted_mask;
369 int valid = 0, table;
372 heap_sizes = heap_tables [6];
373 image->idx_string_wide = ((heap_sizes & 0x01) == 1);
374 image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
375 image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
377 valid_mask = read64 (heap_tables + 8);
378 sorted_mask = read64 (heap_tables + 16);
379 rows = (const guint32 *) (heap_tables + 24);
381 for (table = 0; table < 64; table++){
382 if ((valid_mask & ((guint64) 1 << table)) == 0){
383 image->tables [table].rows = 0;
386 if (table > MONO_TABLE_LAST) {
387 g_warning("bits in valid must be zero above 0x2d (II - 23.1.6)");
389 /*if ((sorted_mask & ((guint64) 1 << table)) == 0){
390 g_print ("table %s (0x%02x) is sorted\n", mono_meta_table_name (table), table);
392 image->tables [table].rows = read32 (rows);
397 image->tables_base = (heap_tables + 24) + (4 * valid);
399 /* They must be the same */
400 g_assert ((const void *) image->tables_base == (const void *) rows);
402 mono_metadata_compute_table_bases (image);
407 load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
409 if (!load_metadata_ptrs (image, iinfo))
412 return load_tables (image);
416 mono_image_add_to_name_cache (MonoImage *image, const char *nspace,
417 const char *name, guint32 index)
419 GHashTable *nspace_table;
420 GHashTable *name_cache = image->name_cache;
422 if (!(nspace_table = g_hash_table_lookup (name_cache, nspace))) {
423 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
424 g_hash_table_insert (name_cache, (char *)nspace, (char *)nspace_table);
426 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (index));
430 load_modules (MonoImage *image, MonoImageOpenStatus *status)
439 t = &image->tables [MONO_TABLE_MODULEREF];
440 image->modules = g_new0 (MonoImage *, t->rows);
441 base_dir = g_path_get_dirname (image->name);
442 for (i = 0; i < t->rows; i++){
445 guint32 cols [MONO_MODULEREF_SIZE];
447 mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
448 name = mono_metadata_string_heap (image, cols [MONO_MODULEREF_NAME]);
449 module_ref = g_build_filename (base_dir, name, NULL);
450 image->modules [i] = mono_image_open (module_ref, status);
451 if (image->modules [i]) {
452 /* g_print ("loaded module %s from %s (%p)\n", module_ref, image->name, image->assembly); */
455 * FIXME: what do we do here? it could be a native dll...
456 * We should probably do lazy-loading of modules.
459 *status = MONO_IMAGE_OK;
467 load_class_names (MonoImage *image)
469 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
470 guint32 cols [MONO_TYPEDEF_SIZE];
473 guint32 i, visib, nspace_index;
474 GHashTable *name_cache2, *nspace_table;
476 /* Temporary hash table to avoid lookups in the nspace_table */
477 name_cache2 = g_hash_table_new (NULL, NULL);
479 for (i = 1; i <= t->rows; ++i) {
480 mono_metadata_decode_row (t, i - 1, cols, MONO_TYPEDEF_SIZE);
481 /* nested types are accessed from the nesting name */
482 visib = cols [MONO_TYPEDEF_FLAGS] & TYPE_ATTRIBUTE_VISIBILITY_MASK;
483 if (visib > TYPE_ATTRIBUTE_PUBLIC && visib <= TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
485 name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
486 nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
488 nspace_index = cols [MONO_TYPEDEF_NAMESPACE];
489 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
491 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
492 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
493 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
496 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (i));
499 /* Load type names from EXPORTEDTYPES table */
501 MonoTableInfo *t = &image->tables [MONO_TABLE_EXPORTEDTYPE];
502 guint32 cols [MONO_EXP_TYPE_SIZE];
505 for (i = 0; i < t->rows; ++i) {
506 mono_metadata_decode_row (t, i, cols, MONO_EXP_TYPE_SIZE);
507 name = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAME]);
508 nspace = mono_metadata_string_heap (image, cols [MONO_EXP_TYPE_NAMESPACE]);
510 nspace_index = cols [MONO_EXP_TYPE_NAMESPACE];
511 nspace_table = g_hash_table_lookup (name_cache2, GUINT_TO_POINTER (nspace_index));
513 nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
514 g_hash_table_insert (image->name_cache, (char*)nspace, nspace_table);
515 g_hash_table_insert (name_cache2, GUINT_TO_POINTER (nspace_index),
518 g_hash_table_insert (nspace_table, (char *) name, GUINT_TO_POINTER (mono_metadata_make_token (MONO_TABLE_EXPORTEDTYPE, i + 1)));
522 g_hash_table_destroy (name_cache2);
526 register_guid (gpointer key, gpointer value, gpointer user_data)
528 MonoImage *image = (MonoImage*)value;
530 if (!g_hash_table_lookup (loaded_images_guid_hash, image))
531 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
535 build_guid_table (void)
537 g_hash_table_foreach (loaded_images_hash, register_guid, NULL);
541 mono_image_init (MonoImage *image)
543 image->method_cache = g_hash_table_new (NULL, NULL);
544 image->class_cache = g_hash_table_new (NULL, NULL);
545 image->field_cache = g_hash_table_new (NULL, NULL);
546 image->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
547 image->array_cache = g_hash_table_new (NULL, NULL);
549 image->delegate_begin_invoke_cache =
550 g_hash_table_new ((GHashFunc)mono_signature_hash,
551 (GCompareFunc)mono_metadata_signature_equal);
552 image->delegate_end_invoke_cache =
553 g_hash_table_new ((GHashFunc)mono_signature_hash,
554 (GCompareFunc)mono_metadata_signature_equal);
555 image->delegate_invoke_cache =
556 g_hash_table_new ((GHashFunc)mono_signature_hash,
557 (GCompareFunc)mono_metadata_signature_equal);
558 image->runtime_invoke_cache =
559 g_hash_table_new ((GHashFunc)mono_signature_hash,
560 (GCompareFunc)mono_metadata_signature_equal);
562 image->managed_wrapper_cache = g_hash_table_new (NULL, NULL);
563 image->native_wrapper_cache = g_hash_table_new (NULL, NULL);
564 image->remoting_invoke_cache = g_hash_table_new (NULL, NULL);
565 image->synchronized_cache = g_hash_table_new (NULL, NULL);
567 image->typespec_cache = g_hash_table_new (NULL, NULL);
568 image->memberref_signatures = g_hash_table_new (NULL, NULL);
570 image->generic_inst_cache =
571 g_hash_table_new ((GHashFunc)mono_metadata_generic_inst_hash,
572 (GCompareFunc)mono_metadata_generic_inst_equal);
576 do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status)
578 MonoCLIImageInfo *iinfo;
579 MonoDotNetHeader *header;
580 MonoMSDOSHeader msdos;
584 mono_image_init (image);
586 iinfo = image->image_info;
587 header = &iinfo->cli_header;
590 *status = MONO_IMAGE_IMAGE_INVALID;
593 if (offset + sizeof (msdos) > image->raw_data_len)
595 memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
597 if (fread (&msdos, sizeof (msdos), 1, image->f) != 1)
601 if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
604 msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
606 if (msdos.pe_offset != sizeof (msdos)) {
608 fseek (image->f, msdos.pe_offset, SEEK_SET);
610 offset = msdos.pe_offset;
613 if (offset + sizeof (MonoDotNetHeader) > image->raw_data_len)
615 memcpy (header, image->raw_data + offset, sizeof (MonoDotNetHeader));
616 offset += sizeof (MonoDotNetHeader);
618 if ((n = fread (header, sizeof (MonoDotNetHeader), 1, image->f)) != 1)
622 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
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)
626 SWAP32 (header->coff.coff_time);
627 SWAP32 (header->coff.coff_symptr);
628 SWAP32 (header->coff.coff_symcount);
629 SWAP16 (header->coff.coff_machine);
630 SWAP16 (header->coff.coff_sections);
631 SWAP16 (header->coff.coff_opt_header_size);
632 SWAP16 (header->coff.coff_attributes);
634 SWAP32 (header->pe.pe_code_size);
635 SWAP32 (header->pe.pe_data_size);
636 SWAP32 (header->pe.pe_uninit_data_size);
637 SWAP32 (header->pe.pe_rva_entry_point);
638 SWAP32 (header->pe.pe_rva_code_base);
639 SWAP32 (header->pe.pe_rva_data_base);
640 SWAP16 (header->pe.pe_magic);
642 /* MonoPEHeaderNT: not used yet */
643 SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
644 SWAP32 (header->nt.pe_section_align); /* must be 8192 */
645 SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
646 SWAP16 (header->nt.pe_os_major); /* must be 4 */
647 SWAP16 (header->nt.pe_os_minor); /* must be 0 */
648 SWAP16 (header->nt.pe_user_major);
649 SWAP16 (header->nt.pe_user_minor);
650 SWAP16 (header->nt.pe_subsys_major);
651 SWAP16 (header->nt.pe_subsys_minor);
652 SWAP32 (header->nt.pe_reserved_1);
653 SWAP32 (header->nt.pe_image_size);
654 SWAP32 (header->nt.pe_header_size);
655 SWAP32 (header->nt.pe_checksum);
656 SWAP16 (header->nt.pe_subsys_required);
657 SWAP16 (header->nt.pe_dll_flags);
658 SWAP32 (header->nt.pe_stack_reserve);
659 SWAP32 (header->nt.pe_stack_commit);
660 SWAP32 (header->nt.pe_heap_reserve);
661 SWAP32 (header->nt.pe_heap_commit);
662 SWAP32 (header->nt.pe_loader_flags);
663 SWAP32 (header->nt.pe_data_dir_count);
665 /* MonoDotNetHeader: mostly unused */
666 SWAPPDE (header->datadir.pe_export_table);
667 SWAPPDE (header->datadir.pe_import_table);
668 SWAPPDE (header->datadir.pe_resource_table);
669 SWAPPDE (header->datadir.pe_exception_table);
670 SWAPPDE (header->datadir.pe_certificate_table);
671 SWAPPDE (header->datadir.pe_reloc_table);
672 SWAPPDE (header->datadir.pe_debug);
673 SWAPPDE (header->datadir.pe_copyright);
674 SWAPPDE (header->datadir.pe_global_ptr);
675 SWAPPDE (header->datadir.pe_tls_table);
676 SWAPPDE (header->datadir.pe_load_config_table);
677 SWAPPDE (header->datadir.pe_bound_import);
678 SWAPPDE (header->datadir.pe_iat);
679 SWAPPDE (header->datadir.pe_delay_import_desc);
680 SWAPPDE (header->datadir.pe_cli_header);
681 SWAPPDE (header->datadir.pe_reserved);
688 if (header->coff.coff_machine != 0x14c)
691 if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
694 if (header->pesig[0] != 'P' || header->pesig[1] != 'E' || header->pe.pe_magic != 0x10B)
699 * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
700 * which produces binaries with 7.0. From Sergey:
702 * The reason is that MSVC7 uses traditional compile/link
703 * sequence for CIL executables, and VS.NET (and Framework
704 * SDK) includes linker version 7, that puts 7.0 in this
705 * field. That's why it's currently not possible to load VC
706 * binaries with Mono. This field is pretty much meaningless
707 * anyway (what linker?).
709 if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
714 * FIXME: byte swap all addresses here for header.
717 if (!load_section_tables (image, iinfo, offset))
720 /* Load the CLI header */
721 if (!load_cli_header (image, iinfo))
724 if (!load_metadata (image, iinfo))
727 load_class_names (image);
729 /* modules don't have an assembly table row */
730 if (image->tables [MONO_TABLE_ASSEMBLY].rows)
731 image->assembly_name = mono_metadata_string_heap (image,
732 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
733 0, MONO_ASSEMBLY_NAME));
735 image->module_name = mono_metadata_string_heap (image,
736 mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
737 0, MONO_MODULE_NAME));
739 load_modules (image, status);
742 *status = MONO_IMAGE_OK;
749 mono_image_close (image);
754 do_mono_image_open (const char *fname, MonoImageOpenStatus *status)
756 MonoCLIImageInfo *iinfo;
760 if ((filed = fopen (fname, "rb")) == NULL){
762 *status = MONO_IMAGE_ERROR_ERRNO;
766 image = g_new0 (MonoImage, 1);
767 image->ref_count = 1;
769 iinfo = g_new0 (MonoCLIImageInfo, 1);
770 image->image_info = iinfo;
772 if (g_path_is_absolute (fname))
773 image->name = g_strdup (fname);
775 gchar *path = g_get_current_dir ();
776 image->name = g_build_filename (path, fname, NULL);
780 return do_mono_image_load (image, status);
784 mono_image_loaded (const char *name)
788 EnterCriticalSection (&images_mutex);
789 res = g_hash_table_lookup (loaded_images_hash, name);
790 LeaveCriticalSection (&images_mutex);
795 mono_image_loaded_by_guid (const char *guid)
799 EnterCriticalSection (&images_mutex);
800 res = g_hash_table_lookup (loaded_images_guid_hash, guid);
801 LeaveCriticalSection (&images_mutex);
806 mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
808 MonoCLIImageInfo *iinfo;
812 if (!data || !data_len) {
814 *status = MONO_IMAGE_IMAGE_INVALID;
819 datac = g_try_malloc (data_len);
822 *status = MONO_IMAGE_ERROR_ERRNO;
825 memcpy (datac, data, data_len);
828 image = g_new0 (MonoImage, 1);
829 image->ref_count = 1;
830 image->raw_data = datac;
831 image->raw_data_len = data_len;
832 image->raw_data_allocated = need_copy;
833 image->name = g_strdup_printf ("data-%p", datac);
834 iinfo = g_new0 (MonoCLIImageInfo, 1);
835 image->image_info = iinfo;
837 return do_mono_image_load (image, status);
842 * @fname: filename that points to the module we want to open
843 * @status: An error condition is returned in this field
845 * Retuns: An open image of type %MonoImage or NULL on error.
846 * if NULL, then check the value of @status for details on the error
849 mono_image_open (const char *fname, MonoImageOpenStatus *status)
851 MonoImage *image, *image2;
852 const char *absfname;
854 g_return_val_if_fail (fname != NULL, NULL);
856 if (g_path_is_absolute (fname))
859 gchar *path = g_get_current_dir ();
860 absfname = g_build_filename (path, fname, NULL);
865 * The easiest solution would be to do all the loading inside the mutex,
866 * but that would lead to scalability problems. So we let the loading
867 * happen outside the mutex, and if multiple threads happen to load
868 * the same image, we discard all but the first copy.
870 EnterCriticalSection (&images_mutex);
871 image = g_hash_table_lookup (loaded_images_hash, absfname);
873 if (absfname != fname)
878 LeaveCriticalSection (&images_mutex);
881 LeaveCriticalSection (&images_mutex);
883 image = do_mono_image_open (fname, status);
887 EnterCriticalSection (&images_mutex);
888 image2 = g_hash_table_lookup (loaded_images_hash, fname);
890 /* Somebody else beat us to it */
891 image2->ref_count ++;
892 LeaveCriticalSection (&images_mutex);
893 mono_image_close (image);
897 g_hash_table_insert (loaded_images_hash, image->name, image);
898 if (image->assembly_name)
899 g_hash_table_insert (loaded_images_hash, (char *) image->assembly_name, image);
900 g_hash_table_insert (loaded_images_guid_hash, image->guid, image);
901 LeaveCriticalSection (&images_mutex);
907 free_hash_table (gpointer key, gpointer val, gpointer user_data)
909 g_hash_table_destroy ((GHashTable*)val);
913 free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
915 mono_metadata_free_method_signature ((MonoMethodSignature*)val);
920 * @image: The image file we wish to add a reference to
922 * Increases the reference count of an image.
925 mono_image_addref (MonoImage *image)
927 InterlockedIncrement (&image->ref_count);
932 * @image: The image file we wish to close
934 * Closes an image file, deallocates all memory consumed and
935 * unmaps all possible sections of the file
938 mono_image_close (MonoImage *image)
942 g_return_if_fail (image != NULL);
944 EnterCriticalSection (&images_mutex);
945 if (--image->ref_count) {
946 LeaveCriticalSection (&images_mutex);
949 image2 = g_hash_table_lookup (loaded_images_hash, image->name);
950 if (image == image2) {
951 /* This is not true if we are called from mono_image_open () */
952 g_hash_table_remove (loaded_images_hash, image->name);
953 if (image->assembly_name)
954 g_hash_table_remove (loaded_images_hash, (char *) image->assembly_name);
955 g_hash_table_remove (loaded_images_guid_hash, image->guid);
956 /* Multiple images might have the same guid */
959 LeaveCriticalSection (&images_mutex);
963 if (image->raw_data_allocated)
964 g_free (image->raw_data);
966 g_free (image->name);
967 g_free (image->files);
969 g_hash_table_destroy (image->method_cache);
970 g_hash_table_destroy (image->class_cache);
971 g_hash_table_destroy (image->field_cache);
972 g_hash_table_destroy (image->array_cache);
973 g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
974 g_hash_table_destroy (image->name_cache);
975 g_hash_table_destroy (image->native_wrapper_cache);
976 g_hash_table_destroy (image->managed_wrapper_cache);
977 g_hash_table_destroy (image->delegate_begin_invoke_cache);
978 g_hash_table_destroy (image->delegate_end_invoke_cache);
979 g_hash_table_destroy (image->delegate_invoke_cache);
980 g_hash_table_destroy (image->remoting_invoke_cache);
981 g_hash_table_destroy (image->runtime_invoke_cache);
982 g_hash_table_destroy (image->typespec_cache);
983 g_hash_table_destroy (image->generic_inst_cache);
984 g_hash_table_foreach (image->memberref_signatures, free_mr_signatures, NULL);
985 g_hash_table_destroy (image->memberref_signatures);
987 if (image->raw_metadata != NULL)
988 mono_raw_buffer_free (image->raw_metadata);
990 if (image->image_info){
991 MonoCLIImageInfo *ii = image->image_info;
994 for (i = 0; i < ii->cli_section_count; i++){
995 if (!ii->cli_sections [i])
997 mono_raw_buffer_free (ii->cli_sections [i]);
999 if (ii->cli_section_tables)
1000 g_free (ii->cli_section_tables);
1001 if (ii->cli_sections)
1002 g_free (ii->cli_sections);
1003 g_free (image->image_info);
1010 * mono_image_strerror:
1011 * @status: an code indicating the result from a recent operation
1013 * Returns: a string describing the error
1016 mono_image_strerror (MonoImageOpenStatus status)
1021 case MONO_IMAGE_ERROR_ERRNO:
1022 return strerror (errno);
1023 case MONO_IMAGE_IMAGE_INVALID:
1024 return "File does not contain a valid CIL image";
1025 case MONO_IMAGE_MISSING_ASSEMBLYREF:
1026 return "An assembly was referenced, but could not be found";
1028 return "Internal error";
1032 mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
1033 guint32 lang_id, gunichar2 *name,
1034 MonoPEResourceDirEntry *entry,
1035 MonoPEResourceDir *root, guint32 level)
1037 gboolean is_string=entry->name_is_string;
1039 /* Level 0 holds a directory entry for each type of resource
1040 * (identified by ID or name).
1042 * Level 1 holds a directory entry for each named resource
1043 * item, and each "anonymous" item of a particular type of
1046 * Level 2 holds a directory entry for each language pointing to
1051 if((is_string==FALSE && entry->name_offset!=res_id) ||
1052 (is_string==TRUE)) {
1055 } else if (level==1) {
1058 is_string==TRUE && name!=lookup (entry->name_offset)) {
1062 } else if (level==2) {
1063 if((is_string==FALSE && entry->name_offset!=lang_id) ||
1064 (is_string==TRUE)) {
1068 g_assert_not_reached ();
1071 if(entry->is_dir==TRUE) {
1072 MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+entry->dir_offset);
1073 MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
1076 entries=res_dir->res_named_entries + res_dir->res_id_entries;
1078 for(i=0; i<entries; i++) {
1079 MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
1082 ret=mono_image_walk_resource_tree (info, res_id,
1093 MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+entry->dir_offset);
1100 mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
1102 MonoCLIImageInfo *info;
1103 MonoDotNetHeader *header;
1104 MonoPEDatadir *datadir;
1105 MonoPEDirEntry *rsrc;
1106 MonoPEResourceDir *resource_dir;
1107 MonoPEResourceDirEntry *res_entries;
1114 info=image->image_info;
1119 header=&info->cli_header;
1124 datadir=&header->datadir;
1129 rsrc=&datadir->pe_resource_table;
1134 resource_dir=(MonoPEResourceDir *)mono_cli_rva_map (info, rsrc->rva);
1135 if(resource_dir==NULL) {
1139 entries=resource_dir->res_named_entries + resource_dir->res_id_entries;
1140 res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
1142 for(i=0; i<entries; i++) {
1143 MonoPEResourceDirEntry *entry=&res_entries[i];
1146 ret=mono_image_walk_resource_tree (info, res_id, lang_id,
1147 name, entry, resource_dir,
1158 mono_image_get_entry_point (MonoImage *image)
1160 return ((MonoCLIImageInfo*)image->image_info)->cli_cli_header.ch_entry_point;
1164 mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
1166 MonoCLIImageInfo *iinfo = image->image_info;
1167 MonoCLIHeader *ch = &iinfo->cli_cli_header;
1170 if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
1173 data = mono_cli_rva_map (iinfo, ch->ch_resources.rva);
1178 *size = read32 (data);
1184 mono_image_load_file_for_image (MonoImage *image, int fileidx)
1186 char *base_dir, *name;
1188 MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
1192 if (fileidx < 1 || fileidx > t->rows)
1195 if (image->files && image->files [fileidx - 1])
1196 return image->files [fileidx - 1];
1199 image->files = g_new0 (MonoImage*, t->rows);
1201 fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
1202 fname = mono_metadata_string_heap (image, fname_id);
1203 base_dir = g_path_get_dirname (image->name);
1204 name = g_build_filename (base_dir, fname, NULL);
1205 res = mono_image_open (name, NULL);
1208 t = &res->tables [MONO_TABLE_MODULEREF];
1209 /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
1210 res->assembly = image->assembly;
1211 for (i = 0; i < t->rows; ++i) {
1212 if (res->modules [i] && !res->modules [i]->assembly)
1213 res->modules [i]->assembly = image->assembly;
1216 image->files [fileidx - 1] = res;
1224 mono_image_get_strong_name (MonoImage *image, guint32 *size)
1226 MonoCLIImageInfo *iinfo = image->image_info;
1227 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1230 if (!de->size || !de->rva)
1232 data = mono_cli_rva_map (iinfo, de->rva);
1241 mono_image_strong_name_position (MonoImage *image, guint32 *size)
1243 MonoCLIImageInfo *iinfo = image->image_info;
1244 MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
1245 const int top = iinfo->cli_section_count;
1246 MonoSectionTable *tables = iinfo->cli_section_tables;
1248 guint32 addr = de->rva;
1252 if (!de->size || !de->rva)
1254 for (i = 0; i < top; i++){
1255 if ((addr >= tables->st_virtual_address) &&
1256 (addr < tables->st_virtual_address + tables->st_raw_data_size)){
1257 return tables->st_raw_data_ptr +
1258 (addr - tables->st_virtual_address);
1267 mono_image_get_public_key (MonoImage *image, guint32 *size)
1271 if (image->tables [MONO_TABLE_ASSEMBLY].rows != 1)
1273 tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
1276 pubkey = mono_metadata_blob_heap (image, tok);
1277 len = mono_metadata_decode_blob_size (pubkey, &pubkey);
1284 mono_image_get_name (MonoImage *image)
1286 return image->assembly_name;
1290 mono_image_get_filename (MonoImage *image)
1295 const MonoTableInfo*
1296 mono_image_get_table_info (MonoImage *image, int table_id)
1298 if (table_id < 0 || table_id >= 64)
1300 return &image->tables [table_id];
1304 mono_image_get_table_rows (MonoImage *image, int table_id)
1306 if (table_id < 0 || table_id >= 64)
1308 return image->tables [table_id].rows;
1312 mono_table_info_get_rows (MonoTableInfo *table)
1318 mono_image_get_assembly (MonoImage *image)
1320 return image->assembly;
1324 mono_image_is_dynamic (MonoImage *image)
1326 return image->dynamic;
1330 mono_image_rva_map (MonoImage *image, guint32 rva)
1332 return mono_cli_rva_map (image->image_info, rva);